@dxos/app-graph 0.8.4-main.937b3ca → 0.8.4-main.9be5663bfe

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/lib/browser/chunk-W47H2NND.mjs +1604 -0
  2. package/dist/lib/browser/chunk-W47H2NND.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +17 -1276
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +39 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-LYZWNJ7J.mjs +1605 -0
  9. package/dist/lib/node-esm/chunk-LYZWNJ7J.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +17 -1276
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing/index.mjs +40 -0
  14. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  15. package/dist/types/src/graph-builder.d.ts +11 -7
  16. package/dist/types/src/graph-builder.d.ts.map +1 -1
  17. package/dist/types/src/graph.d.ts +13 -17
  18. package/dist/types/src/graph.d.ts.map +1 -1
  19. package/dist/types/src/index.d.ts +1 -0
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/node-matcher.d.ts +44 -18
  22. package/dist/types/src/node-matcher.d.ts.map +1 -1
  23. package/dist/types/src/node.d.ts +21 -5
  24. package/dist/types/src/node.d.ts.map +1 -1
  25. package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
  26. package/dist/types/src/testing/index.d.ts +2 -0
  27. package/dist/types/src/testing/index.d.ts.map +1 -0
  28. package/dist/types/src/testing/setup-graph-builder.d.ts +31 -0
  29. package/dist/types/src/testing/setup-graph-builder.d.ts.map +1 -0
  30. package/dist/types/src/util.d.ts +39 -0
  31. package/dist/types/src/util.d.ts.map +1 -0
  32. package/dist/types/tsconfig.tsbuildinfo +1 -1
  33. package/package.json +36 -26
  34. package/src/graph-builder.test.ts +569 -102
  35. package/src/graph-builder.ts +202 -74
  36. package/src/graph.test.ts +187 -52
  37. package/src/graph.ts +177 -98
  38. package/src/index.ts +1 -0
  39. package/src/node-matcher.ts +59 -29
  40. package/src/node.ts +46 -5
  41. package/src/stories/EchoGraph.stories.tsx +93 -65
  42. package/src/stories/Tree.tsx +1 -1
  43. package/src/testing/index.ts +5 -0
  44. package/src/testing/setup-graph-builder.ts +41 -0
  45. package/src/util.ts +95 -0
package/src/graph.ts CHANGED
@@ -15,6 +15,7 @@ import { log } from '@dxos/log';
15
15
  import { type MakeOptional, isNonNullable } from '@dxos/util';
16
16
 
17
17
  import * as Node from './node';
18
+ import { normalizeRelation, primaryKey, primaryParts, secondaryKey, secondaryParts, shallowEqual } from './util';
18
19
 
19
20
  const graphSymbol = Symbol('graph');
20
21
 
@@ -48,12 +49,8 @@ export type GraphTraversalOptions = {
48
49
  */
49
50
  source?: string;
50
51
 
51
- /**
52
- * The relation to traverse graph edges.
53
- *
54
- * @default 'outbound'
55
- */
56
- relation?: Node.Relation;
52
+ /** The relation(s) to traverse graph edges. */
53
+ relation: Node.RelationInput | Node.RelationInput[];
57
54
  };
58
55
 
59
56
  export type GraphProps = {
@@ -65,8 +62,8 @@ export type GraphProps = {
65
62
  onRemoveNode?: (id: string) => void;
66
63
  };
67
64
 
68
- export type Edge = { source: string; target: string };
69
- export type Edges = { inbound: string[]; outbound: string[] };
65
+ export type Edge = { source: string; target: string; relation: Node.RelationInput };
66
+ export type Edges = Record<string, string[]>;
70
67
 
71
68
  /**
72
69
  * Identifier denoting a Graph.
@@ -104,7 +101,7 @@ export interface BaseGraph extends Pipeable.Pipeable {
104
101
  /**
105
102
  * Get the atom key for the connections of the node with the given id.
106
103
  */
107
- connections(id: string, relation?: Node.Relation): Atom.Atom<Node.Node[]>;
104
+ connections(id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]>;
108
105
  /**
109
106
  * Get the atom key for the actions of the node with the given id.
110
107
  */
@@ -148,6 +145,7 @@ class GraphImpl implements WritableGraph {
148
145
 
149
146
  readonly _registry: Registry.Registry;
150
147
  readonly _expanded = Record.empty<string, boolean>();
148
+ readonly _pendingExpands = new Set<string>();
151
149
  readonly _initialized = Record.empty<string, boolean>();
152
150
  readonly _initialEdges = Record.empty<string, Edges>();
153
151
  readonly _initialNodes = Record.fromEntries([
@@ -177,7 +175,7 @@ class GraphImpl implements WritableGraph {
177
175
  });
178
176
 
179
177
  readonly _edges = Atom.family<string, Atom.Writable<Edges>>((id) => {
180
- const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({ inbound: [], outbound: [] })));
178
+ const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({}) as Edges));
181
179
  return Atom.make<Edges>(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:edges:${id}`));
182
180
  });
183
181
 
@@ -185,9 +183,15 @@ class GraphImpl implements WritableGraph {
185
183
  // TODO(wittjosiah): Atom feature request, support for something akin to `ComplexMap` to allow for complex arguments.
186
184
  readonly _connections = Atom.family<string, Atom.Atom<Node.Node[]>>((key) => {
187
185
  return Atom.make((get) => {
188
- const [id, relation] = key.split('$');
186
+ const parts = key ? primaryParts(key) : [];
187
+ // Empty id (e.g. from `useConnections(graph, undefined, ...)`) yields a key like `\u0001child\u0002outbound`,
188
+ // which has 2 parts but an empty id — treat as no connections rather than throwing.
189
+ if (parts.length < 2 || !parts[0]) {
190
+ return [];
191
+ }
192
+ const { id, relation } = relationFromConnectionKey(key);
189
193
  const edges = get(this._edges(id));
190
- return edges[relation as Node.Relation]
194
+ return (edges[relationKey(relation)] ?? [])
191
195
  .map((id) => get(this._node(id)))
192
196
  .filter(Option.isSome)
193
197
  .map((o) => o.value);
@@ -196,16 +200,17 @@ class GraphImpl implements WritableGraph {
196
200
 
197
201
  readonly _actions = Atom.family<string, Atom.Atom<(Node.Action | Node.ActionGroup)[]>>((id) => {
198
202
  return Atom.make((get) => {
199
- return get(this._connections(`${id}$outbound`)).filter(
200
- (node) => node.type === Node.ActionType || node.type === Node.ActionGroupType,
201
- );
203
+ if (!id) {
204
+ return [];
205
+ }
206
+ return get(this._connections(connectionKey(id, Node.actionRelation()))) as (Node.Action | Node.ActionGroup)[];
202
207
  }).pipe(Atom.withLabel(`graph:actions:${id}`));
203
208
  });
204
209
 
205
210
  readonly _json = Atom.family<string, Atom.Atom<any>>((id) => {
206
211
  return Atom.make((get) => {
207
212
  const toJSON = (node: Node.Node, seen: string[] = []): any => {
208
- const nodes = get(this._connections(`${node.id}$outbound`));
213
+ const nodes = get(this._connections(connectionKey(node.id, 'child')));
209
214
  const obj: Record<string, any> = {
210
215
  id: node.id,
211
216
  type: node.type,
@@ -261,7 +266,7 @@ class GraphImpl implements WritableGraph {
261
266
  return nodeOrThrowImpl(this, id);
262
267
  }
263
268
 
264
- connections(id: string, relation: Node.Relation = 'outbound'): Atom.Atom<Node.Node[]> {
269
+ connections(id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]> {
265
270
  return connectionsImpl(this, id, relation);
266
271
  }
267
272
 
@@ -327,13 +332,9 @@ const nodeOrThrowImpl = (graph: BaseGraph, id: string): Atom.Atom<Node.Node> =>
327
332
  /**
328
333
  * Implementation helper for connections.
329
334
  */
330
- const connectionsImpl = (
331
- graph: BaseGraph,
332
- id: string,
333
- relation: Node.Relation = 'outbound',
334
- ): Atom.Atom<Node.Node[]> => {
335
+ const connectionsImpl = (graph: BaseGraph, id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]> => {
335
336
  const internal = getInternal(graph);
336
- return internal._connections(`${id}$${relation}`);
337
+ return internal._connections(connectionKey(id, relation));
337
338
  };
338
339
 
339
340
  /**
@@ -421,7 +422,7 @@ export function getRoot(graph: BaseGraph): Node.Node {
421
422
  /**
422
423
  * Implementation helper for getConnections.
423
424
  */
424
- const getConnectionsImpl = (graph: BaseGraph, id: string, relation: Node.Relation = 'outbound'): Node.Node[] => {
425
+ const getConnectionsImpl = (graph: BaseGraph, id: string, relation: Node.RelationInput): Node.Node[] => {
425
426
  const internal = getInternal(graph);
426
427
  return internal._registry.get(connectionsImpl(graph, id, relation));
427
428
  };
@@ -429,23 +430,24 @@ const getConnectionsImpl = (graph: BaseGraph, id: string, relation: Node.Relatio
429
430
  /**
430
431
  * Get all nodes connected to the node with the given id by the given relation from the graph's registry.
431
432
  */
432
- export function getConnections(graph: BaseGraph, id: string, relation?: Node.Relation): Node.Node[];
433
- export function getConnections(id: string, relation?: Node.Relation): (graph: BaseGraph) => Node.Node[];
433
+ export function getConnections(graph: BaseGraph, id: string, relation: Node.RelationInput): Node.Node[];
434
+ export function getConnections(id: string, relation: Node.RelationInput): (graph: BaseGraph) => Node.Node[];
434
435
  export function getConnections(
435
436
  graphOrId: BaseGraph | string,
436
- idOrRelation?: string | Node.Relation,
437
- relation?: Node.Relation,
437
+ idOrRelation: string | Node.RelationInput,
438
+ relation?: Node.RelationInput,
438
439
  ): Node.Node[] | ((graph: BaseGraph) => Node.Node[]) {
439
440
  if (typeof graphOrId === 'string') {
440
- // Curried: getConnections(id, relation?)
441
+ // Curried: getConnections(id, relation)
441
442
  const id = graphOrId;
442
- const rel = (typeof idOrRelation === 'string' ? 'outbound' : idOrRelation) ?? 'outbound';
443
+ const rel = idOrRelation as Node.RelationInput;
443
444
  return (graph: BaseGraph) => getConnectionsImpl(graph, id, rel);
444
445
  } else {
445
- // Direct: getConnections(graph, id, relation?)
446
+ // Direct: getConnections(graph, id, relation)
446
447
  const graph = graphOrId;
447
448
  const id = idOrRelation as string;
448
- const rel = relation ?? 'outbound';
449
+ invariant(relation !== undefined, 'Relation is required.');
450
+ const rel = relation;
449
451
  return getConnectionsImpl(graph, id, rel);
450
452
  }
451
453
  }
@@ -510,7 +512,7 @@ export function getEdges(graphOrId: BaseGraph | string, id?: string): Edges | ((
510
512
  * Implementation helper for traverse.
511
513
  */
512
514
  const traverseImpl = (graph: BaseGraph, options: GraphTraversalOptions, path: string[] = []): void => {
513
- const { visitor, source = Node.RootId, relation = 'outbound' } = options;
515
+ const { visitor, source = Node.RootId, relation } = options;
514
516
  // Break cycles.
515
517
  if (path.includes(source)) {
516
518
  return;
@@ -522,9 +524,16 @@ const traverseImpl = (graph: BaseGraph, options: GraphTraversalOptions, path: st
522
524
  return;
523
525
  }
524
526
 
525
- Object.values(getConnections(graph, source, relation)).forEach((child) =>
526
- traverseImpl(graph, { source: child.id, relation, visitor }, [...path, source]),
527
- );
527
+ const relations = Array.isArray(relation) ? relation : [relation];
528
+ const seen = new Set<string>();
529
+ for (const rel of relations) {
530
+ for (const connected of getConnections(graph, source, rel)) {
531
+ if (!seen.has(connected.id)) {
532
+ seen.add(connected.id);
533
+ traverseImpl(graph, { source: connected.id, relation, visitor }, [...path, source]);
534
+ }
535
+ }
536
+ }
528
537
  };
529
538
 
530
539
  /**
@@ -561,6 +570,7 @@ const getPathImpl = (graph: BaseGraph, params: { source?: string; target: string
561
570
  let found: Option.Option<string[]> = Option.none();
562
571
  traverseImpl(graph, {
563
572
  source: node.id,
573
+ relation: 'child',
564
574
  visitor: (node, path) => {
565
575
  if (Option.isSome(found)) {
566
576
  return false;
@@ -660,8 +670,8 @@ const initializeImpl = async <T extends ExpandableGraph | WritableGraph>(graph:
660
670
  const initialized = Record.get(internal._initialized, id).pipe(Option.getOrElse(() => false));
661
671
  log('initialize', { id, initialized });
662
672
  if (!initialized) {
663
- await internal._onInitialize?.(id);
664
673
  Record.set(internal._initialized, id, true);
674
+ await internal._onInitialize?.(id);
665
675
  }
666
676
  return graph;
667
677
  };
@@ -690,19 +700,29 @@ export function initialize<T extends ExpandableGraph | WritableGraph>(
690
700
 
691
701
  /**
692
702
  * Implementation helper for expand.
703
+ * If the node does not exist yet, the expand is recorded as pending and applied when the node is added.
693
704
  */
694
705
  const expandImpl = <T extends ExpandableGraph | WritableGraph>(
695
706
  graph: T,
696
707
  id: string,
697
- relation: Node.Relation = 'outbound',
708
+ relation: Node.RelationInput,
698
709
  ): T => {
699
710
  const internal = getInternal(graph);
700
- const key = `${id}$${relation}`;
711
+ const normalizedRelation = normalizeRelation(relation);
712
+ const key = primaryKey(id, relationKey(normalizedRelation));
713
+ const nodeOpt = internal._registry.get(internal._node(id));
714
+ if (Option.isNone(nodeOpt)) {
715
+ // Node not yet in graph: record expand to run when the node is added.
716
+ internal._pendingExpands.add(key);
717
+ log('expand', { key, deferred: true });
718
+ return graph;
719
+ }
720
+
701
721
  const expanded = Record.get(internal._expanded, key).pipe(Option.getOrElse(() => false));
702
722
  log('expand', { key, expanded });
703
723
  if (!expanded) {
704
- internal._onExpand?.(id, relation);
705
724
  Record.set(internal._expanded, key, true);
725
+ internal._onExpand?.(id, normalizedRelation);
706
726
  }
707
727
  return graph;
708
728
  };
@@ -712,26 +732,31 @@ const expandImpl = <T extends ExpandableGraph | WritableGraph>(
712
732
  *
713
733
  * Fires the `onExpand` callback to add connections to the node.
714
734
  */
715
- export function expand<T extends ExpandableGraph | WritableGraph>(graph: T, id: string, relation?: Node.Relation): T;
735
+ export function expand<T extends ExpandableGraph | WritableGraph>(
736
+ graph: T,
737
+ id: string,
738
+ relation: Node.RelationInput,
739
+ ): T;
716
740
  export function expand(
717
741
  id: string,
718
- relation?: Node.Relation,
742
+ relation: Node.RelationInput,
719
743
  ): <T extends ExpandableGraph | WritableGraph>(graph: T) => T;
720
744
  export function expand<T extends ExpandableGraph | WritableGraph>(
721
745
  graphOrId: T | string,
722
- idOrRelation?: string | Node.Relation,
723
- relation?: Node.Relation,
746
+ idOrRelation: string | Node.RelationInput,
747
+ relation?: Node.RelationInput,
724
748
  ): T | (<T extends ExpandableGraph | WritableGraph>(graph: T) => T) {
725
749
  if (typeof graphOrId === 'string') {
726
- // Curried: expand(id, relation?)
750
+ // Curried: expand(id, relation)
727
751
  const id = graphOrId;
728
- const rel = (typeof idOrRelation === 'string' ? 'outbound' : idOrRelation) ?? 'outbound';
752
+ const rel = idOrRelation as Node.RelationInput;
729
753
  return <T extends ExpandableGraph | WritableGraph>(graph: T) => expandImpl(graph, id, rel);
730
754
  } else {
731
- // Direct: expand(graph, id, relation?)
755
+ // Direct: expand(graph, id, relation)
732
756
  const graph = graphOrId;
733
757
  const id = idOrRelation as string;
734
- const rel = relation ?? 'outbound';
758
+ invariant(relation !== undefined, 'Relation is required.');
759
+ const rel = relation;
735
760
  return expandImpl(graph, id, rel);
736
761
  }
737
762
  }
@@ -742,16 +767,24 @@ export function expand<T extends ExpandableGraph | WritableGraph>(
742
767
  const sortEdgesImpl = <T extends ExpandableGraph | WritableGraph>(
743
768
  graph: T,
744
769
  id: string,
745
- relation: Node.Relation,
770
+ relation: Node.RelationInput,
746
771
  order: string[],
747
772
  ): T => {
748
773
  const internal = getInternal(graph);
749
774
  const edgesAtom = internal._edges(id);
750
775
  const edges = internal._registry.get(edgesAtom);
751
- const unsorted = edges[relation].filter((id) => !order.includes(id)) ?? [];
752
- const sorted = order.filter((id) => edges[relation].includes(id)) ?? [];
753
- edges[relation].splice(0, edges[relation].length, ...[...sorted, ...unsorted]);
754
- internal._registry.set(edgesAtom, edges);
776
+ const relationId = relationKey(relation);
777
+ const current = edges[relationId] ?? [];
778
+ const unsorted = current.filter((id) => !order.includes(id));
779
+ const sorted = order.filter((id) => current.includes(id));
780
+ const newOrder = [...sorted, ...unsorted];
781
+ if (newOrder.length === current.length && newOrder.every((id, i) => id === current[i])) {
782
+ return graph;
783
+ }
784
+ internal._registry.set(edgesAtom, {
785
+ ...edges,
786
+ [relationId]: newOrder,
787
+ });
755
788
  return graph;
756
789
  };
757
790
 
@@ -761,31 +794,31 @@ const sortEdgesImpl = <T extends ExpandableGraph | WritableGraph>(
761
794
  export function sortEdges<T extends ExpandableGraph | WritableGraph>(
762
795
  graph: T,
763
796
  id: string,
764
- relation: Node.Relation,
797
+ relation: Node.RelationInput,
765
798
  order: string[],
766
799
  ): T;
767
800
  export function sortEdges(
768
801
  id: string,
769
- relation: Node.Relation,
802
+ relation: Node.RelationInput,
770
803
  order: string[],
771
804
  ): <T extends ExpandableGraph | WritableGraph>(graph: T) => T;
772
805
  export function sortEdges<T extends ExpandableGraph | WritableGraph>(
773
806
  graphOrId: T | string,
774
- idOrRelation?: string | Node.Relation,
775
- relationOrOrder?: Node.Relation | string[],
807
+ idOrRelation?: string | Node.RelationInput,
808
+ relationOrOrder?: Node.RelationInput | string[],
776
809
  order?: string[],
777
810
  ): T | (<T extends ExpandableGraph | WritableGraph>(graph: T) => T) {
778
811
  if (typeof graphOrId === 'string') {
779
812
  // Curried: sortEdges(id, relation, order)
780
813
  const id = graphOrId;
781
- const relation = idOrRelation as Node.Relation;
814
+ const relation = idOrRelation as Node.RelationInput;
782
815
  const order = relationOrOrder as string[];
783
816
  return <T extends ExpandableGraph | WritableGraph>(graph: T) => sortEdgesImpl(graph, id, relation, order);
784
817
  } else {
785
818
  // Direct: sortEdges(graph, id, relation, order)
786
819
  const graph = graphOrId;
787
820
  const id = idOrRelation as string;
788
- const relation = relationOrOrder as Node.Relation;
821
+ const relation = relationOrOrder as Node.RelationInput;
789
822
  return sortEdgesImpl(graph, id, relation, order!);
790
823
  }
791
824
  }
@@ -842,7 +875,7 @@ const addNodeImpl = <T extends WritableGraph>(graph: T, nodeArg: Node.NodeArg<an
842
875
  Option.match(existingNode, {
843
876
  onSome: (existing) => {
844
877
  const typeChanged = existing.type !== type;
845
- const dataChanged = existing.data !== data;
878
+ const dataChanged = !shallowEqual(existing.data, data);
846
879
  const propertiesChanged = Object.keys(properties).some((key) => existing.properties[key] !== properties[key]);
847
880
  log('existing node', {
848
881
  id,
@@ -868,12 +901,21 @@ const addNodeImpl = <T extends WritableGraph>(graph: T, nodeArg: Node.NodeArg<an
868
901
  const newNode = internal._constructNode({ id, type, data, properties, ...rest });
869
902
  internal._registry.set(nodeAtom, newNode);
870
903
  graph.onNodeChanged.emit({ id, node: newNode });
904
+
905
+ // Apply any expands that were deferred because this node did not exist yet.
906
+ const toApply = [...internal._pendingExpands].filter((k) => primaryParts(k)[0] === id);
907
+ for (const pendingKey of toApply) {
908
+ internal._pendingExpands.delete(pendingKey);
909
+ const relation = relationFromKey(primaryParts(pendingKey)[1]);
910
+ Record.set(internal._expanded, pendingKey, true);
911
+ internal._onExpand?.(id, relation);
912
+ }
871
913
  },
872
914
  });
873
915
 
874
916
  if (nodes) {
875
917
  addNodesImpl(graph, nodes);
876
- const _edges = nodes.map((node) => ({ source: id, target: node.id }));
918
+ const _edges = nodes.map((node) => ({ source: id, target: node.id, relation: 'child' as const }));
877
919
  addEdgesImpl(graph, _edges);
878
920
  }
879
921
 
@@ -949,11 +991,20 @@ const removeNodeImpl = <T extends WritableGraph>(graph: T, id: string, edges = f
949
991
  // TODO(wittjosiah): Reset expanded and initialized flags?
950
992
 
951
993
  if (edges) {
952
- const { inbound, outbound } = internal._registry.get(internal._edges(id));
953
- const edgesToRemove = [
954
- ...inbound.map((source) => ({ source, target: id })),
955
- ...outbound.map((target) => ({ source: id, target })),
956
- ];
994
+ const nodeEdges = internal._registry.get(internal._edges(id));
995
+ const edgesToRemove: Edge[] = [];
996
+ for (const [relationKeyValue, relatedIds] of Object.entries(nodeEdges)) {
997
+ const relation = relationFromKey(relationKeyValue);
998
+ const isInboundRelation = relation.direction === 'inbound';
999
+ for (const relatedId of relatedIds) {
1000
+ if (isInboundRelation) {
1001
+ // Inbound edge lists store source node IDs; reconstruct the canonical outbound edge.
1002
+ edgesToRemove.push({ source: relatedId, target: id, relation: inverseRelation(relation) });
1003
+ } else {
1004
+ edgesToRemove.push({ source: id, target: relatedId, relation });
1005
+ }
1006
+ }
1007
+ }
957
1008
  removeEdgesImpl(graph, edgesToRemove);
958
1009
  }
959
1010
 
@@ -1019,32 +1070,28 @@ export function addEdges<T extends WritableGraph>(
1019
1070
  * Implementation helper for addEdge.
1020
1071
  */
1021
1072
  const addEdgeImpl = <T extends WritableGraph>(graph: T, edgeArg: Edge): T => {
1073
+ const relation = normalizeRelation(edgeArg.relation);
1074
+ const relationId = relationKey(relation);
1075
+ const inverse = inverseRelation(relation);
1076
+ const inverseId = relationKey(inverse);
1022
1077
  const internal = getInternal(graph);
1078
+
1023
1079
  const sourceAtom = internal._edges(edgeArg.source);
1024
1080
  const source = internal._registry.get(sourceAtom);
1025
- if (!source.outbound.includes(edgeArg.target)) {
1026
- log('add outbound edge', {
1027
- source: edgeArg.source,
1028
- target: edgeArg.target,
1029
- });
1030
- internal._registry.set(sourceAtom, {
1031
- inbound: source.inbound,
1032
- outbound: [...source.outbound, edgeArg.target],
1033
- });
1081
+ const sourceList = source[relationId] ?? [];
1082
+ if (!sourceList.includes(edgeArg.target)) {
1083
+ log('add edge', { source: edgeArg.source, target: edgeArg.target, relation: relationId });
1084
+ internal._registry.set(sourceAtom, { ...source, [relationId]: [...sourceList, edgeArg.target] });
1034
1085
  }
1035
1086
 
1036
1087
  const targetAtom = internal._edges(edgeArg.target);
1037
1088
  const target = internal._registry.get(targetAtom);
1038
- if (!target.inbound.includes(edgeArg.source)) {
1039
- log('add inbound edge', {
1040
- source: edgeArg.source,
1041
- target: edgeArg.target,
1042
- });
1043
- internal._registry.set(targetAtom, {
1044
- inbound: [...target.inbound, edgeArg.source],
1045
- outbound: target.outbound,
1046
- });
1089
+ const targetList = target[inverseId] ?? [];
1090
+ if (!targetList.includes(edgeArg.source)) {
1091
+ log('add inverse edge', { source: edgeArg.source, target: edgeArg.target, relation: inverseId });
1092
+ internal._registry.set(targetAtom, { ...target, [inverseId]: [...targetList, edgeArg.source] });
1047
1093
  }
1094
+
1048
1095
  return graph;
1049
1096
  };
1050
1097
 
@@ -1106,32 +1153,34 @@ export function removeEdges<T extends WritableGraph>(
1106
1153
  * Implementation helper for removeEdge.
1107
1154
  */
1108
1155
  const removeEdgeImpl = <T extends WritableGraph>(graph: T, edgeArg: Edge, removeOrphans = false): T => {
1156
+ const relation = normalizeRelation(edgeArg.relation);
1157
+ const relationId = relationKey(relation);
1158
+ const inverse = inverseRelation(relation);
1159
+ const inverseId = relationKey(inverse);
1109
1160
  const internal = getInternal(graph);
1161
+
1110
1162
  const sourceAtom = internal._edges(edgeArg.source);
1111
1163
  const source = internal._registry.get(sourceAtom);
1112
- if (source.outbound.includes(edgeArg.target)) {
1113
- internal._registry.set(sourceAtom, {
1114
- inbound: source.inbound,
1115
- outbound: source.outbound.filter((id) => id !== edgeArg.target),
1116
- });
1164
+ const sourceList = source[relationId] ?? [];
1165
+ if (sourceList.includes(edgeArg.target)) {
1166
+ internal._registry.set(sourceAtom, { ...source, [relationId]: sourceList.filter((id) => id !== edgeArg.target) });
1117
1167
  }
1118
1168
 
1119
1169
  const targetAtom = internal._edges(edgeArg.target);
1120
1170
  const target = internal._registry.get(targetAtom);
1121
- if (target.inbound.includes(edgeArg.source)) {
1122
- internal._registry.set(targetAtom, {
1123
- inbound: target.inbound.filter((id) => id !== edgeArg.source),
1124
- outbound: target.outbound,
1125
- });
1171
+ const targetList = target[inverseId] ?? [];
1172
+ if (targetList.includes(edgeArg.source)) {
1173
+ internal._registry.set(targetAtom, { ...target, [inverseId]: targetList.filter((id) => id !== edgeArg.source) });
1126
1174
  }
1127
1175
 
1128
1176
  if (removeOrphans) {
1129
- const source = internal._registry.get(sourceAtom);
1130
- const target = internal._registry.get(targetAtom);
1131
- if (source.outbound.length === 0 && source.inbound.length === 0 && edgeArg.source !== Node.RootId) {
1177
+ const sourceAfter = internal._registry.get(sourceAtom);
1178
+ const targetAfter = internal._registry.get(targetAtom);
1179
+ const isEmpty = (edges: Edges) => Object.values(edges).every((ids) => ids.length === 0);
1180
+ if (isEmpty(sourceAfter) && edgeArg.source !== Node.RootId) {
1132
1181
  removeNodesImpl(graph, [edgeArg.source]);
1133
1182
  }
1134
- if (target.outbound.length === 0 && target.inbound.length === 0 && edgeArg.target !== Node.RootId) {
1183
+ if (isEmpty(targetAfter) && edgeArg.target !== Node.RootId) {
1135
1184
  removeNodesImpl(graph, [edgeArg.target]);
1136
1185
  }
1137
1186
  }
@@ -1172,3 +1221,33 @@ export function removeEdge<T extends WritableGraph>(
1172
1221
  export const make = (params?: GraphProps): Graph => {
1173
1222
  return new GraphImpl(params);
1174
1223
  };
1224
+
1225
+ //
1226
+ // Utilities
1227
+ //
1228
+
1229
+ export const relationKey = (relation: Node.RelationInput): string => {
1230
+ const normalized = normalizeRelation(relation);
1231
+ return secondaryKey(normalized.kind, normalized.direction);
1232
+ };
1233
+
1234
+ export const relationFromKey = (encoded: string): Node.Relation => {
1235
+ const parts = secondaryParts(encoded);
1236
+ invariant(parts.length === 2 && parts[0].length > 0 && parts[1].length > 0, `Invalid relation key: ${encoded}`);
1237
+ const [kind, directionRaw] = parts;
1238
+ invariant(directionRaw === 'outbound' || directionRaw === 'inbound', `Invalid relation direction: ${directionRaw}`);
1239
+ return Node.relation(kind, directionRaw);
1240
+ };
1241
+
1242
+ const connectionKey = (id: string, relation: Node.RelationInput): string => primaryKey(id, relationKey(relation));
1243
+
1244
+ const relationFromConnectionKey = (key: string): { id: string; relation: Node.Relation } => {
1245
+ const [id, encodedRelation] = primaryParts(key);
1246
+ invariant(id && encodedRelation, `Invalid connection key: ${key}`);
1247
+ return { id, relation: relationFromKey(encodedRelation) };
1248
+ };
1249
+
1250
+ const inverseRelation = (relation: Node.RelationInput): Node.Relation => {
1251
+ const normalized = normalizeRelation(relation);
1252
+ return Node.relation(normalized.kind, normalized.direction === 'outbound' ? 'inbound' : 'outbound');
1253
+ };
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export * as Graph from './graph';
8
8
  export * as GraphBuilder from './graph-builder';
9
9
  export * as Node from './node';
10
10
  export * as NodeMatcher from './node-matcher';
11
+ export { qualifyId, getParentId, getSegmentId } from './util';
11
12
 
12
13
  // TODO(wittjosiah): Direct re-export needed for portable type references.
13
14
  export type { BuilderExtensions } from './graph-builder';