123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import { EntityType, Entity } from "../packages/entity";
- import { Attrib, ShapeType } from "../type";
- import { inRevise } from "./public";
- import { getChangeAllPoart } from "./util";
- const getExtendsProps = (parent: Entity<any, any>) => {
- return parent
- ? {
- reactive: parent.props.reactive,
- readonly: parent.props.reactive,
- }
- : {};
- };
- export const entityFactory = <
- T extends Attrib,
- S extends ShapeType,
- C extends EntityType<T, S, { attrib: T }>
- >(
- attrib: T,
- Type: C,
- parent?: Entity<any, any>,
- extra?: (self: InstanceType<C>) => void
- ) => {
- const entity = new Type({
- attrib,
- ...getExtendsProps(parent),
- }) as InstanceType<C>;
- 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<T extends Attrib, E extends Entity<T, any>> = (
- attribs: T[] | T
- ) => IncEntitys<T, E>;
- export type IncEntitys<T extends Attrib, E extends Entity<T, any>> = {
- adds: E[];
- dels: E[];
- upds: E[];
- };
- // 增量工厂
- export const incEntitysFactoryGenerate = <
- T extends Attrib,
- S extends ShapeType,
- C extends EntityType<T, S, { attrib: T }>
- >(
- Type: C,
- parent?: Entity<any, any>,
- extra?: (self: InstanceType<C>) => void
- ) => {
- let oldAttribs: T[] = [];
- const findAttrib = (attribs: T[], id: Attrib["id"]) =>
- attribs.find((attrib) => attrib.id === id);
- const cache: { [key in Attrib["id"]]: InstanceType<C> } = {};
- 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,
- };
- };
- };
|