| 20 | export type Node = SparseNode | PopulatedNode; |
| 21 | |
| 22 | export class NodeManager { |
| 23 | public root: PopulatedNode; |
| 24 | |
| 25 | private references = new Map<string, PopulatedNode>(); |
| 26 | private subscribers = new Set<() => void>(); |
| 27 | |
| 28 | constructor(source: Node) { |
| 29 | this.root = this.populate(source); |
| 30 | } |
| 31 | |
| 32 | public find = (id: string): PopulatedNode | undefined => { |
| 33 | return this.references.get(id); |
| 34 | }; |
| 35 | |
| 36 | public insert = (node: Node, destination: { id: string; index: number }) => { |
| 37 | const child = 'id' in node ? (node as PopulatedNode) : this.populate(node); |
| 38 | const parent = this.find(destination.id); |
| 39 | |
| 40 | if (!parent) { |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | child.parent = parent.id; |
| 45 | parent.children = [ |
| 46 | ...parent.children.slice(0, destination.index), |
| 47 | child, |
| 48 | ...parent.children.slice(destination.index), |
| 49 | ]; |
| 50 | |
| 51 | this.notify(); |
| 52 | |
| 53 | return child.id; |
| 54 | }; |
| 55 | |
| 56 | public remove = (id: string, permanent = true) => { |
| 57 | const node = this.find(id); |
| 58 | |
| 59 | if (!node) { |
| 60 | throw new Error(`Node with id ${id} not found`); |
| 61 | } |
| 62 | |
| 63 | if (!node.parent) { |
| 64 | throw new Error('Cannot remove root node'); |
| 65 | } |
| 66 | |
| 67 | const parent = this.find(node.parent); |
| 68 | |
| 69 | if (!parent) { |
| 70 | throw new Error('Parent node not found'); |
| 71 | } |
| 72 | |
| 73 | parent.children = parent.children.filter((child) => typeof child === 'string' || child.id !== id); |
| 74 | |
| 75 | if (node.implicit.parentPropKey) { |
| 76 | parent.props[node.implicit.parentPropKey] = null; |
| 77 | delete parent.implicit.children[node.implicit.parentPropKey]; |
| 78 | delete node.implicit.parentPropKey; |
| 79 | } |
nothing calls this directly
no outgoing calls
no test coverage detected