@arqlet/engine-client 0.4.0 → 0.6.0

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.
package/arqlet.wasm CHANGED
Binary file
package/columns.d.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type {Scene} from '@arqlet/contracts';
2
+
3
+ /**
4
+ * Provisional (ADR 0019, step 4): a session's scene as columns. Index `i` of an id or text table is node, route, port, label,
5
+ * row, conflict or edge `i`, and the typed arrays of the same part are indexed alike. Coordinates are `f32`.
6
+ */
7
+ export interface SceneColumns {
8
+ schemaVersion: number;
9
+ revision: number;
10
+ layoutVersion: number;
11
+
12
+ /** Node ids, labels and kinds (`nodeKind` indexes `nodeKinds`) by node index. */
13
+ nodeIds: string[];
14
+ nodeLabels: string[];
15
+ nodeKinds: string[];
16
+ /** x, y, width, height per node, in scene coordinates. */
17
+ nodeBounds: Float32Array;
18
+ /** Parent node index, `NONE` for a root. */
19
+ nodeParent: Uint32Array;
20
+ /** Bits of `NODE_FLAGS`. */
21
+ nodeFlags: Uint32Array;
22
+ nodeKind: Uint32Array;
23
+ /** Values of `SHAPES`. */
24
+ nodeShape: Uint32Array;
25
+
26
+ /** Route ids by route index. */
27
+ routeIds: string[];
28
+ /** Node index of each route's ends, `NONE` when the end is not a node of the scene. */
29
+ routeSource: Uint32Array;
30
+ routeTarget: Uint32Array;
31
+ routeWeight: Uint32Array;
32
+ /** Bits of `ROUTE_FLAGS`. */
33
+ routeFlags: Uint32Array;
34
+ /** One more than the routes: route `i` is the points `routeOffsets[i]` to `routeOffsets[i + 1]` of `routePoints`. */
35
+ routeOffsets: Uint32Array;
36
+ /** x and y alternating, all routes one after the other. */
37
+ routePoints: Float32Array;
38
+ /** Each route's kind (index into `routeKinds`, '' for none), the edges it stands for in the other direction (`NONE`
39
+ * when it is not a two-way route), and the edges of a bundle (indices into `edgeIds`, behind `routeMemberOffsets`). */
40
+ routeKinds: string[];
41
+ routeKind: Uint32Array;
42
+ routeBackWeight: Uint32Array;
43
+ routeMemberOffsets: Uint32Array;
44
+ routeMembers: Uint32Array;
45
+
46
+ /** Port ids by port index. */
47
+ portIds: string[];
48
+ /** The edges that ports and boundary crossings name, each once. */
49
+ edgeIds: string[];
50
+ /** Node index of each port's node. */
51
+ portNode: Uint32Array;
52
+ /** Index into `edgeIds`. */
53
+ portEdge: Uint32Array;
54
+ /** Bits of `PORT_FLAGS`. */
55
+ portFlags: Uint32Array;
56
+ /** Values of `SIDES`. */
57
+ portSide: Uint32Array;
58
+ /** x and y alternating. */
59
+ portPosition: Float32Array;
60
+
61
+ /** Boundary crossings: edge (index into `edgeIds`), container (node index), ordinal, side, flags (bit 0: derived), position. */
62
+ crossingEdge: Uint32Array;
63
+ crossingContainer: Uint32Array;
64
+ crossingOrdinal: Uint32Array;
65
+ crossingSide: Uint32Array;
66
+ crossingFlags: Uint32Array;
67
+ crossingPosition: Float32Array;
68
+
69
+ /** Placed labels: id and text by label index, `labelKind` indexes `labelKinds`. */
70
+ labelIds: string[];
71
+ labelTexts: string[];
72
+ labelKinds: string[];
73
+ labelKind: Uint32Array;
74
+ /** x, y, width, height per label. */
75
+ labelBounds: Float32Array;
76
+
77
+ /** Rows of the nodes' content, node by node: id and label by row index, the node (index), bounds (four per row). */
78
+ rowIds: string[];
79
+ rowLabels: string[];
80
+ rowNode: Uint32Array;
81
+ rowBounds: Float32Array;
82
+
83
+ /** Conflicts: kind (index into `conflictKinds`) and reason by conflict index; the nodes and routes each names are indices
84
+ * (`NONE` for one outside the scene) in `conflictNodes` and `conflictRoutes`, behind the offsets (conflicts + 1). */
85
+ conflictKinds: string[];
86
+ conflictReasons: string[];
87
+ conflictKind: Uint32Array;
88
+ conflictNodeOffsets: Uint32Array;
89
+ conflictNodes: Uint32Array;
90
+ conflictRouteOffsets: Uint32Array;
91
+ conflictRoutes: Uint32Array;
92
+
93
+ /** Where bus lines branch: x and y alternating. */
94
+ junctions: Float32Array;
95
+ /** x, y, width, height of everything drawn, with its margin (full precision). */
96
+ bounds: [number, number, number, number];
97
+ showPorts: boolean;
98
+ /** The explicit buses, each as its edges' ids. */
99
+ buses: string[][];
100
+ }
101
+
102
+ /** "No node" in an index column. */
103
+ export const NONE: number;
104
+ export const NODE_FLAGS: {readonly container: 1; readonly aggregate: 2; readonly collapsed: 4; readonly invalid: 8};
105
+ export const ROUTE_FLAGS: {readonly invalid: 1; readonly rounded: 2};
106
+ export const PORT_FLAGS: {readonly explicit: 1; readonly target: 2};
107
+ export const SIDES: {readonly left: 0; readonly right: 1; readonly top: 2; readonly bottom: 3};
108
+ export const SHAPES: {readonly rect: 0; readonly square: 1; readonly circle: 2; readonly busLine: 3};
109
+
110
+ /** The columns of a scene object, as the engine builds them (`f32` coordinates). Provisional. */
111
+ export function columnsOfScene(scene: Scene): SceneColumns;
package/columns.js ADDED
@@ -0,0 +1,161 @@
1
+ // Provisional (ADR 0019, step 4): the scene as columns. The engine's own columns (`session.columns()` on a resident
2
+ // session in WASM) and this function give the same arrays; this one serves engines that keep their session elsewhere
3
+ // (the backend answers JSON only) and is the reference the parity tests compare against. Pure: no DOM, no engine.
4
+
5
+ /** "No node" in an index column (`u32::MAX`). */
6
+ export const NONE = 0xffffffff;
7
+ /** Bits of `nodeFlags`. */
8
+ export const NODE_FLAGS = {container: 1, aggregate: 2, collapsed: 4, invalid: 8};
9
+ /** Bits of `routeFlags`. */
10
+ export const ROUTE_FLAGS = {invalid: 1, rounded: 2};
11
+ /** Bits of `portFlags`: authored, and the target end (the source end otherwise). */
12
+ export const PORT_FLAGS = {explicit: 1, target: 2};
13
+ /** Values of `portSide` and `crossingSide`. */
14
+ export const SIDES = {left: 0, right: 1, top: 2, bottom: 3};
15
+ /** Values of `nodeShape` (an unknown shape counts as `rect`). */
16
+ export const SHAPES = {rect: 0, square: 1, circle: 2, busLine: 3};
17
+
18
+ // Strings kept once, numbered in the order they first occur.
19
+ const table = () => {
20
+ const items = [], index = new Map();
21
+ return {items, id: text => { if (!index.has(text)) { index.set(text, items.length); items.push(text); } return index.get(text); }};
22
+ };
23
+ const rects = (list, get) => {
24
+ const out = new Float32Array(list.length * 4);
25
+ list.forEach((item, i) => { const b = get(item); out.set([b.x, b.y, b.width, b.height], i * 4); });
26
+ return out;
27
+ };
28
+ const points = (list, get) => {
29
+ const out = new Float32Array(list.length * 2);
30
+ list.forEach((item, i) => { const p = get(item); out[i * 2] = p.x; out[i * 2 + 1] = p.y; });
31
+ return out;
32
+ };
33
+
34
+ /**
35
+ * The columns of a scene (as `session.scene()` gives it), in the scene's order. Id and text tables (`nodeIds`, `nodeLabels`,
36
+ * `nodeKinds`, `routeIds`, `portIds`, `edgeIds`, `labelIds`, `labelTexts`, `labelKinds`, `rowIds`, `rowLabels`,
37
+ * `conflictKinds`, `conflictReasons`, `buses`), `bounds` (x, y, width, height of everything drawn), `showPorts`, and typed
38
+ * arrays: see `SceneColumns`. Coordinates are narrowed to `f32` as the engine does.
39
+ */
40
+ export function columnsOfScene(scene) {
41
+ const nodes = scene.nodes ?? [];
42
+ const routes = scene.routes ?? [];
43
+ const ports = scene.ports ?? [];
44
+ const crossings = scene.crossings ?? [];
45
+ const labels = scene.labels ?? [];
46
+ const conflicts = scene.conflicts ?? [];
47
+ const index = new Map();
48
+ nodes.forEach((n, i) => index.set(n.id, i));
49
+ const at = id => (index.has(id) ? index.get(id) : NONE);
50
+ const routeIndex = new Map();
51
+ routes.forEach((r, i) => routeIndex.set(r.id, i));
52
+ const atRoute = id => (routeIndex.has(id) ? routeIndex.get(id) : NONE);
53
+
54
+ const nodeBounds = rects(nodes, n => n.bounds);
55
+ const nodeParent = new Uint32Array(nodes.length);
56
+ const nodeFlags = new Uint32Array(nodes.length);
57
+ const nodeKind = new Uint32Array(nodes.length);
58
+ const nodeShape = new Uint32Array(nodes.length);
59
+ const nodeKinds = table();
60
+ nodes.forEach((n, i) => {
61
+ nodeParent[i] = n.parentId == null ? NONE : at(n.parentId);
62
+ nodeFlags[i] = (n.container ? 1 : 0) | (n.aggregate ? 2 : 0) | (n.collapsed ? 4 : 0) | (n.invalid ? 8 : 0);
63
+ nodeKind[i] = nodeKinds.id(n.kind);
64
+ nodeShape[i] = SHAPES[n.shape] ?? 0;
65
+ });
66
+
67
+ const routeSource = new Uint32Array(routes.length);
68
+ const routeTarget = new Uint32Array(routes.length);
69
+ const routeWeight = new Uint32Array(routes.length);
70
+ const routeFlags = new Uint32Array(routes.length);
71
+ const routeKinds = table();
72
+ const routeKind = new Uint32Array(routes.length);
73
+ const routeBackWeight = new Uint32Array(routes.length);
74
+ const routeOffsets = new Uint32Array(routes.length + 1);
75
+ let total = 0;
76
+ for (const r of routes) total += r.points.length;
77
+ const routePoints = new Float32Array(total * 2);
78
+ let cursor = 0;
79
+ routes.forEach((r, i) => {
80
+ routeSource[i] = at(r.source);
81
+ routeTarget[i] = at(r.target);
82
+ routeWeight[i] = Math.min(r.weight ?? 0, NONE);
83
+ routeFlags[i] = (r.invalid ? 1 : 0) | (r.rounded ? 2 : 0);
84
+ routeKind[i] = routeKinds.id(r.kind ?? '');
85
+ routeBackWeight[i] = r.backWeight == null ? NONE : Math.min(r.backWeight, NONE - 1);
86
+ for (const p of r.points) { routePoints[cursor++] = p.x; routePoints[cursor++] = p.y; }
87
+ routeOffsets[i + 1] = cursor / 2;
88
+ });
89
+
90
+ // Ports and boundary crossings name edges; the edges are numbered once, ports first.
91
+ const edges = table();
92
+ const portNode = Uint32Array.from(ports, p => at(p.nodeId));
93
+ const portEdge = Uint32Array.from(ports, p => edges.id(p.edgeId));
94
+ const portFlags = Uint32Array.from(ports, p => (p.explicit ? 1 : 0) | (p.endpoint === 'target' ? 2 : 0));
95
+ const portSide = Uint32Array.from(ports, p => SIDES[p.side]);
96
+ const crossingEdge = Uint32Array.from(crossings, x => edges.id(x.edgeId));
97
+ // The edges of bundles come after those of ports and crossings.
98
+ const routeMemberOffsets = [0], routeMembers = [];
99
+ for (const r of routes) {
100
+ for (const member of r.members ?? []) routeMembers.push(edges.id(member));
101
+ routeMemberOffsets.push(routeMembers.length);
102
+ }
103
+ const labelKinds = table();
104
+
105
+ const conflictKinds = table();
106
+ const conflictNodes = [], conflictRoutes = [], conflictNodeOffsets = [0], conflictRouteOffsets = [0];
107
+ for (const k of conflicts) {
108
+ for (const id of k.nodes) conflictNodes.push(at(id));
109
+ for (const id of k.routes) conflictRoutes.push(atRoute(id));
110
+ conflictNodeOffsets.push(conflictNodes.length);
111
+ conflictRouteOffsets.push(conflictRoutes.length);
112
+ }
113
+ const conflictKind = Uint32Array.from(conflicts, k => conflictKinds.id(k.kind));
114
+
115
+ const rows = [];
116
+ nodes.forEach((n, i) => { for (const row of n.rows ?? []) rows.push({row, node: i}); });
117
+ const b = scene.bounds;
118
+
119
+ return {
120
+ schemaVersion: scene.schemaVersion,
121
+ revision: scene.revision,
122
+ layoutVersion: scene.layoutVersion,
123
+ nodeIds: nodes.map(n => n.id),
124
+ nodeLabels: nodes.map(n => n.label),
125
+ nodeKinds: nodeKinds.items,
126
+ routeIds: routes.map(r => r.id),
127
+ routeKinds: routeKinds.items,
128
+ portIds: ports.map(p => p.id),
129
+ edgeIds: edges.items,
130
+ labelIds: labels.map(l => l.id),
131
+ labelTexts: labels.map(l => l.text),
132
+ labelKinds: labelKinds.items,
133
+ rowIds: rows.map(r => r.row.id),
134
+ rowLabels: rows.map(r => r.row.label),
135
+ conflictKinds: conflictKinds.items,
136
+ conflictReasons: conflicts.map(k => k.reason),
137
+ buses: scene.buses ?? [],
138
+ bounds: b ? [b.x, b.y, b.width, b.height] : [0, 0, 0, 0],
139
+ showPorts: Boolean(scene.showPorts),
140
+ nodeBounds, nodeParent, nodeFlags, nodeKind, nodeShape,
141
+ routeSource, routeTarget, routeWeight, routeFlags, routeOffsets, routePoints,
142
+ routeKind, routeBackWeight, routeMemberOffsets: Uint32Array.from(routeMemberOffsets), routeMembers: Uint32Array.from(routeMembers),
143
+ portNode, portEdge, portFlags, portSide, portPosition: points(ports, p => p.position),
144
+ crossingEdge,
145
+ crossingContainer: Uint32Array.from(crossings, x => at(x.containerId)),
146
+ crossingOrdinal: Uint32Array.from(crossings, x => Math.min(x.ordinal, NONE)),
147
+ crossingSide: Uint32Array.from(crossings, x => SIDES[x.side]),
148
+ crossingFlags: Uint32Array.from(crossings, x => (x.derived ? 1 : 0)),
149
+ crossingPosition: points(crossings, x => x.position),
150
+ labelKind: Uint32Array.from(labels, l => labelKinds.id(l.kind)),
151
+ labelBounds: rects(labels, l => l.bounds),
152
+ rowNode: Uint32Array.from(rows, r => r.node),
153
+ rowBounds: rects(rows, r => r.row.bounds),
154
+ conflictKind,
155
+ conflictNodeOffsets: Uint32Array.from(conflictNodeOffsets),
156
+ conflictNodes: Uint32Array.from(conflictNodes),
157
+ conflictRouteOffsets: Uint32Array.from(conflictRouteOffsets),
158
+ conflictRoutes: Uint32Array.from(conflictRoutes),
159
+ junctions: points(scene.junctions ?? [], p => p),
160
+ };
161
+ }
package/engine.d.ts CHANGED
@@ -18,6 +18,29 @@ export function loadEngine(
18
18
  /** Scene v1 for a snapshot, computed by the engine and cached per snapshot object. Throws the engine's error. */
19
19
  export function sceneOf(run: Run, snapshot: Snapshot): Scene;
20
20
 
21
+ /**
22
+ * Provisional: the groups and communities the view of `graph` adds with `options` (`groups`, `communities`,
23
+ * `communityHubs`), as the `groups` option takes them: node id → path of labels. Given back as `options.groups`, the view
24
+ * gets the same containers (of kind `group`) without computing communities again. Throws the engine's error.
25
+ */
26
+ export function communityGroups(
27
+ run: Run,
28
+ graph: import('@arqlet/contracts').Graph,
29
+ options?: import('@arqlet/contracts').LayoutOptions,
30
+ ): {[nodeId: string]: string[]};
31
+
32
+ /**
33
+ * Provisional: the first view of `graph` (`import`). With `omitSource`, the snapshot leaves the source graph out and
34
+ * carries `sourceDigest`; later requests on it send the graph as `source`. Throws the engine's error.
35
+ */
36
+ export function importGraph(
37
+ run: Run,
38
+ graph: import('@arqlet/contracts').Graph,
39
+ limit: number,
40
+ options?: import('@arqlet/contracts').LayoutOptions,
41
+ delivery?: {omitSource?: boolean},
42
+ ): Snapshot;
43
+
21
44
  /**
22
45
  * Starts a module worker that answers engine requests (browser only). Post `{requestId, request}`; the worker answers
23
46
  * `{requestId, ...response}` and, while a request runs, `{requestId, publication, emittedAt, bytes}` for each
package/engine.js CHANGED
@@ -43,6 +43,28 @@ export function sceneOf(run, snapshot) {
43
43
  return result.scene;
44
44
  }
45
45
 
46
+ /**
47
+ * Provisional: the groups and communities the view of `graph` adds with `options` (`groups`, `communities`,
48
+ * `communityHubs`), as the `groups` option takes them: node id → path of labels. Computed once (in a backend, for a large
49
+ * graph) and given back as `options.groups`, the view gets the same containers without computing communities again.
50
+ * Throws the engine's error.
51
+ */
52
+ export function communityGroups(run, graph, options = {}) {
53
+ const result = run({op: 'communities', graph, options});
54
+ if (!result.ok) throw Error(result.error);
55
+ return result.groups;
56
+ }
57
+
58
+ /**
59
+ * Provisional: the first view of `graph` (`import`). With `omitSource`, the snapshot leaves the source graph out and
60
+ * carries its fingerprint (`sourceDigest`); later requests on it send the graph as `source`. Throws the engine's error.
61
+ */
62
+ export function importGraph(run, graph, limit, options = {}, {omitSource = false} = {}) {
63
+ const result = run({op: 'import', graph, limit, options, ...(omitSource ? {omitSource: true} : {})});
64
+ if (!result.ok) throw Error(result.error);
65
+ return result.snapshot;
66
+ }
67
+
46
68
  /**
47
69
  * Starts a module worker that answers engine requests for the WASM at `wasmUrl`. The worker's own URL is
48
70
  * resolved from this module, so the same package works from any host page or import map.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "The Arqlet graph-layout engine as WebAssembly, with a loader, a worker protocol, an ELK-style layout call and preset sequencing. Provisional.",
5
5
  "keywords": [
6
6
  "graph",
@@ -47,6 +47,10 @@
47
47
  "types": "./session.d.ts",
48
48
  "default": "./session.js"
49
49
  },
50
+ "./columns.js": {
51
+ "types": "./columns.d.ts",
52
+ "default": "./columns.js"
53
+ },
50
54
  "./worker.js": "./worker.js",
51
55
  "./arqlet.wasm": "./arqlet.wasm"
52
56
  },
@@ -56,11 +60,13 @@
56
60
  "presets.js",
57
61
  "elk.js",
58
62
  "session.js",
63
+ "columns.js",
59
64
  "engine.d.ts",
60
65
  "wasm-client.d.ts",
61
66
  "presets.d.ts",
62
67
  "elk.d.ts",
63
68
  "session.d.ts",
69
+ "columns.d.ts",
64
70
  "worker.js",
65
71
  "arqlet.wasm",
66
72
  "README.md",
@@ -71,7 +77,7 @@
71
77
  "access": "public"
72
78
  },
73
79
  "dependencies": {
74
- "@arqlet/contracts": "^0.4.0"
80
+ "@arqlet/contracts": "^0.6.0"
75
81
  },
76
82
  "scripts": {
77
83
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type {Graph, Hidden, Overview, OverviewRequest, Scene, Snapshot} from '@arqlet/contracts';
1
+ import type {Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
2
+ import type {SceneColumns} from './columns.js';
2
3
  import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
3
4
 
4
5
  /** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
@@ -11,6 +12,9 @@ export interface SessionResult {
11
12
  unchanged?: boolean;
12
13
  }
13
14
 
15
+ /** The answer of a read-only request (`trace`, `neighbourhood`): its fields beside `ok: true`, or the error. */
16
+ export type ReadAnswer<T> = ({ok: true} & T) | {ok: false; error: string};
17
+
14
18
  /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
15
19
  export interface Session {
16
20
  /**
@@ -41,14 +45,35 @@ export interface Session {
41
45
  * and routes of the current view that carry them; `distance` the hops of every visible node from the path.
42
46
  * `edgeKinds`: the paths follow only edges of these kinds (default: every edge).
43
47
  */
44
- trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<EngineResponse>;
48
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<TraceAnswer>>;
49
+ /**
50
+ * Provisional: the nodes within `hops` edges (default 1) of a node or of each of a list, read only, answered as
51
+ * `trace` (`nodes`, `edges`, `visible`, `distance`) plus the `hops` of every node; `nodes` can go to `reveal`.
52
+ * `direction`: `out` (what it leads to), `in` (what leads to it) or `both` (default); `edgeKinds`: only these kinds.
53
+ */
54
+ neighbourhood(
55
+ nodeId: string | string[],
56
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
57
+ ): Promise<ReadAnswer<NeighbourhoodAnswer>>;
58
+ /**
59
+ * Provisional: changes the graph without a new import (removals first; a removed node takes what it holds and its
60
+ * edges along); the view keeps its state and is laid out as a toggle lays it out (abstracting views) or again from
61
+ * where it was.
62
+ */
63
+ patch(patch: GraphPatch): Promise<SessionResult>;
45
64
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
46
65
  reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
47
- /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest;
48
- * `hide` replaces what was hidden before, `{}` shows everything. */
66
+ /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest, or
67
+ * (`compact: true`) laying the view out again without them; `hide` replaces what was hidden before, `{}` shows everything. */
49
68
  filter(hide?: Hidden): Promise<SessionResult>;
50
69
  /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
51
70
  scene(): Promise<Scene>;
71
+ /**
72
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns. In a resident WASM session called
73
+ * directly, the arrays are views into the engine's memory, valid until the next request to the session (copy what
74
+ * you keep); through a worker they are copies transferred once; otherwise they are built from the scene.
75
+ */
76
+ columns(): Promise<SceneColumns>;
52
77
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
53
78
  exportSnapshot(): Promise<Snapshot | null>;
54
79
  /** Whether the snapshot stays in the engine. */
@@ -61,6 +86,10 @@ export interface Session {
61
86
  export interface ResidentSession {
62
87
  run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
63
88
  close(): unknown;
89
+ /** Provisional (ADR 0019, step 4): the scene as columns, where the engine keeps them (WASM, a worker). */
90
+ columns?(): SceneColumns | Promise<SceneColumns>;
91
+ /** Provisional (step 4): an `overview` request answered with typed arrays for the numbers, where the engine can. */
92
+ overview?(request: EngineRequest, init?: {copy?: boolean}): EngineResponse | Promise<EngineResponse>;
64
93
  }
65
94
 
66
95
  /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
@@ -118,6 +147,13 @@ export interface OverviewSession {
118
147
  open(graph: Graph, request?: OverviewSessionRequest): Promise<OverviewAnswer>;
119
148
  /** Lays out the graph again; `start` without positions continues from the last overview (same cluster options). */
120
149
  layOut(request?: OverviewSessionRequest): Promise<OverviewAnswer>;
150
+ /** Provisional: the paths between two nodes of the overview's graph, read only (`GraphTrace`). */
151
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<GraphTrace>>;
152
+ /** Provisional: the nodes within `hops` of a node (or of each of a list) of the overview's graph, read only. */
153
+ neighbourhood(
154
+ nodeId: string | string[],
155
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
156
+ ): Promise<ReadAnswer<GraphNeighbourhood>>;
121
157
  /** The last overview, or null. */
122
158
  readonly overview: OverviewAnswer['overview'] | null;
123
159
  /** Whether the graph stays in the engine. */
@@ -131,7 +167,17 @@ export function createOverviewSession(
131
167
  run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
132
168
  openSession?: () => ResidentSession | Promise<ResidentSession>;
133
169
  },
134
- init?: {resident?: boolean | 'auto'},
170
+ init?: {
171
+ resident?: boolean | 'auto';
172
+ /**
173
+ * Provisional (ADR 0019, step 4): the overview's numbers (`parent`, `x`, `y`, `r`, `kind`, `edges`, `links`) as typed
174
+ * arrays instead of JSON arrays, moved without JSON (copied once out of the engine's memory, transferred from a
175
+ * worker). Needs a resident session in an engine that offers `overview` (WASM, a worker); an answer says so
176
+ * otherwise. Default false: the arrays are plain, as before. Typed arrays index like arrays; a `start` built from
177
+ * them is sent as plain arrays.
178
+ */
179
+ columns?: boolean;
180
+ },
135
181
  ): OverviewSession;
136
182
 
137
183
  /** The most nodes an import selects for its view; the default of `Session.import`'s limit. */
package/session.js CHANGED
@@ -6,6 +6,8 @@
6
6
  // layout version to every change, runs changes one after the other on the newest snapshot, and never applies an answer
7
7
  // that was overtaken: after a new `import`, or `reset`, a change still under way resolves to `{ok: false, stale: true}`.
8
8
 
9
+ import {columnsOfScene} from './columns.js';
10
+
9
11
  /**
10
12
  * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
11
13
  * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
@@ -31,7 +33,18 @@ export function workerRun(worker, {onPublication} = {}) {
31
33
  run.openSession = async () => {
32
34
  const opened = await post({session: 'open'});
33
35
  if (!opened.ok) throw Error(opened.error);
34
- return {run: request => post({session: opened.session, request}), close: () => post({session: opened.session, close: true})};
36
+ return {
37
+ run: request => post({session: opened.session, request}),
38
+ close: () => post({session: opened.session, close: true}),
39
+ // Provisional (ADR 0019, step 4): the columns arrive as transferred buffers, copied once in the worker.
40
+ columns: async () => {
41
+ const answer = await post({session: opened.session, columns: true});
42
+ if (!answer.ok) throw Error(answer.error);
43
+ return answer.columns;
44
+ },
45
+ // Provisional: an overview request answered with typed arrays (see `createEngine`'s `overview`).
46
+ overview: request => post({session: opened.session, request, overview: true}),
47
+ };
35
48
  };
36
49
  return run;
37
50
  }
@@ -175,12 +188,31 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
175
188
  return call({op: 'trace', snapshot, from, to, mode, ...(edgeKinds ? {edgeKinds} : {})});
176
189
  },
177
190
 
191
+ /**
192
+ * Provisional: the nodes within `hops` edges (default 1) of `nodeId` (a node id or a list), read only:
193
+ * `{ok, nodes, edges, hops, visible: {nodes, routes}, distance}` as for `trace`; `nodes` can go to `reveal`.
194
+ * `direction`: `out`, `in` or `both` (default); `edgeKinds`: follow only edges of these kinds.
195
+ */
196
+ async neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
197
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
198
+ return call({op: 'neighbourhood', snapshot, ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
199
+ ...(hops !== undefined ? {hops} : {}), ...(direction ? {direction} : {}), ...(edgeKinds ? {edgeKinds} : {})});
200
+ },
201
+
202
+ /**
203
+ * Provisional: changes the graph without a new import: `{nodes, edges, removeNodes, removeEdges}` (removals first; a
204
+ * removed node takes what it holds and its edges along). The view keeps its state; with a level of detail,
205
+ * communities or groups it is laid out as a toggle lays it out, otherwise again from where it was.
206
+ */
207
+ patch(patch) { return change({op: 'patch', patch}); },
208
+
178
209
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
179
210
  reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
180
211
 
181
212
  /**
182
- * Provisional: hides nodes by kind or id (each with what it holds) and edges by kind, keeping the place of the rest.
183
- * `hide` replaces what was hidden before; `{}` shows everything again.
213
+ * Provisional: hides nodes by kind or id (each with what it holds) and edges by kind, keeping the place of the rest;
214
+ * with `compact: true` the view is laid out again without them, so the rest closes up. `hide` replaces what was hidden
215
+ * before; `{}` shows everything again.
184
216
  */
185
217
  filter(hide = {}) { return change({op: 'filter', hide}); },
186
218
 
@@ -196,6 +228,23 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
196
228
  return answer.scene;
197
229
  },
198
230
 
231
+ /**
232
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns (`SceneColumns`): id tables and typed
233
+ * arrays for bounds, parents, flags and route points. In a resident WASM session called directly, the arrays are
234
+ * views into the engine's memory (no copy), valid until the next request to the session; through a worker they are
235
+ * copies transferred once; for a backend or a session that sends the snapshot they are built from the scene. The
236
+ * content is the same in every case.
237
+ */
238
+ async columns() {
239
+ if (!snapshot) throw Error('Nothing imported yet.');
240
+ if (resident) {
241
+ await queue;
242
+ const kept = await opened;
243
+ if (typeof kept.columns === 'function') return kept.columns();
244
+ }
245
+ return columnsOfScene(await this.scene());
246
+ },
247
+
199
248
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
200
249
  async exportSnapshot() {
201
250
  if (!snapshot) return null;
@@ -217,9 +266,18 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
217
266
  };
218
267
  }
219
268
 
269
+ // A request whose `start` positions are typed arrays, with plain arrays instead (JSON has no typed arrays).
270
+ const plain = request => {
271
+ const start = request.start;
272
+ if (!start || !['x', 'y', 'r'].some(k => ArrayBuffer.isView(start[k]))) return request;
273
+ const fixed = {...start};
274
+ for (const k of ['x', 'y', 'r']) if (ArrayBuffer.isView(fixed[k])) fixed[k] = Array.from(fixed[k]);
275
+ return {...request, start: fixed};
276
+ };
277
+
220
278
  // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
221
- // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` compared as given.
222
- const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null]);
279
+ // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` and `hubs` compared as given.
280
+ const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null, options?.hubs ?? null]);
223
281
 
224
282
  /**
225
283
  * Provisional (ADR 0019 for the overview): an overview of one graph, laid out again as the host asks, with the graph kept
@@ -228,7 +286,7 @@ const clustersOf = options => JSON.stringify([options?.communities ?? 120, optio
228
286
  * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
229
287
  * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
230
288
  */
231
- export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
289
+ export function createOverviewSession(run, {resident: wanted = 'auto', columns = false} = {}) {
232
290
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
233
291
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
234
292
  const opened = resident ? Promise.resolve(run.openSession()) : null;
@@ -236,7 +294,21 @@ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
236
294
  let graph = null, started = false, last = null, clusters = null, generation = 0, queue = Promise.resolve();
237
295
 
238
296
  const send = async request => {
239
- if (resident) return (await opened).run(request);
297
+ if (resident) {
298
+ // On the graph the engine has, only what moves comes back (`positionsOnly`) while the clusters stay; it is put
299
+ // together with the last overview here, so every answer is a whole overview.
300
+ const asked = !request.graph && last ? {...request, positionsOnly: true} : request;
301
+ const kept = await opened;
302
+ // With `columns` the numbers come back as typed arrays (views are copied: `last` outlives the next request); a
303
+ // `start` a host built from them is sent as plain arrays.
304
+ if (columns && typeof kept.overview !== 'function') return {ok: false, error: 'This engine has no columnar overview'};
305
+ const answer = await (columns ? kept.overview(plain(asked), {copy: true}) : kept.run(asked));
306
+ if (answer.ok && answer.overview?.positionsOnly) {
307
+ const {positionsOnly: _moved, ...moved} = answer.overview;
308
+ return {...answer, overview: {...last, ...moved}};
309
+ }
310
+ return answer;
311
+ }
240
312
  const sent = {...request, graph: request.graph ?? graph};
241
313
  const start = request.start;
242
314
  if (start && start.x === undefined) {
@@ -246,6 +318,17 @@ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
246
318
  }
247
319
  return run(sent);
248
320
  };
321
+ // A read of the overview's graph, after the changes before it: the session's graph, or the one kept here.
322
+ const read = request => {
323
+ const mine = generation;
324
+ const result = queue.then(async () => {
325
+ if (!started) return {ok: false, error: 'No graph yet: open one first.'};
326
+ const answer = resident ? await (await opened).run(request) : await run({...request, graph});
327
+ return mine === generation ? answer : {ok: false, stale: true, error: 'A new graph overtook this read.'};
328
+ });
329
+ queue = result.catch(() => {});
330
+ return result;
331
+ };
249
332
  const enqueue = (request, fresh) => {
250
333
  if (fresh) generation++;
251
334
  const mine = generation;
@@ -276,6 +359,18 @@ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
276
359
  const {graph: _ignored, ...rest} = request;
277
360
  return enqueue({...rest, op: 'overview'}, false);
278
361
  },
362
+ /**
363
+ * Provisional: the paths between two nodes of the overview's graph (`overviewTrace`: `{ok, found, reversed, length,
364
+ * nodes, edges}`), read only; `mode` and `edgeKinds` as for `trace`. The viewer's `pathOf` maps them to its discs.
365
+ */
366
+ trace(from, to, {mode, edgeKinds} = {}) {
367
+ return read({op: 'overviewTrace', from, to, ...(mode ? {mode} : {}), ...(edgeKinds ? {edgeKinds} : {})});
368
+ },
369
+ /** Provisional: the nodes within `hops` of a node of the overview's graph (`overviewNeighbourhood`), read only. */
370
+ neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
371
+ return read({op: 'overviewNeighbourhood', ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
372
+ ...(hops !== undefined ? {hops} : {}), ...(direction ? {direction} : {}), ...(edgeKinds ? {edgeKinds} : {})});
373
+ },
279
374
  /** The last overview (`{ids, parent, x, y, r, …}`), or null. */
280
375
  get overview() { return last; },
281
376
  /** Whether the graph stays in the engine. */
package/wasm-client.d.ts CHANGED
@@ -16,7 +16,14 @@ export type EngineResponse =
16
16
  * snapshot stays in the engine: its requests leave the snapshot out, and its answers bring the scene.
17
17
  */
18
18
  export type Run = ((request: EngineRequest) => EngineResponse) & {
19
- openSession?: () => {run(request: EngineRequest): EngineResponse; close(): void};
19
+ openSession?: () => {
20
+ run(request: EngineRequest): EngineResponse;
21
+ close(): void;
22
+ /** Provisional (step 4): the scene as columns; the numbers are views into the module's memory, valid until the next request. */
23
+ columns?(): import('./columns.js').SceneColumns;
24
+ /** Provisional (step 4): an `overview` request answered with typed arrays; `copy` copies them out of the memory. */
25
+ overview?(request: EngineRequest, init?: {copy?: boolean}): EngineResponse;
26
+ };
20
27
  };
21
28
 
22
29
  export interface CreateEngineOptions {
package/wasm-client.js CHANGED
@@ -31,7 +31,39 @@ export async function createEngine(bytes,{onPublish}={}) {
31
31
  if(api.lw_session_open){
32
32
  run.openSession=()=>{
33
33
  const id=api.lw_session_open();
34
- return {run:input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len)),close:()=>api.lw_session_close(id)};
34
+ const run=input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len));
35
+ // Provisional (ADR 0019, step 4): the scene as columns. The numbers are typed-array views into the module's memory,
36
+ // not copies: valid until the next request to this session (a change drops them) or until the memory grows, so a
37
+ // host that keeps them copies them (`slice()`). The id tables are copies.
38
+ const views={f32:Float32Array,u32:Uint32Array,i32:Int32Array,f64:Float64Array};
39
+ // `listed`: name, type and length of each column as the engine described them; `read(index)` its address and bytes.
40
+ const viewsOf=(listed,read,copy)=>{
41
+ const result={};
42
+ listed.forEach((c,index)=>{
43
+ const answer=read(index);
44
+ const ptr=Number(answer & 0xffffffffn),bytes=Number(answer >> 32n);
45
+ const view=new views[c.type](api.memory.buffer,ptr,bytes/views[c.type].BYTES_PER_ELEMENT);
46
+ result[c.name]=copy?view.slice():view;
47
+ });
48
+ return result;
49
+ };
50
+ const columns=()=>{
51
+ const meta=run({op:'columns'});
52
+ if(!meta.ok) throw Error(meta.error);
53
+ const {ok,columns:listed,...result}=meta;
54
+ return {...result,...viewsOf(listed,index=>api.lw_session_column(id,index),false)};
55
+ };
56
+ // Provisional: an `overview` request whose numbers come back as typed arrays instead of JSON arrays (`parent`, `x`,
57
+ // `y`, `r`, `kind`, `edges`, `links`; a continuation with `positionsOnly` only `x`, `y` and `r`), in an answer shaped
58
+ // like the JSON one. `copy` (default false) copies them out of the module's memory, for a host that keeps them past
59
+ // its next request; views are valid only until then.
60
+ const overview=(request,{copy=false}={})=>{
61
+ const answer=run({...request,columns:true});
62
+ if(!answer.ok) return answer;
63
+ const {columns:listed,...rest}=answer.overview;
64
+ return {...answer,overview:{...rest,...viewsOf(listed,index=>api.lw_session_overview_column(id,index),copy)}};
65
+ };
66
+ return {run,close:()=>api.lw_session_close(id),...(api.lw_session_column?{columns}:{}),...(api.lw_session_overview_column?{overview}:{})};
35
67
  };
36
68
  }
37
69
  return run;
package/worker.js CHANGED
@@ -26,6 +26,20 @@ self.onmessage=async({data})=>{
26
26
  const session=sessions.get(data.session);
27
27
  if(!session)throw Error('Unknown session');
28
28
  if(data.close){session.close();sessions.delete(data.session);self.postMessage({requestId:data.requestId,ok:true});return;}
29
+ if(data.columns){
30
+ // The page cannot view this module's memory: copy each column once and hand the copies over (transferred, not cloned).
31
+ if(!session.columns)throw Error('This engine has no columns');
32
+ const result=session.columns();const transfer=[];
33
+ for(const [k,v] of Object.entries(result))if(ArrayBuffer.isView(v)){result[k]=v.slice();transfer.push(result[k].buffer);}
34
+ self.postMessage({requestId:data.requestId,ok:true,columns:result},transfer);return;
35
+ }
36
+ if(data.overview){
37
+ // As for the scene's columns: the numbers of the overview are copied once and transferred.
38
+ if(!session.overview)throw Error('This engine has no columnar overview');
39
+ const result=session.overview(data.request,{copy:true});const transfer=[];
40
+ if(result.ok)for(const v of Object.values(result.overview))if(ArrayBuffer.isView(v))transfer.push(v.buffer);
41
+ self.postMessage({requestId:data.requestId,...result},transfer);return;
42
+ }
29
43
  running=data.requestId;const result=session.run(data.request);running=null;
30
44
  self.postMessage({requestId:data.requestId,...result});return;
31
45
  }