entity-group.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { Group } from "konva/lib/Group";
  2. import {
  3. Entity,
  4. EntityProps,
  5. EntityShape,
  6. EntityTree,
  7. EntityType,
  8. } from "./entity";
  9. import { IncEntitysFactory, incEntitysFactoryGenerate } from "./entity-factory";
  10. type Data<T extends EntityType> = T extends EntityType<infer D> ? D : never;
  11. export class EntityGroup<
  12. T extends EntityType<any, EntityShape, EntityTree<any, any>>
  13. > extends Entity<
  14. Data<T>[],
  15. Group,
  16. EntityTree<EntityGroup<T>, InstanceType<T>>
  17. > {
  18. private incFactory: IncEntitysFactory<EntityGroup<T>, Data<T>, T>;
  19. constructor({ type, ...props }: EntityProps<Data<T>[]> & { type: T }) {
  20. super(props);
  21. this.incFactory = incEntitysFactoryGenerate(type, this as EntityGroup<T>);
  22. this.diffRedraw();
  23. }
  24. diffRedraw() {
  25. const { adds } = this.incFactory(this.attrib);
  26. adds.forEach((add) => {
  27. add.bus.on("destroyed", () => {
  28. const ndx = this.attrib.indexOf(add.attrib);
  29. if (~ndx) {
  30. this.attrib.splice(ndx, 1);
  31. }
  32. });
  33. add.bus.on("updateAttrib", ([newAttrib, oldAttrib]) => {
  34. const ndx = this.attrib.indexOf(oldAttrib);
  35. if (~ndx) {
  36. this.attrib[ndx] = newAttrib;
  37. }
  38. });
  39. });
  40. }
  41. addItem(data: Data<T>) {
  42. this.attrib.push(data);
  43. this.diffRedraw();
  44. }
  45. delItem(data: Data<T>) {
  46. const ndx = this.attrib.indexOf(data);
  47. if (~ndx) {
  48. this.attrib.splice(ndx, 1);
  49. this.diffRedraw();
  50. }
  51. }
  52. }