@arqlet/engine-client 0.1.0 → 0.3.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/README.md CHANGED
@@ -5,6 +5,8 @@ The Arqlet engine as WebAssembly (`arqlet.wasm`, included) and its JavaScript ac
5
5
  - `engine.js`: `loadEngine(url?)` (browser via `fetch`, Node from disk), `sceneOf(run, snapshot)`, `createEngineWorker(url?)`;
6
6
  - `wasm-client.js`: `createEngine(bytes, {onPublish})`, the raw binding;
7
7
  - `elk.js`: `createElkLayout(run)`, an `elk.layout(graph)`-style call;
8
+ - `session.js`: `createSession(run)`, a layout session that keeps positions across changes (collapse, expand, …)
9
+ with revision checks, and `workerRun(worker)`, the worker as an asynchronous `run`;
8
10
  - `presets.js`: `presetState` and `applyPreset`.
9
11
 
10
12
  Most users want the [`arqlet`](https://www.npmjs.com/package/arqlet) package, which re-exports these.
package/arqlet.wasm CHANGED
Binary file
package/elk.d.ts CHANGED
@@ -46,7 +46,8 @@ export interface ElkNode extends ElkShape {
46
46
  export interface ElkLayoutOptions {
47
47
  /** Arqlet layout options; they win over the ones translated from `layoutOptions`. */
48
48
  options?: Record<string, unknown>;
49
- /** Runs the refinement after the layout. Default `false`. */
49
+ /** Runs the refinement after the layout. Default `false`. It removes conflicts (routes through nodes, shared lines);
50
+ * a drawing without them comes back the same, a little later. */
50
51
  refine?: boolean;
51
52
  }
52
53
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.1.0",
3
+ "version": "0.3.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",
@@ -43,6 +43,10 @@
43
43
  "types": "./elk.d.ts",
44
44
  "default": "./elk.js"
45
45
  },
46
+ "./session.js": {
47
+ "types": "./session.d.ts",
48
+ "default": "./session.js"
49
+ },
46
50
  "./worker.js": "./worker.js",
47
51
  "./arqlet.wasm": "./arqlet.wasm"
48
52
  },
@@ -51,10 +55,12 @@
51
55
  "wasm-client.js",
52
56
  "presets.js",
53
57
  "elk.js",
58
+ "session.js",
54
59
  "engine.d.ts",
55
60
  "wasm-client.d.ts",
56
61
  "presets.d.ts",
57
62
  "elk.d.ts",
63
+ "session.d.ts",
58
64
  "worker.js",
59
65
  "arqlet.wasm",
60
66
  "README.md",
@@ -65,7 +71,7 @@
65
71
  "access": "public"
66
72
  },
67
73
  "dependencies": {
68
- "@arqlet/contracts": "^0.1.0"
74
+ "@arqlet/contracts": "^0.3.0"
69
75
  },
70
76
  "scripts": {
71
77
  "test": "node --test"
package/session.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type {Graph, Scene, Snapshot} from '@arqlet/contracts';
2
+ import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
3
+
4
+ /** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
5
+ export interface SessionResult {
6
+ ok: boolean;
7
+ snapshot?: Snapshot;
8
+ error?: string;
9
+ stale?: boolean;
10
+ /** `expand`/`collapse`: the container was in that state already; no engine call was made. */
11
+ unchanged?: boolean;
12
+ }
13
+
14
+ /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
15
+ export interface Session {
16
+ /** The current snapshot, or null before the first import. */
17
+ readonly snapshot: Snapshot | null;
18
+ /**
19
+ * Lays out `graph` (nodes with `parentId` are containers) and starts the session on it; changes still under way are
20
+ * dropped. `limit`: the most nodes the first view shows (default: all). `options`: layout options.
21
+ */
22
+ import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
23
+ /** Drops the snapshot; changes still under way resolve as stale. */
24
+ reset(): void;
25
+ /** Whether container `id` is collapsed in the current snapshot. */
26
+ isCollapsed(id: string): boolean;
27
+ /** Collapses or expands container `id`. */
28
+ toggle(id: string): Promise<SessionResult>;
29
+ /** Expands container `id` unless it is open. */
30
+ expand(id: string): Promise<SessionResult>;
31
+ /** Collapses container `id` unless it is collapsed. */
32
+ collapse(id: string): Promise<SessionResult>;
33
+ /** Any other change of the protocol (`direction`, `configure`, `add`, …); snapshot and expected versions are added. */
34
+ apply(request: Omit<EngineRequest, 'snapshot' | 'expectedRevision' | 'expectedLayoutVersion'> & {op: string}): Promise<SessionResult>;
35
+ /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
36
+ scene(): Promise<Scene>;
37
+ }
38
+
39
+ /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
40
+ export function createSession(
41
+ run: Run | ((request: EngineRequest) => Promise<EngineResponse>),
42
+ init?: {onChange?: (snapshot: Snapshot) => void},
43
+ ): Session;
44
+
45
+ /**
46
+ * Wraps a worker of `createEngineWorker` as an asynchronous run. `onPublication` receives the progressive publications
47
+ * of a running request.
48
+ */
49
+ export function workerRun(
50
+ worker: Worker,
51
+ init?: {onPublication?: (requestId: number, message: unknown) => void},
52
+ ): (request: EngineRequest) => Promise<EngineResponse>;
package/session.js ADDED
@@ -0,0 +1,123 @@
1
+ // A layout session (provisional): one graph, its current snapshot, and the changes sent to the engine as operations on
2
+ // it, so that unchanged parts keep their place. Pure: no DOM, no fetch; `run` is the engine (`loadEngine`) or a worker
3
+ // (`workerRun`).
4
+ //
5
+ // The engine refuses a change to an older snapshot ("Stale view request"); the session adds the snapshot's revision and
6
+ // layout version to every change, runs changes one after the other on the newest snapshot, and never applies an answer
7
+ // that was overtaken: after a new `import`, or `reset`, a change still under way resolves to `{ok: false, stale: true}`.
8
+
9
+ /**
10
+ * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
11
+ * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
12
+ */
13
+ export function workerRun(worker, {onPublication} = {}) {
14
+ let next = 0;
15
+ const waiting = new Map();
16
+ worker.addEventListener('message', ({data}) => {
17
+ const pending = waiting.get(data?.requestId);
18
+ if (!pending) return;
19
+ if (data.publication !== undefined) { onPublication?.(data.requestId, data); return; }
20
+ waiting.delete(data.requestId);
21
+ const {requestId, ...response} = data;
22
+ pending(response);
23
+ });
24
+ return request => new Promise(resolve => {
25
+ const requestId = ++next;
26
+ waiting.set(requestId, resolve);
27
+ worker.postMessage({requestId, request});
28
+ });
29
+ }
30
+
31
+ /** Creates a session on `run` (synchronous or asynchronous). `onChange(snapshot)` is called after every applied change. */
32
+ export function createSession(run, {onChange} = {}) {
33
+ let snapshot = null;
34
+ let generation = 0;
35
+ let queue = Promise.resolve();
36
+ const scenes = new WeakMap();
37
+
38
+ // Runs `step` after every change before it; its answer counts only if no import or reset came in between.
39
+ const enqueue = step => {
40
+ const mine = generation;
41
+ const result = queue.then(async () => {
42
+ if (mine !== generation) return {ok: false, stale: true, error: 'The session was reset.'};
43
+ const answer = await step();
44
+ if (mine !== generation) return {ok: false, stale: true, error: 'The session was reset.'};
45
+ if (answer?.ok && answer.snapshot && !answer.unchanged) {
46
+ snapshot = answer.snapshot;
47
+ onChange?.(snapshot);
48
+ }
49
+ return answer;
50
+ });
51
+ queue = result.catch(() => {});
52
+ return result;
53
+ };
54
+
55
+ // A change to the current snapshot; called inside a queued step.
56
+ const send = request => {
57
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
58
+ return run({
59
+ ...request,
60
+ snapshot,
61
+ expectedRevision: snapshot.revision,
62
+ expectedLayoutVersion: snapshot.layoutVersion,
63
+ });
64
+ };
65
+ const change = request => enqueue(() => send(request));
66
+
67
+ const collapsed = id => (snapshot?.collapsedIds ?? []).includes(id);
68
+ // Toggles `id` only when it is not yet in the wanted state, decided and sent in one step.
69
+ const ensure = (id, wantCollapsed) => enqueue(() => (collapsed(id) === wantCollapsed
70
+ ? {ok: true, snapshot, unchanged: true}
71
+ : send({op: 'toggle', nodeId: id})));
72
+
73
+ return {
74
+ /** The current snapshot, or null before the first import. */
75
+ get snapshot() { return snapshot; },
76
+
77
+ /**
78
+ * Lays out `graph` (nodes with `parentId` are containers) and starts the session on it. `limit` is the most nodes
79
+ * the first view shows (containers beyond it start collapsed); `options` are layout options (`docs/configuration.md`).
80
+ * Any change still under way is dropped.
81
+ */
82
+ import(graph, {limit = graph.nodes.length, options} = {}) {
83
+ generation++;
84
+ return enqueue(() => run({op: 'import', graph, limit, ...(options ? {options} : {})}));
85
+ },
86
+
87
+ /** Drops the snapshot; changes still under way resolve as stale. */
88
+ reset() {
89
+ generation++;
90
+ snapshot = null;
91
+ },
92
+
93
+ /** Whether container `id` is collapsed in the current snapshot. */
94
+ isCollapsed: collapsed,
95
+
96
+ /** Collapses or expands container `id`. */
97
+ toggle(id) { return change({op: 'toggle', nodeId: id}); },
98
+
99
+ /** Expands container `id`; `{ok: true, unchanged: true}` when it is open already. */
100
+ expand(id) { return ensure(id, false); },
101
+
102
+ /** Collapses container `id`; `{ok: true, unchanged: true}` when it is collapsed already. */
103
+ collapse(id) { return ensure(id, true); },
104
+
105
+ /**
106
+ * Any other change of the engine's protocol, for example `{op: 'direction', nodeId, direction: 'tb'}`,
107
+ * `{op: 'configure', options}` or `{op: 'add', sourceId, label}`. The snapshot and the expected versions are added.
108
+ */
109
+ apply(request) { return change(request); },
110
+
111
+ /** The scene (drawing) of the current snapshot, computed once per snapshot. */
112
+ async scene() {
113
+ const current = snapshot;
114
+ if (!current) throw Error('Nothing imported yet.');
115
+ const known = scenes.get(current);
116
+ if (known) return known;
117
+ const answer = await run({op: 'scene', snapshot: current});
118
+ if (!answer.ok) throw Error(answer.error);
119
+ scenes.set(current, answer.scene);
120
+ return answer.scene;
121
+ },
122
+ };
123
+ }