@arqlet/engine-client 0.5.0 → 0.7.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,114 @@
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
+ /** Provisional: each node's `childCount` and `hiddenCount`, `NONE` when absent. */
26
+ nodeChildCount: Uint32Array;
27
+ nodeHiddenCount: Uint32Array;
28
+
29
+ /** Route ids by route index. */
30
+ routeIds: string[];
31
+ /** Node index of each route's ends, `NONE` when the end is not a node of the scene. */
32
+ routeSource: Uint32Array;
33
+ routeTarget: Uint32Array;
34
+ routeWeight: Uint32Array;
35
+ /** Bits of `ROUTE_FLAGS`. */
36
+ routeFlags: Uint32Array;
37
+ /** One more than the routes: route `i` is the points `routeOffsets[i]` to `routeOffsets[i + 1]` of `routePoints`. */
38
+ routeOffsets: Uint32Array;
39
+ /** x and y alternating, all routes one after the other. */
40
+ routePoints: Float32Array;
41
+ /** Each route's kind (index into `routeKinds`, '' for none), the edges it stands for in the other direction (`NONE`
42
+ * when it is not a two-way route), and the edges of a bundle (indices into `edgeIds`, behind `routeMemberOffsets`). */
43
+ routeKinds: string[];
44
+ routeKind: Uint32Array;
45
+ routeBackWeight: Uint32Array;
46
+ routeMemberOffsets: Uint32Array;
47
+ routeMembers: Uint32Array;
48
+
49
+ /** Port ids by port index. */
50
+ portIds: string[];
51
+ /** The edges that ports and boundary crossings name, each once. */
52
+ edgeIds: string[];
53
+ /** Node index of each port's node. */
54
+ portNode: Uint32Array;
55
+ /** Index into `edgeIds`. */
56
+ portEdge: Uint32Array;
57
+ /** Bits of `PORT_FLAGS`. */
58
+ portFlags: Uint32Array;
59
+ /** Values of `SIDES`. */
60
+ portSide: Uint32Array;
61
+ /** x and y alternating. */
62
+ portPosition: Float32Array;
63
+
64
+ /** Boundary crossings: edge (index into `edgeIds`), container (node index), ordinal, side, flags (bit 0: derived), position. */
65
+ crossingEdge: Uint32Array;
66
+ crossingContainer: Uint32Array;
67
+ crossingOrdinal: Uint32Array;
68
+ crossingSide: Uint32Array;
69
+ crossingFlags: Uint32Array;
70
+ crossingPosition: Float32Array;
71
+
72
+ /** Placed labels: id and text by label index, `labelKind` indexes `labelKinds`. */
73
+ labelIds: string[];
74
+ labelTexts: string[];
75
+ labelKinds: string[];
76
+ labelKind: Uint32Array;
77
+ /** x, y, width, height per label. */
78
+ labelBounds: Float32Array;
79
+
80
+ /** Rows of the nodes' content, node by node: id and label by row index, the node (index), bounds (four per row). */
81
+ rowIds: string[];
82
+ rowLabels: string[];
83
+ rowNode: Uint32Array;
84
+ rowBounds: Float32Array;
85
+
86
+ /** Conflicts: kind (index into `conflictKinds`) and reason by conflict index; the nodes and routes each names are indices
87
+ * (`NONE` for one outside the scene) in `conflictNodes` and `conflictRoutes`, behind the offsets (conflicts + 1). */
88
+ conflictKinds: string[];
89
+ conflictReasons: string[];
90
+ conflictKind: Uint32Array;
91
+ conflictNodeOffsets: Uint32Array;
92
+ conflictNodes: Uint32Array;
93
+ conflictRouteOffsets: Uint32Array;
94
+ conflictRoutes: Uint32Array;
95
+
96
+ /** Where bus lines branch: x and y alternating. */
97
+ junctions: Float32Array;
98
+ /** x, y, width, height of everything drawn, with its margin (full precision). */
99
+ bounds: [number, number, number, number];
100
+ showPorts: boolean;
101
+ /** The explicit buses, each as its edges' ids. */
102
+ buses: string[][];
103
+ }
104
+
105
+ /** "No node" in an index column. */
106
+ export const NONE: number;
107
+ export const NODE_FLAGS: {readonly container: 1; readonly aggregate: 2; readonly collapsed: 4; readonly invalid: 8};
108
+ export const ROUTE_FLAGS: {readonly invalid: 1; readonly rounded: 2};
109
+ export const PORT_FLAGS: {readonly explicit: 1; readonly target: 2};
110
+ export const SIDES: {readonly left: 0; readonly right: 1; readonly top: 2; readonly bottom: 3};
111
+ export const SHAPES: {readonly rect: 0; readonly square: 1; readonly circle: 2; readonly busLine: 3};
112
+
113
+ /** The columns of a scene object, as the engine builds them (`f32` coordinates). Provisional. */
114
+ export function columnsOfScene(scene: Scene): SceneColumns;
package/columns.js ADDED
@@ -0,0 +1,165 @@
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 nodeChildCount = new Uint32Array(nodes.length);
60
+ const nodeHiddenCount = new Uint32Array(nodes.length);
61
+ const nodeKinds = table();
62
+ nodes.forEach((n, i) => {
63
+ nodeParent[i] = n.parentId == null ? NONE : at(n.parentId);
64
+ nodeFlags[i] = (n.container ? 1 : 0) | (n.aggregate ? 2 : 0) | (n.collapsed ? 4 : 0) | (n.invalid ? 8 : 0);
65
+ nodeKind[i] = nodeKinds.id(n.kind);
66
+ nodeShape[i] = SHAPES[n.shape] ?? 0;
67
+ nodeChildCount[i] = n.childCount ?? NONE;
68
+ nodeHiddenCount[i] = n.hiddenCount ?? NONE;
69
+ });
70
+
71
+ const routeSource = new Uint32Array(routes.length);
72
+ const routeTarget = new Uint32Array(routes.length);
73
+ const routeWeight = new Uint32Array(routes.length);
74
+ const routeFlags = new Uint32Array(routes.length);
75
+ const routeKinds = table();
76
+ const routeKind = new Uint32Array(routes.length);
77
+ const routeBackWeight = new Uint32Array(routes.length);
78
+ const routeOffsets = new Uint32Array(routes.length + 1);
79
+ let total = 0;
80
+ for (const r of routes) total += r.points.length;
81
+ const routePoints = new Float32Array(total * 2);
82
+ let cursor = 0;
83
+ routes.forEach((r, i) => {
84
+ routeSource[i] = at(r.source);
85
+ routeTarget[i] = at(r.target);
86
+ routeWeight[i] = Math.min(r.weight ?? 0, NONE);
87
+ routeFlags[i] = (r.invalid ? 1 : 0) | (r.rounded ? 2 : 0);
88
+ routeKind[i] = routeKinds.id(r.kind ?? '');
89
+ routeBackWeight[i] = r.backWeight == null ? NONE : Math.min(r.backWeight, NONE - 1);
90
+ for (const p of r.points) { routePoints[cursor++] = p.x; routePoints[cursor++] = p.y; }
91
+ routeOffsets[i + 1] = cursor / 2;
92
+ });
93
+
94
+ // Ports and boundary crossings name edges; the edges are numbered once, ports first.
95
+ const edges = table();
96
+ const portNode = Uint32Array.from(ports, p => at(p.nodeId));
97
+ const portEdge = Uint32Array.from(ports, p => edges.id(p.edgeId));
98
+ const portFlags = Uint32Array.from(ports, p => (p.explicit ? 1 : 0) | (p.endpoint === 'target' ? 2 : 0));
99
+ const portSide = Uint32Array.from(ports, p => SIDES[p.side]);
100
+ const crossingEdge = Uint32Array.from(crossings, x => edges.id(x.edgeId));
101
+ // The edges of bundles come after those of ports and crossings.
102
+ const routeMemberOffsets = [0], routeMembers = [];
103
+ for (const r of routes) {
104
+ for (const member of r.members ?? []) routeMembers.push(edges.id(member));
105
+ routeMemberOffsets.push(routeMembers.length);
106
+ }
107
+ const labelKinds = table();
108
+
109
+ const conflictKinds = table();
110
+ const conflictNodes = [], conflictRoutes = [], conflictNodeOffsets = [0], conflictRouteOffsets = [0];
111
+ for (const k of conflicts) {
112
+ for (const id of k.nodes) conflictNodes.push(at(id));
113
+ for (const id of k.routes) conflictRoutes.push(atRoute(id));
114
+ conflictNodeOffsets.push(conflictNodes.length);
115
+ conflictRouteOffsets.push(conflictRoutes.length);
116
+ }
117
+ const conflictKind = Uint32Array.from(conflicts, k => conflictKinds.id(k.kind));
118
+
119
+ const rows = [];
120
+ nodes.forEach((n, i) => { for (const row of n.rows ?? []) rows.push({row, node: i}); });
121
+ const b = scene.bounds;
122
+
123
+ return {
124
+ schemaVersion: scene.schemaVersion,
125
+ revision: scene.revision,
126
+ layoutVersion: scene.layoutVersion,
127
+ nodeIds: nodes.map(n => n.id),
128
+ nodeLabels: nodes.map(n => n.label),
129
+ nodeKinds: nodeKinds.items,
130
+ routeIds: routes.map(r => r.id),
131
+ routeKinds: routeKinds.items,
132
+ portIds: ports.map(p => p.id),
133
+ edgeIds: edges.items,
134
+ labelIds: labels.map(l => l.id),
135
+ labelTexts: labels.map(l => l.text),
136
+ labelKinds: labelKinds.items,
137
+ rowIds: rows.map(r => r.row.id),
138
+ rowLabels: rows.map(r => r.row.label),
139
+ conflictKinds: conflictKinds.items,
140
+ conflictReasons: conflicts.map(k => k.reason),
141
+ buses: scene.buses ?? [],
142
+ bounds: b ? [b.x, b.y, b.width, b.height] : [0, 0, 0, 0],
143
+ showPorts: Boolean(scene.showPorts),
144
+ nodeBounds, nodeParent, nodeFlags, nodeKind, nodeShape, nodeChildCount, nodeHiddenCount,
145
+ routeSource, routeTarget, routeWeight, routeFlags, routeOffsets, routePoints,
146
+ routeKind, routeBackWeight, routeMemberOffsets: Uint32Array.from(routeMemberOffsets), routeMembers: Uint32Array.from(routeMembers),
147
+ portNode, portEdge, portFlags, portSide, portPosition: points(ports, p => p.position),
148
+ crossingEdge,
149
+ crossingContainer: Uint32Array.from(crossings, x => at(x.containerId)),
150
+ crossingOrdinal: Uint32Array.from(crossings, x => Math.min(x.ordinal, NONE)),
151
+ crossingSide: Uint32Array.from(crossings, x => SIDES[x.side]),
152
+ crossingFlags: Uint32Array.from(crossings, x => (x.derived ? 1 : 0)),
153
+ crossingPosition: points(crossings, x => x.position),
154
+ labelKind: Uint32Array.from(labels, l => labelKinds.id(l.kind)),
155
+ labelBounds: rects(labels, l => l.bounds),
156
+ rowNode: Uint32Array.from(rows, r => r.node),
157
+ rowBounds: rects(rows, r => r.row.bounds),
158
+ conflictKind,
159
+ conflictNodeOffsets: Uint32Array.from(conflictNodeOffsets),
160
+ conflictNodes: Uint32Array.from(conflictNodes),
161
+ conflictRouteOffsets: Uint32Array.from(conflictRouteOffsets),
162
+ conflictRoutes: Uint32Array.from(conflictRoutes),
163
+ junctions: points(scene.junctions ?? [], p => p),
164
+ };
165
+ }
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.5.0",
3
+ "version": "0.7.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.5.0"
80
+ "@arqlet/contracts": "^0.7.0"
75
81
  },
76
82
  "scripts": {
77
83
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,7 +1,33 @@
1
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. */
6
+ /** Provisional (drag API): a move gesture of `Session.drag`. */
7
+ export interface DragHandle {
8
+ /** The node being moved. */
9
+ readonly node: string;
10
+ /** Whether the gesture still takes positions (not dropped, cancelled or refused). */
11
+ readonly active: boolean;
12
+ /** Steps sent, positions replaced by a newer one before they were sent, and steps the engine applied. */
13
+ readonly stats: {sent: number; coalesced: number; applied: number};
14
+ /** The answer to picking the node up (the first step). */
15
+ readonly begun: Promise<SessionResult>;
16
+ /**
17
+ * A newer position (and optionally newer positions of the others). Positions that arrive while one is computed replace
18
+ * each other: only the newest is sent. Resolves with the answer of the step that carried it, or `{ok: true, unchanged}`
19
+ * when a newer position took its place.
20
+ */
21
+ move(position: {x: number; y: number}, others?: Record<string, {x: number; y: number}>): Promise<SessionResult>;
22
+ /**
23
+ * Applies the last position and ends the gesture; the node stays pinned there, or with `release` the layout may move it
24
+ * again. With `settle`, force-directed areas settle afterwards (`op: settle`).
25
+ */
26
+ drop(init?: {release?: boolean; settle?: boolean}): Promise<SessionResult>;
27
+ /** Ends the gesture and puts the node (and the others) back where they were. */
28
+ cancel(): Promise<SessionResult>;
29
+ }
30
+
5
31
  export interface SessionResult {
6
32
  ok: boolean;
7
33
  snapshot?: Snapshot;
@@ -60,6 +86,19 @@ export interface Session {
60
86
  * where it was.
61
87
  */
62
88
  patch(patch: GraphPatch): Promise<SessionResult>;
89
+ /**
90
+ * Provisional (drag API): pins `nodeId` at `position` (in its parent's frame, as `toReactFlow` gives `position`), or
91
+ * where it is now. The layout keeps a pinned node in place.
92
+ */
93
+ pin(nodeId: string, position?: {x: number; y: number}): Promise<SessionResult>;
94
+ /** Provisional (drag API): releases the pin of `nodeId`; the layout may move it again. */
95
+ unpin(nodeId: string): Promise<SessionResult>;
96
+ /**
97
+ * Provisional (drag API): starts moving leaf `nodeId` to `position` (in its parent's frame). `others` maps further
98
+ * nodes moved with it (a selection) to their positions; the set is fixed for the gesture. Each applied step changes the
99
+ * session's snapshot (`onChange`); other changes wait until the gesture ends.
100
+ */
101
+ drag(nodeId: string, position: {x: number; y: number}, init?: {others?: Record<string, {x: number; y: number}>}): DragHandle;
63
102
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
64
103
  reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
65
104
  /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest, or
@@ -67,6 +106,12 @@ export interface Session {
67
106
  filter(hide?: Hidden): Promise<SessionResult>;
68
107
  /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
69
108
  scene(): Promise<Scene>;
109
+ /**
110
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns. In a resident WASM session called
111
+ * directly, the arrays are views into the engine's memory, valid until the next request to the session (copy what
112
+ * you keep); through a worker they are copies transferred once; otherwise they are built from the scene.
113
+ */
114
+ columns(): Promise<SceneColumns>;
70
115
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
71
116
  exportSnapshot(): Promise<Snapshot | null>;
72
117
  /** Whether the snapshot stays in the engine. */
@@ -79,6 +124,10 @@ export interface Session {
79
124
  export interface ResidentSession {
80
125
  run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
81
126
  close(): unknown;
127
+ /** Provisional (ADR 0019, step 4): the scene as columns, where the engine keeps them (WASM, a worker). */
128
+ columns?(): SceneColumns | Promise<SceneColumns>;
129
+ /** Provisional (step 4): an `overview` request answered with typed arrays for the numbers, where the engine can. */
130
+ overview?(request: EngineRequest, init?: {copy?: boolean}): EngineResponse | Promise<EngineResponse>;
82
131
  }
83
132
 
84
133
  /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
@@ -156,7 +205,17 @@ export function createOverviewSession(
156
205
  run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
157
206
  openSession?: () => ResidentSession | Promise<ResidentSession>;
158
207
  },
159
- init?: {resident?: boolean | 'auto'},
208
+ init?: {
209
+ resident?: boolean | 'auto';
210
+ /**
211
+ * Provisional (ADR 0019, step 4): the overview's numbers (`parent`, `x`, `y`, `r`, `kind`, `edges`, `links`) as typed
212
+ * arrays instead of JSON arrays, moved without JSON (copied once out of the engine's memory, transferred from a
213
+ * worker). Needs a resident session in an engine that offers `overview` (WASM, a worker); an answer says so
214
+ * otherwise. Default false: the arrays are plain, as before. Typed arrays index like arrays; a `start` built from
215
+ * them is sent as plain arrays.
216
+ */
217
+ columns?: boolean;
218
+ },
160
219
  ): OverviewSession;
161
220
 
162
221
  /** 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
  }
@@ -72,6 +85,8 @@ export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
72
85
  * chooses: `'auto'` (default) where the engine can, `true` always (an error without it), `false` never (every request
73
86
  * sends the snapshot, as before 0.4).
74
87
  */
88
+ let dragCounter = 0;
89
+
75
90
  export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
76
91
  let snapshot = null;
77
92
  let generation = 0;
@@ -193,6 +208,79 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
193
208
  */
194
209
  patch(patch) { return change({op: 'patch', patch}); },
195
210
 
211
+ /**
212
+ * Provisional (drag API): pins `nodeId` at `position` (in its parent's frame, as `toReactFlow` gives `position`), or
213
+ * where it is now; the layout keeps it there.
214
+ */
215
+ pin(nodeId, position) { return change({op: 'pin', nodeId, ...(position ? {position} : {})}); },
216
+
217
+ /** Provisional (drag API): releases the pin of `nodeId`; the layout may move it again. */
218
+ unpin(nodeId) { return change({op: 'pin', nodeId, unpin: true}); },
219
+
220
+ /**
221
+ * Provisional (drag API): starts moving leaf `nodeId` to `position` (in its parent's frame). `others` maps further
222
+ * nodes moved with it (a selection) to their positions; the set is fixed for the gesture. Returns a handle:
223
+ * `move(position, others?)` sends a newer position (positions that arrive while one is computed replace each other, so
224
+ * only the newest is sent); `drop({release, settle})` applies the last position and ends the gesture, keeping the node
225
+ * pinned there (or releasing the pin with `release`), then with `settle` lets force-directed areas settle; `cancel()`
226
+ * puts the node back. Every applied step changes the session's snapshot (`onChange`), so a host redraws from
227
+ * `scene()`. Other changes wait until the gesture ends.
228
+ */
229
+ drag(nodeId, position, {others = {}} = {}) {
230
+ const id = `drag-${++dragCounter}`;
231
+ let seq = 0, pending = null, inFlight = null, ended = false, refused = null;
232
+ const stats = {sent: 0, coalesced: 0, applied: 0};
233
+ const step = (phase, at, release = false) => {
234
+ seq += 1;
235
+ stats.sent += 1;
236
+ return enqueue(() => send({op: 'move', gestureId: id, seq, phase, node: nodeId, position: at, release,
237
+ ...(Object.keys(others).length ? {others} : {})})).then(answer => {
238
+ if (answer.ok) stats.applied += 1; else refused ??= answer;
239
+ return answer;
240
+ });
241
+ };
242
+ // One step at a time; the newest pending position goes next.
243
+ const pump = () => {
244
+ if (inFlight || !pending || refused) return inFlight;
245
+ const at = pending;
246
+ pending = null;
247
+ inFlight = step('update', at).finally(() => { inFlight = null; pump(); });
248
+ return inFlight;
249
+ };
250
+ const begun = step('begin', position);
251
+ const end = async (phase, release, settle) => {
252
+ if (ended) return {ok: false, error: 'The gesture has ended.'};
253
+ ended = true;
254
+ await begun;
255
+ while (inFlight) await inFlight;
256
+ if (phase === 'cancel') pending = null;
257
+ if (pending && !refused) { const at = pending; pending = null; await step('update', at); }
258
+ if (refused) return refused;
259
+ const answer = await step(phase, null, release);
260
+ if (answer.ok && settle) return change({op: 'settle'});
261
+ return answer;
262
+ };
263
+ return {
264
+ /** The node being moved. */
265
+ node: nodeId,
266
+ /** Whether the gesture still takes positions. */
267
+ get active() { return !ended && !refused; },
268
+ /** Steps sent, positions replaced by newer ones before they were sent, and steps applied. */
269
+ get stats() { return {...stats}; },
270
+ /** The answer of the first step (the engine's view after the node was picked up). */
271
+ begun,
272
+ move(at, moved) {
273
+ if (ended || refused) return Promise.resolve(refused ?? {ok: false, error: 'The gesture has ended.'});
274
+ if (pending) stats.coalesced += 1;
275
+ pending = at;
276
+ if (moved) others = moved;
277
+ return begun.then(() => pump() ?? {ok: true, unchanged: true});
278
+ },
279
+ drop({release = false, settle = false} = {}) { return end('finish', release, settle); },
280
+ cancel() { return end('cancel', false, false); },
281
+ };
282
+ },
283
+
196
284
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
197
285
  reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
198
286
 
@@ -215,6 +303,23 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
215
303
  return answer.scene;
216
304
  },
217
305
 
306
+ /**
307
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns (`SceneColumns`): id tables and typed
308
+ * arrays for bounds, parents, flags and route points. In a resident WASM session called directly, the arrays are
309
+ * views into the engine's memory (no copy), valid until the next request to the session; through a worker they are
310
+ * copies transferred once; for a backend or a session that sends the snapshot they are built from the scene. The
311
+ * content is the same in every case.
312
+ */
313
+ async columns() {
314
+ if (!snapshot) throw Error('Nothing imported yet.');
315
+ if (resident) {
316
+ await queue;
317
+ const kept = await opened;
318
+ if (typeof kept.columns === 'function') return kept.columns();
319
+ }
320
+ return columnsOfScene(await this.scene());
321
+ },
322
+
218
323
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
219
324
  async exportSnapshot() {
220
325
  if (!snapshot) return null;
@@ -236,6 +341,15 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
236
341
  };
237
342
  }
238
343
 
344
+ // A request whose `start` positions are typed arrays, with plain arrays instead (JSON has no typed arrays).
345
+ const plain = request => {
346
+ const start = request.start;
347
+ if (!start || !['x', 'y', 'r'].some(k => ArrayBuffer.isView(start[k]))) return request;
348
+ const fixed = {...start};
349
+ for (const k of ['x', 'y', 'r']) if (ArrayBuffer.isView(fixed[k])) fixed[k] = Array.from(fixed[k]);
350
+ return {...request, start: fixed};
351
+ };
352
+
239
353
  // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
240
354
  // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` and `hubs` compared as given.
241
355
  const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null, options?.hubs ?? null]);
@@ -247,7 +361,7 @@ const clustersOf = options => JSON.stringify([options?.communities ?? 120, optio
247
361
  * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
248
362
  * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
249
363
  */
250
- export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
364
+ export function createOverviewSession(run, {resident: wanted = 'auto', columns = false} = {}) {
251
365
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
252
366
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
253
367
  const opened = resident ? Promise.resolve(run.openSession()) : null;
@@ -259,7 +373,11 @@ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
259
373
  // On the graph the engine has, only what moves comes back (`positionsOnly`) while the clusters stay; it is put
260
374
  // together with the last overview here, so every answer is a whole overview.
261
375
  const asked = !request.graph && last ? {...request, positionsOnly: true} : request;
262
- const answer = await (await opened).run(asked);
376
+ const kept = await opened;
377
+ // With `columns` the numbers come back as typed arrays (views are copied: `last` outlives the next request); a
378
+ // `start` a host built from them is sent as plain arrays.
379
+ if (columns && typeof kept.overview !== 'function') return {ok: false, error: 'This engine has no columnar overview'};
380
+ const answer = await (columns ? kept.overview(plain(asked), {copy: true}) : kept.run(asked));
263
381
  if (answer.ok && answer.overview?.positionsOnly) {
264
382
  const {positionsOnly: _moved, ...moved} = answer.overview;
265
383
  return {...answer, overview: {...last, ...moved}};
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
@@ -1,9 +1,11 @@
1
1
  // `onPublish(message)` receives each progressive publication as JSON while the call that produced it is still running.
2
- // The module always imports `lw_publish`; without a callback the messages are dropped.
2
+ // The module always imports `lw_publish` and `lw_now`; without a callback the messages are dropped.
3
3
  export async function createEngine(bytes,{onPublish}={}) {
4
4
  const decoder=new TextDecoder();
5
5
  let api;
6
6
  const imports={env:{
7
+ // The clock for phase timings (`timings: true` on a request); the layout itself never reads it.
8
+ lw_now:()=>performance.now(),
7
9
  lw_publish:(ptr,len)=>{
8
10
  if(!onPublish) return;
9
11
  // Copy out of linear memory now: the module releases the buffer when this returns.
@@ -31,7 +33,39 @@ export async function createEngine(bytes,{onPublish}={}) {
31
33
  if(api.lw_session_open){
32
34
  run.openSession=()=>{
33
35
  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)};
36
+ const run=input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len));
37
+ // Provisional (ADR 0019, step 4): the scene as columns. The numbers are typed-array views into the module's memory,
38
+ // not copies: valid until the next request to this session (a change drops them) or until the memory grows, so a
39
+ // host that keeps them copies them (`slice()`). The id tables are copies.
40
+ const views={f32:Float32Array,u32:Uint32Array,i32:Int32Array,f64:Float64Array};
41
+ // `listed`: name, type and length of each column as the engine described them; `read(index)` its address and bytes.
42
+ const viewsOf=(listed,read,copy)=>{
43
+ const result={};
44
+ listed.forEach((c,index)=>{
45
+ const answer=read(index);
46
+ const ptr=Number(answer & 0xffffffffn),bytes=Number(answer >> 32n);
47
+ const view=new views[c.type](api.memory.buffer,ptr,bytes/views[c.type].BYTES_PER_ELEMENT);
48
+ result[c.name]=copy?view.slice():view;
49
+ });
50
+ return result;
51
+ };
52
+ const columns=()=>{
53
+ const meta=run({op:'columns'});
54
+ if(!meta.ok) throw Error(meta.error);
55
+ const {ok,columns:listed,...result}=meta;
56
+ return {...result,...viewsOf(listed,index=>api.lw_session_column(id,index),false)};
57
+ };
58
+ // Provisional: an `overview` request whose numbers come back as typed arrays instead of JSON arrays (`parent`, `x`,
59
+ // `y`, `r`, `kind`, `edges`, `links`; a continuation with `positionsOnly` only `x`, `y` and `r`), in an answer shaped
60
+ // like the JSON one. `copy` (default false) copies them out of the module's memory, for a host that keeps them past
61
+ // its next request; views are valid only until then.
62
+ const overview=(request,{copy=false}={})=>{
63
+ const answer=run({...request,columns:true});
64
+ if(!answer.ok) return answer;
65
+ const {columns:listed,...rest}=answer.overview;
66
+ return {...answer,overview:{...rest,...viewsOf(listed,index=>api.lw_session_overview_column(id,index),copy)}};
67
+ };
68
+ return {run,close:()=>api.lw_session_close(id),...(api.lw_session_column?{columns}:{}),...(api.lw_session_overview_column?{overview}:{})};
35
69
  };
36
70
  }
37
71
  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
  }