import { connect, IViewInstance, ChangeOptions } from '@goldfishjs/reactive'; import ComponentStore from './ComponentStore'; import attachLogic from './attachLogic'; import getMiniDataSetter from './getMiniDataSetter'; export const isComponent2 = typeof my !== 'undefined' ? my.canIUse('component2') : false; export type ComponentInstance
= { store: CS } & tinyapp.IComponentInstance
&
Omit = ThisType ;
export default function createTinyappComponent<
P,
CS extends ComponentStore ,
D = any,
M extends tinyapp.IComponentMethods = tinyapp.IComponentMethods,
>(
storeClass: new () => CS,
componentOptions: ComponentOptions & { onError?: (e: any) => void } = {},
options?: {
beforeCreateStore?: (view: ComponentInstance ) => void;
afterCreateStore?: (view: ComponentInstance , store: CS) => void;
},
): tinyapp.ComponentOptions {
const beforeCreateStore = options && options.beforeCreateStore;
const afterCreateStore = options && options.afterCreateStore;
const enterKey = isComponent2 ? 'onInit' : 'didMount';
const leaveKey = 'didUnmount';
connect(
componentOptions,
enterKey,
leaveKey,
function (
this: tinyapp.IComponentInstance & {
setData: tinyapp.SetDataMethod );
const store = new storeClass();
afterCreateStore && afterCreateStore(instance as ComponentInstance , store);
return store;
},
{
onError: componentOptions.onError,
},
);
function syncProps(lifeCycleName: 'onInit' | 'didMount' | 'deriveDataFromProps' | 'didUpdate') {
return function (this: ComponentInstance , ...args: any[]) {
const nextProps: P = {
onInit: this.props,
didMount: this.props,
deriveDataFromProps: args[0],
didUpdate: this.props,
}[lifeCycleName];
for (const key in nextProps) {
if (key in this.store.props) {
this.store.props[key] = nextProps[key];
}
}
};
}
attachLogic ) {
this.store && (this.store.isSyncDataSafe = false);
},
);
return componentOptions;
}