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 & M; export type ComponentOptions = ThisType> & tinyapp.ComponentOptions; 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; store: CS; }, obj: any, keyPathList: (string | number)[], newV: any, oldV: any, options?: ChangeOptions, ) { if (!this.store.isSyncDataSafe) { return; } const miniDataSetter = getMiniDataSetter(); miniDataSetter.set(this, obj, keyPathList, newV, oldV, options); }, instance => { beforeCreateStore && beforeCreateStore(instance as ComponentInstance); 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>[typeof enterKey]>( componentOptions, enterKey, 'after', syncProps(enterKey), ); const refreshKey = isComponent2 ? 'deriveDataFromProps' : 'didUpdate'; attachLogic>[typeof refreshKey]>( componentOptions, refreshKey, 'after', syncProps(refreshKey), ); attachLogic>[typeof leaveKey]>( componentOptions, leaveKey, 'after', function (this: ComponentInstance) { this.store && (this.store.isSyncDataSafe = false); }, ); return componentOptions; }