import { EntityType, Entity } from "../packages/entity"; import { Attrib, ShapeType } from "../type"; import { inRevise } from "./public"; import { getChangeAllPoart } from "./util"; const getExtendsProps = (parent: Entity) => { return parent ? { reactive: parent.props.reactive, readonly: parent.props.reactive, } : {}; }; export const entityFactory = < T extends Attrib, S extends ShapeType, C extends EntityType >( attrib: T, Type: C, parent?: Entity, extra?: (self: InstanceType) => void ) => { const entity = new Type({ attrib, ...getExtendsProps(parent), }) as InstanceType; extra && extra(entity); if (parent) { entity.container = parent.container; entity.setParent(parent); } entity.init(); entity.mount(entity.teleport); if (parent.isMounted) { entity.mounted(); } return entity; }; export type IncEntitysFactory> = ( attribs: T[] | T ) => IncEntitys; export type IncEntitys> = { adds: E[]; dels: E[]; upds: E[]; }; // 增量工厂 export const incEntitysFactoryGenerate = < T extends Attrib, S extends ShapeType, C extends EntityType >( Type: C, parent?: Entity, extra?: (self: InstanceType) => void ) => { let oldAttribs: T[] = []; const findAttrib = (attribs: T[], id: Attrib["id"]) => attribs.find((attrib) => attrib.id === id); const cache: { [key in Attrib["id"]]: InstanceType } = {}; const destory = (id: Attrib["id"]) => { const delEntity = cache[id]; delEntity.destory(); delete cache[id]; return delEntity; }; const add = (attrib: T) => { const addEntity = entityFactory(attrib, Type, parent, extra); cache[attrib.id] = addEntity; return addEntity; }; return (attribsRaw: T | T[]) => { const attribs = Array.isArray(attribsRaw) ? attribsRaw : [attribsRaw]; const { addPort, delPort, changePort } = getChangeAllPoart( attribs, oldAttribs ); const dels = delPort.map(destory); const adds = addPort.map((id) => add(findAttrib(attribs, id))); const upds = changePort.map((id) => { const newAttrib = findAttrib(attribs, id); if (inRevise(newAttrib, cache[id].attrib)) { console.log("setAttrib"); cache[id].setAttrib(findAttrib(attribs, id)); } return cache[id]; }); oldAttribs = [...attribs]; return { adds, dels, upds, }; }; };