@arqlet/engine-client 0.8.0 → 0.10.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
@@ -12,7 +12,7 @@ The Arqlet engine as WebAssembly (`arqlet.wasm`, included) and its JavaScript ac
12
12
  with `subscribe` (for `useSyncExternalStore`), open/close, paging through `+N more`, filters, a path or neighbourhood
13
13
  kept as the highlight, the details of a selected node or edge (`select`, `state.details`) and the hover, back and
14
14
  forward, search (`find`), `focus` for the camera, keyboard navigation (`navigate`, `navigateScene`), bookmarks
15
- (`bookmark`, `openBookmark`, `encodeBookmark`), a look into a collapsed container (`peek`), refinement on a second
15
+ (`bookmark`, `openBookmark`, `encodeBookmark`; `compactBookmark` for a short text in a URL), a look into a collapsed container (`peek`), refinement on a second
16
16
  engine (`refine` option,
17
17
  `workerRefineRun`), and a
18
18
  scene diff per step, snapshots the host made (`adopt`);
@@ -1,6 +1,6 @@
1
1
  # Third-party notices
2
2
 
3
- The WebAssembly engine in this package contains the Rust crates listed below, each under the license named, and their
3
+ The WebAssembly module in this package contains the Rust crates listed below, each under the license named, and their
4
4
  copyright and license notices follow. Arqlet itself is licensed under either of the Apache License, Version 2.0
5
5
  (LICENSE-APACHE) or the MIT license (LICENSE-MIT), at your option.
6
6
 
package/arqlet.wasm CHANGED
Binary file
package/elk.d.ts CHANGED
@@ -49,11 +49,37 @@ export interface ElkLayoutOptions {
49
49
  /** Runs the refinement after the layout. Default `false`. It removes conflicts (routes through nodes, shared lines);
50
50
  * a drawing without them comes back the same, a little later. */
51
51
  refine?: boolean;
52
+ /** Reports where each call's time went in `timings` (#152). Default `false`. */
53
+ timings?: boolean;
54
+ }
55
+
56
+ /** Where a call's time went, in ms (#152). The phases below `layout` are parts of it; 0 where the engine has no clock. */
57
+ export interface ElkTimings {
58
+ total: number;
59
+ layout: number;
60
+ placement: number;
61
+ organicStress: number;
62
+ separation: number;
63
+ repair: number;
64
+ portResolution: number;
65
+ routing: number;
66
+ /** Single pass, parts of `routing`. */
67
+ plan: number;
68
+ channelGrowth: number;
69
+ construction: number;
70
+ fallbackRouting: number;
71
+ finalization: number;
72
+ buses: number;
73
+ /** Outside `layout`: the ELK translation in and out, and a refinement on request. */
74
+ elkTranslation: number;
75
+ refinement: number;
52
76
  }
53
77
 
54
78
  export interface ElkLayout {
55
79
  /** ELK options without an Arqlet counterpart, reported by the last `layout` call. */
56
80
  diagnostics: string[];
81
+ /** With `timings: true`, where the last `layout` call's time went; otherwise `null`. */
82
+ timings: ElkTimings | null;
57
83
  /** Resolves with a copy of `graph`, laid out: positions, sizes, ports, labels and edge `sections`. */
58
84
  layout(graph: ElkNode): Promise<ElkNode>;
59
85
  }
package/elk.js CHANGED
@@ -2,14 +2,17 @@
2
2
  // `createEngine`, a worker or a backend): `layout(graph)` resolves with the graph in ELK's JSON form laid out (`x`, `y`,
3
3
  // sizes, ports, labels and edge `sections`), as `elk.layout(graph)` does. Not a 1:1 ELK: the options without a counterpart are
4
4
  // listed in `diagnostics` after each call (see crates/elk). `options` are Arqlet options that win over the translated
5
- // ones; `refine` runs the refinement after the layout.
6
- export function createElkLayout(run,{options,refine=false}={}) {
5
+ // ones; `refine` runs the refinement after the layout; with `timings` each call reports where its time went in `timings`
6
+ // (ms by phase; all 0 when the engine has no clock).
7
+ export function createElkLayout(run,{options,refine=false,timings=false}={}) {
7
8
  return {
8
9
  diagnostics:[],
10
+ timings:null,
9
11
  async layout(graph) {
10
- const response=await run({op:'elkLayout',graph,...(options?{options}:{}),refine});
12
+ const response=await run({op:'elkLayout',graph,...(options?{options}:{}),refine,...(timings?{timings:true}:{})});
11
13
  if(!response.ok) throw new Error(response.error);
12
14
  this.diagnostics=response.diagnostics;
15
+ this.timings=response.timings??null;
13
16
  return response.graph;
14
17
  },
15
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.8.0",
3
+ "version": "0.10.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",
@@ -84,7 +84,7 @@
84
84
  "access": "public"
85
85
  },
86
86
  "dependencies": {
87
- "@arqlet/contracts": "^0.8.0"
87
+ "@arqlet/contracts": "^0.10.0"
88
88
  },
89
89
  "scripts": {
90
90
  "test": "node --test"
package/session.d.ts CHANGED
@@ -93,7 +93,7 @@ export type DetailTarget = {nodeId: string; edgeId?: never} | {edgeId: string; n
93
93
  /** The answer of a read-only request (`trace`, `neighbourhood`): its fields beside `ok: true`, or the error. */
94
94
  /** Provisional (ADR 0021, M5b): what a query is given besides its text. */
95
95
  export interface QueryInit {
96
- /** The values of the `$name` parameters (JSON values; a map is refused). */
96
+ /** The values of the `$name` parameters (JSON values; an object is a map). */
97
97
  params?: Record<string, unknown>;
98
98
  /** Also map the answer onto the current view (`shown`); costs a few milliseconds on a large view. */
99
99
  view?: boolean;
@@ -103,8 +103,19 @@ export interface QueryInit {
103
103
  maxHops?: number;
104
104
  }
105
105
 
106
- /** A value in a row of a query answer: a JSON value, a node as `{node: id}`, an edge as `{edge: id}`, or a list. */
107
- export type QueryValue = null | boolean | number | string | {node: string} | {edge: string} | QueryValue[];
106
+ /**
107
+ * A value in a row of a query answer: a JSON value or a list. Every object is tagged: a node is `{node: id}`, an edge
108
+ * `{edge: id}`, a map `{map: {key: value}}`.
109
+ */
110
+ export type QueryValue =
111
+ | null
112
+ | boolean
113
+ | number
114
+ | string
115
+ | {node: string}
116
+ | {edge: string}
117
+ | {map: {[key: string]: QueryValue}}
118
+ | QueryValue[];
108
119
 
109
120
  /** Provisional (ADR 0021, M5b): the answer of a query. */
110
121
  export interface QueryAnswer {
@@ -120,7 +131,7 @@ export interface QueryAnswer {
120
131
  contentRevision?: number;
121
132
  /** Content for ids the graph does not have (kept, ignored by the query). */
122
133
  ignoredContent?: number;
123
- /** Content values the query layer has no type for (a map), read as null. */
134
+ /** Content values the query layer has no type for (an integer beyond 64 bits), read as null. */
124
135
  skippedValues?: number;
125
136
  /** With `view: true`: the box that shows each node and the drawn line that carries each edge (null when none). */
126
137
  shown?: {nodes: Record<string, string | null>; edges: Record<string, string | null>};
@@ -147,6 +158,13 @@ export interface Session {
147
158
  * view) at once, the changes still under way resolving as stale.
148
159
  */
149
160
  load(snapshot: Snapshot, options?: {reset?: boolean}): Promise<SessionResult>;
161
+ /** Provisional (#148): keeps the current snapshot under a mark (the same mark while it is unchanged); at most `limit` (default 32). */
162
+ keep(options?: {limit?: number}): Promise<{ok: boolean; mark?: number; error?: string}>;
163
+ /**
164
+ * Provisional (#148): the snapshot kept under `mark` becomes current again with its geometry (next layout version);
165
+ * `evicted` when it is no longer kept, `changed` when the graph changed since.
166
+ */
167
+ recall(mark: number): Promise<SessionResult & {evicted?: boolean; changed?: boolean}>;
150
168
  reset(): void;
151
169
  /** Whether container `id` is collapsed in the current snapshot. */
152
170
  isCollapsed(id: string): boolean;
@@ -305,7 +323,8 @@ export function httpRun(
305
323
 
306
324
  /**
307
325
  * An overview request without `op` and `graph` (`OverviewRequest` in `@arqlet/contracts`): `start` without positions
308
- * continues from the last overview.
326
+ * continues from the last overview, `start.nodes` (places by node id) from the places given, also on a new graph, and
327
+ * keeps their clusters.
309
328
  */
310
329
  export type OverviewSessionRequest = Omit<OverviewRequest, 'graph'>;
311
330
 
@@ -322,7 +341,8 @@ export interface OverviewAnswer {
322
341
  export interface OverviewSession {
323
342
  /** Lays out `graph`; replaces the graph the session had. */
324
343
  open(graph: Graph, request?: OverviewSessionRequest): Promise<OverviewAnswer>;
325
- /** Lays out the graph again; `start` without positions continues from the last overview (same cluster options). */
344
+ /** Lays out the graph again; `start` without positions continues from the last overview (same cluster options).
345
+ * With `edgeData: true` the answer has each edge's kind and weight (ask each time). */
326
346
  layOut(request?: OverviewSessionRequest): Promise<OverviewAnswer>;
327
347
  /** Provisional: the paths between two nodes of the overview's graph, read only (`GraphTrace`). */
328
348
  trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<GraphTrace>>;
@@ -347,8 +367,8 @@ export function createOverviewSession(
347
367
  init?: {
348
368
  resident?: boolean | 'auto';
349
369
  /**
350
- * Provisional (ADR 0019, step 4): the overview's numbers (`parent`, `x`, `y`, `r`, `kind`, `edges`, `links`) as typed
351
- * arrays instead of JSON arrays, moved without JSON (copied once out of the engine's memory, transferred from a
370
+ * Provisional (ADR 0019, step 4): the overview's numbers (`parent`, `x`, `y`, `r`, `kind`, `edges`, `links`, and
371
+ * with `edgeData` `edgeKind` and `edgeWeight`) as typed arrays instead of JSON arrays, moved without JSON (copied once out of the engine's memory, transferred from a
352
372
  * worker). Needs a resident session in an engine that offers `overview` (WASM, a worker); an answer says so
353
373
  * otherwise. Default false: the arrays are plain, as before. Typed arrays index like arrays; a `start` built from
354
374
  * them is sent as plain arrays.
package/session.js CHANGED
@@ -120,6 +120,9 @@ export function createSession(engine, {onChange, resident: wanted = 'auto'} = {}
120
120
  let run = engine;
121
121
  let snapshot = null;
122
122
  let generation = 0;
123
+ // Snapshots kept by mark when the session is not resident (#148); a resident session keeps them in the engine.
124
+ let kept = [];
125
+ let marks = 0;
123
126
  let queue = Promise.resolve();
124
127
  const scenes = new WeakMap();
125
128
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
@@ -187,6 +190,7 @@ export function createSession(engine, {onChange, resident: wanted = 'auto'} = {}
187
190
  // A new view does not wait for the changes still under way: they resolve as stale.
188
191
  generation++;
189
192
  queue = Promise.resolve();
193
+ kept = [];
190
194
  return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
191
195
  },
192
196
 
@@ -196,17 +200,55 @@ export function createSession(engine, {onChange, resident: wanted = 'auto'} = {}
196
200
  */
197
201
  load(snapshot, {reset = false} = {}) {
198
202
  // With `reset` (another view) it does not wait for the changes still under way: they resolve as stale.
203
+ // The same graph keeps the snapshots kept for `recall` (#148); another one (`reset`) drops them.
199
204
  if (reset) {
200
205
  generation++;
201
206
  queue = Promise.resolve();
207
+ kept = [];
202
208
  }
203
- return enqueue(() => (resident ? call({op: 'load', snapshot}) : {ok: true, snapshot}));
209
+ return enqueue(() => (resident ? call({op: 'load', snapshot, keep: !reset}) : {ok: true, snapshot}));
210
+ },
211
+
212
+ /**
213
+ * Provisional (#148): keeps the current snapshot under a mark, `{ok, mark}` (the same mark while it is unchanged), at
214
+ * most `limit` (default 32) of them, the oldest dropped first. With a resident session the engine keeps them (only the
215
+ * mark crosses); otherwise this session does. A new import drops them.
216
+ */
217
+ keep({limit = 32} = {}) {
218
+ return enqueue(async () => {
219
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
220
+ if (resident) return call({op: 'keep', limit});
221
+ const last = kept.at(-1);
222
+ if (last && last.snapshot === snapshot) return {ok: true, mark: last.mark};
223
+ kept.push({mark: ++marks, snapshot});
224
+ if (kept.length > limit) kept.splice(0, kept.length - limit);
225
+ return {ok: true, mark: marks};
226
+ });
227
+ },
228
+
229
+ /**
230
+ * Provisional (#148): makes the snapshot kept under `mark` current again (its geometry as it was) under the next layout
231
+ * version. `{ok: false, evicted: true}` when it is no longer kept, `{ok: false, changed: true}` when the graph changed
232
+ * since (another revision); then lay out again from the decisions (`restore`).
233
+ */
234
+ recall(mark) {
235
+ return enqueue(async () => {
236
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
237
+ if (resident) return call({op: 'recall', mark});
238
+ const entry = kept.find(k => k.mark === mark);
239
+ if (!entry) return {ok: false, evicted: true, error: `The snapshot of mark ${mark} is no longer kept`};
240
+ if (entry.snapshot.revision !== snapshot.revision) {
241
+ return {ok: false, changed: true, error: `The graph changed since mark ${mark}`};
242
+ }
243
+ return {ok: true, snapshot: {...entry.snapshot, layoutVersion: snapshot.layoutVersion + 1}};
244
+ });
204
245
  },
205
246
 
206
247
  /** Drops the snapshot; changes still under way resolve as stale. */
207
248
  reset() {
208
249
  generation++;
209
250
  snapshot = null;
251
+ kept = [];
210
252
  },
211
253
 
212
254
  /** Whether container `id` is collapsed in the current snapshot. */
@@ -532,6 +574,10 @@ const plain = request => {
532
574
  return {...request, start: fixed};
533
575
  };
534
576
 
577
+ // An overview's places by node id, as `start.nodes` takes them, each with its parent's id.
578
+ const placesOf = o => Object.fromEntries(Array.from(o.ids, (id, i) => [id,
579
+ {x: o.x[i], y: o.y[i], r: o.r[i], ...(o.parent[i] >= 0 ? {parent: o.ids[o.parent[i]]} : {})}]));
580
+
535
581
  // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
536
582
  // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` and `hubs` compared as given.
537
583
  const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null, options?.hubs ?? null]);
@@ -540,7 +586,8 @@ const clustersOf = options => JSON.stringify([options?.communities ?? 120, optio
540
586
  * Provisional (ADR 0019 for the overview): an overview of one graph, laid out again as the host asks, with the graph kept
541
587
  * in the engine where it can keep a session (`run.openSession`). `open(graph, request)` lays out a graph; `layOut(request)`
542
588
  * lays it out again (other options, `radii`, `intent`, `configSet`); a `start` without positions (`{settle}` or `{}`)
543
- * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
589
+ * continues from the last overview, and `{nodes}` (places by node id) from those places, also on a new graph (`open`).
590
+ * Without a resident session the graph and the last positions stay here and are sent
544
591
  * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
545
592
  */
546
593
  export function createOverviewSession(run, {resident: wanted = 'auto', columns = false} = {}) {
@@ -549,6 +596,9 @@ export function createOverviewSession(run, {resident: wanted = 'auto', columns =
549
596
  const opened = resident ? Promise.resolve(run.openSession()) : null;
550
597
  // `graph` is kept here only without a resident session; `started`: an `open` was asked for (it may still run).
551
598
  let graph = null, started = false, last = null, clusters = null, generation = 0, queue = Promise.resolve();
599
+ // Whether the last overview's clusters are those of places by id: an engine given the graph again would cluster it
600
+ // anew, so a continuation of it is sent by id too.
601
+ let byPlaces = false;
552
602
 
553
603
  const send = async request => {
554
604
  if (resident) {
@@ -562,15 +612,23 @@ export function createOverviewSession(run, {resident: wanted = 'auto', columns =
562
612
  const answer = await (columns ? kept.overview(plain(asked), {copy: true}) : kept.run(asked));
563
613
  if (answer.ok && answer.overview?.positionsOnly) {
564
614
  const {positionsOnly: _moved, ...moved} = answer.overview;
565
- return {...answer, overview: {...last, ...moved}};
615
+ // What became of places by id belongs to the answer that was asked with them.
616
+ const {continuation: _earlier, ...kept} = last;
617
+ return {...answer, overview: {...kept, ...moved}};
566
618
  }
567
619
  return answer;
568
620
  }
569
621
  const sent = {...request, graph: request.graph ?? graph};
570
622
  const start = request.start;
571
- if (start && start.x === undefined) {
623
+ if (start && start.x === undefined && start.nodes === undefined) {
572
624
  if (!last || request.graph) return {ok: false, error: 'No overview to continue from: lay out without start first.'};
573
625
  if (clustersOf(request.options) !== clusters) return {ok: false, error: 'The clusters changed since the last overview; lay out without start.'};
626
+ if (byPlaces) {
627
+ const answer = await run({...sent, start: {...start, nodes: placesOf(last)}});
628
+ if (!answer.ok) return answer;
629
+ const {continuation: _own, ...overview} = answer.overview;
630
+ return {...answer, overview};
631
+ }
574
632
  sent.start = {...start, x: last.x, y: last.y, r: last.r};
575
633
  }
576
634
  return run(sent);
@@ -596,6 +654,7 @@ export function createOverviewSession(run, {resident: wanted = 'auto', columns =
596
654
  if (answer.ok) {
597
655
  last = answer.overview;
598
656
  clusters = clustersOf(request.options);
657
+ byPlaces = !!request.start && (request.start.nodes !== undefined || (byPlaces && request.start.x === undefined));
599
658
  if (fresh && !resident) graph = request.graph;
600
659
  }
601
660
  return answer;
@@ -2,7 +2,11 @@ import type {DetailsAnswer, FindAnswer, Graph, Hidden, Intent, NeighbourhoodAnsw
2
2
  import type {DetailTarget, PayloadAnswer, PayloadChange, PeekAnswer, ReadAnswer, RefineRun, Session, SessionResult} from './session.js';
3
3
  import type {EngineRequest} from './wasm-client.js';
4
4
 
5
- /** Provisional: a view as a value (`bookmark`): the engine's intent, the highlight, the selection, the graph's digest. */
5
+ /**
6
+ * Provisional: a view as a value (`bookmark`): the engine's intent, the highlight, the selection, and the digest of the
7
+ * source graph as the view had it (with its changed shapes, directions, strategies, routing and ports). Whether it
8
+ * belongs to a graph is answered by `openBookmark` (or the engine's `readBookmark`), not by comparing digests.
9
+ */
6
10
  export interface ViewBookmark {
7
11
  version: 1;
8
12
  digest: string | null;
@@ -11,7 +15,22 @@ export interface ViewBookmark {
11
15
  selection?: DetailTarget;
12
16
  }
13
17
 
14
- /** A bookmark as URL-safe text, and back (throws on text that is not one). */
18
+ /**
19
+ * Provisional: what reading a bookmark against the current graph left out (`openBookmark` of a compact bookmark, or of a
20
+ * forced one of another graph).
21
+ */
22
+ export interface BookmarkReport {
23
+ /** Whether the bookmark was made on this graph (not counting shapes, directions, strategies, routing and ports). */
24
+ sameSource: boolean;
25
+ /** Whether the view as imported that a compact bookmark was compared with is the one it was read with. */
26
+ sameDefaults: boolean;
27
+ /** The ids the bookmark names that the graph does not have. */
28
+ missing: string[];
29
+ /** The decisions left out, by kind (`collapsed`, `pins`, `partial`, `hidden`, `highlight`, `selection`, …) and id. */
30
+ ignored: {field: string; id: string}[];
31
+ }
32
+
33
+ /** A bookmark as URL-safe text, and back (throws on text that is not one, such as a compact bookmark). */
15
34
  export function encodeBookmark(bookmark: ViewBookmark): string;
16
35
  export function decodeBookmark(text: string): ViewBookmark;
17
36
 
@@ -82,7 +101,11 @@ export interface ViewState {
82
101
  }
83
102
 
84
103
  /** A step's answer: the engine's, or `cancelled` when `cancel()` dropped it before it started. */
85
- export type ViewResult = SessionResult & {cancelled?: boolean};
104
+ export type ViewResult = SessionResult & {
105
+ cancelled?: boolean;
106
+ /** `back` / `forward` (#148): false when the kept snapshot came back with its geometry, true when the view was laid out again. */
107
+ relaidOut?: boolean;
108
+ };
86
109
 
87
110
  /**
88
111
  * Provisional (request 31): a headless view controller over a layout session. `subscribe` and `getState` fit React's
@@ -95,7 +118,7 @@ export interface ViewController {
95
118
  open(id: string): Promise<ViewResult>;
96
119
  close(id: string): Promise<ViewResult>;
97
120
  toggle(id: string): Promise<ViewResult>;
98
- /** The next `count` (default `page`) children of a `+N more` box; `container` or `rest:<container>`. */
121
+ /** The next `count` (default `page`) children of a `+N more` box, or the first page of a collapsed container; `container` or `rest:<container>`. */
99
122
  showRest(container: string, count?: number): Promise<ViewResult>;
100
123
  reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<ViewResult>;
101
124
  filter(hide?: Hidden): Promise<ViewResult>;
@@ -133,10 +156,20 @@ export interface ViewController {
133
156
  cancelRefinement(): void;
134
157
  /** Moves the selection the way `direction` says and sets `state.focus` (nothing opened, not a step for `back`). */
135
158
  navigate(direction: NavigationDirection): Promise<ViewResult | {ok: false; none: true; collapsed?: boolean}>;
136
- /** The view as a value to keep or share (`encodeBookmark` for a URL). */
159
+ /** The view as a value to keep or share (`encodeBookmark` for a URL; `compactBookmark` for a short one). */
137
160
  bookmark(): Promise<{ok: true; bookmark: ViewBookmark} | {ok: false; error?: string; cancelled?: boolean}>;
138
- /** Opens a bookmark (a step for `back`); another graph's is refused unless `force`. */
139
- openBookmark(bookmark: ViewBookmark, options?: {force?: boolean}): Promise<ViewResult>;
161
+ /**
162
+ * Provisional: the view as a short text for a URL (`b1.…`): what differs from the view as imported, with the highlight
163
+ * and the selection. `openBookmark` opens it.
164
+ */
165
+ compactBookmark(): Promise<{ok: true; text: string} | {ok: false; error?: string; cancelled?: boolean}>;
166
+ /**
167
+ * Opens a bookmark (a step for `back`), a value or a text. Another graph's long form is refused unless `force` (a graph
168
+ * that differs only in shapes, directions, strategies, routing and ports is the same one, and the bookmark's are
169
+ * restored); a compact one, and a forced one of another graph, restores what the graph has and reports the rest
170
+ * (`BookmarkReport`).
171
+ */
172
+ openBookmark(bookmark: ViewBookmark | string, options?: {force?: boolean}): Promise<ViewResult & Partial<BookmarkReport>>;
140
173
  back(): Promise<ViewResult>;
141
174
  forward(): Promise<ViewResult>;
142
175
  /** Any other change of the protocol, remembered for `back` under `label`. */
@@ -155,6 +188,6 @@ export interface ViewController {
155
188
  cancel(): void;
156
189
  }
157
190
 
158
- export function createViewController(session: Session, options?: {page?: number; historyLimit?: number; scenes?: boolean; detailLimit?: number; refine?: RefineRun; publicationInterval?: number}): ViewController;
191
+ export function createViewController(session: Session, options?: {page?: number; historyLimit?: number; scenes?: boolean; detailLimit?: number; refine?: RefineRun; publicationInterval?: number; keepGeometry?: boolean}): ViewController;
159
192
 
160
193
  export function sceneDiff(before: Scene | null, after: Scene | null): SceneDiff;
@@ -127,8 +127,12 @@ export function navigateScene(scene, from, direction) {
127
127
  }
128
128
  }
129
129
 
130
+ // The engine's compact bookmark (`compactBookmark`): `b1.` and base64url; the JSON form's text holds no `.`.
131
+ const compactText = /^b\d+\./;
132
+
130
133
  /**
131
134
  * A bookmark as text for a URL (base64url of its JSON, UTF-8), and back. `decodeBookmark` throws on text that is not one.
135
+ * This is the long form; `compactBookmark` of a view controller gives a short one, which `openBookmark` takes as text.
132
136
  */
133
137
  export function encodeBookmark(bookmark) {
134
138
  const bytes = new TextEncoder().encode(JSON.stringify(bookmark));
@@ -138,6 +142,7 @@ export function encodeBookmark(bookmark) {
138
142
  }
139
143
 
140
144
  export function decodeBookmark(text) {
145
+ if (compactText.test(text)) throw Error('A compact bookmark: open its text with openBookmark.');
141
146
  const base64 = text.replace(/-/g, '+').replace(/_/g, '/');
142
147
  const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));
143
148
  const bookmark = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, c => c.charCodeAt(0))));
@@ -154,9 +159,14 @@ export function decodeBookmark(text) {
154
159
  * `(request, {onPublication, signal}) => Promise<answer>` that runs a refinement request on a snapshot the controller
155
160
  * sends and calls `onPublication(publication)` for every intermediate result of a progressive one. It runs beside the
156
161
  * interactive steps, never in their queue; `publicationInterval` (ms) throttles how often intermediate results are shown.
162
+ *
163
+ * `keepGeometry` (default true, provisional, #148): every step keeps the snapshots before and after it (`session.keep`),
164
+ * so that `back` and `forward` restore the geometry as it was (`session.recall`) instead of laying the view out again;
165
+ * only when a snapshot is no longer kept or the graph changed since is the view laid out again from the decisions
166
+ * (the step's result then says `relaidOut: true`). With `false` only the decisions are kept, as before.
157
167
  */
158
168
  export function createViewController(session, {page = 12, historyLimit = 50, scenes = true, detailLimit, refine: refineRun,
159
- publicationInterval = 120} = {}) {
169
+ publicationInterval = 120, keepGeometry = true} = {}) {
160
170
  let state = Object.freeze({
161
171
  snapshot: null, scene: null, diff: null, busy: false, error: null,
162
172
  highlight: null, selection: null, details: null, hover: null, search: null, focus: null, peek: null, refining: null, refined: null,
@@ -205,12 +215,51 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
205
215
  return answer.ok ? answer.digest ?? null : null;
206
216
  };
207
217
 
218
+ // The view's decisions as it was imported, which a compact bookmark is compared with: undefined until they are read,
219
+ // null when unknown. They are read with the first change that reads the decisions anyway, or for a bookmark, so that no
220
+ // step costs an engine call for them; `pristine` says whether the view then came from an import.
221
+ let defaults;
222
+ let pristine = null;
223
+ const isPristine = snapshot => !!snapshot && (snapshot.layoutVersion ?? 0) === 0;
224
+ // Another view: its defaults are read from it, if it is as an import left it (a snapshot that went through changes holds
225
+ // decisions, which must stay in the bookmark).
226
+ const newView = () => {
227
+ defaults = undefined;
228
+ pristine = isPristine(session.snapshot);
229
+ };
230
+ // `now` is the current intent, if the caller has read it.
231
+ const readDefaults = async now => {
232
+ if (defaults !== undefined) return;
233
+ defaults = (pristine ?? isPristine(session.snapshot)) ? now ?? await intent() : null;
234
+ };
235
+ // Call before a change that may alter decisions, with the intent before it if the step has read it. Without it the
236
+ // defaults stay unknown: a compact bookmark then keeps every decision.
237
+ const beforeChange = async before => {
238
+ if (before) await readDefaults(before);
239
+ else if (defaults === undefined) defaults = null;
240
+ };
241
+ const withDefaults = request => (defaults ? {...request, defaults} : request);
242
+
243
+ // The current snapshot kept by the session for `back` (#148): its mark, or null without it.
244
+ const mark = async () => {
245
+ if (!keepGeometry || typeof session.keep !== 'function') return null;
246
+ const answer = await session.keep({limit: Math.min(historyLimit + 1, 1000)});
247
+ return answer?.ok ? answer.mark : null;
248
+ };
208
249
  const intent = async () => {
209
250
  const answer = await session.apply({op: 'intent'});
210
251
  if (!answer.ok) throw Error(answer.error ?? 'No intent');
211
252
  return answer.intent;
212
253
  };
213
254
 
255
+ // What a bookmark keeps beside the decisions: the highlight's question (not its answer) and the selection.
256
+ const marks = () => {
257
+ const h = state.highlight;
258
+ const highlight = h ? {kind: h.kind, ...(h.kind === 'trace' ? {from: h.from, to: h.to} : {nodeId: h.nodeId}),
259
+ ...(h.init ? {init: h.init} : {})} : null;
260
+ return {...(highlight ? {highlight} : {}), ...(state.selection ? {selection: state.selection} : {})};
261
+ };
262
+
214
263
  // Asks the highlight's query again on the current view (its visible nodes and routes depend on what is open).
215
264
  const refreshHighlight = async highlight => {
216
265
  if (!highlight) return null;
@@ -289,10 +338,13 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
289
338
 
290
339
  // A change the user makes: its decisions before and after are remembered (unless `remember` is false), so that `back`
291
340
  // undoes it. A refinement under way is stopped: its result would be for the view before the change.
292
- const change = (label, run, extra = () => ({}), remember = true, merge = false) => enqueue(async current => {
341
+ // `settles`: the change moves nodes and alters no decision.
342
+ const change = (label, run, extra = () => ({}), remember = true, merge = false, settles = false) => enqueue(async current => {
293
343
  if (!session.snapshot) return {ok: false, error: 'Nothing imported yet.'};
294
344
  stopRefinement('cancelled');
295
345
  const before = remember ? await intent() : null;
346
+ if (!settles) await beforeChange(before);
347
+ const beforeMark = remember ? await mark() : null;
296
348
  const result = await run();
297
349
  if (!current()) return {ok: false, cancelled: true};
298
350
  if (!result.ok) {
@@ -300,6 +352,7 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
300
352
  return result;
301
353
  }
302
354
  const after = remember ? await intent() : null;
355
+ const afterMark = remember ? await mark() : null;
303
356
  if (!current()) return {ok: false, cancelled: true};
304
357
  // A look into a container belongs to the view before the change.
305
358
  if (state.peek) state = Object.freeze({...state, peek: null});
@@ -307,10 +360,11 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
307
360
  // A follow-up of the last change (such as a container keeping the size a drop gave it): one entry for both.
308
361
  const last = back.at(-1);
309
362
  last.after = after;
363
+ last.afterMark = afterMark;
310
364
  if (same(last.before, last.after)) back.pop();
311
365
  forward = [];
312
366
  } else if (remember && !same(before, after)) {
313
- back.push({label, before, after});
367
+ back.push({label, before, after, beforeMark, afterMark});
314
368
  if (back.length > historyLimit) back.shift();
315
369
  forward = [];
316
370
  }
@@ -318,13 +372,26 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
318
372
  return result;
319
373
  });
320
374
 
321
- // Back and forward: the engine restores the remembered decisions; a refused restore keeps the entry.
375
+ // Back and forward: the kept snapshot of that side comes back with its geometry (#148); when it is no longer kept or the
376
+ // graph changed since, the engine restores the remembered decisions and lays the view out again. A refused step keeps
377
+ // the entry.
322
378
  const step = direction => enqueue(async current => {
323
379
  stopRefinement('cancelled');
324
380
  const from = direction < 0 ? back : forward;
325
381
  const entry = from.at(-1);
326
382
  if (!entry) return {ok: false, error: direction < 0 ? 'Nothing to undo.' : 'Nothing to redo.'};
327
- const result = await session.apply({op: 'restore', intent: direction < 0 ? entry.before : entry.after});
383
+ const kept = direction < 0 ? entry.beforeMark : entry.afterMark;
384
+ let result = kept == null ? null : await session.recall(kept);
385
+ if (result && !result.ok && !result.evicted && !result.changed) {
386
+ publish({error: result.error ?? 'The engine refused the step.'});
387
+ return result;
388
+ }
389
+ if (result?.ok) {
390
+ result = {...result, relaidOut: false};
391
+ } else {
392
+ result = await session.apply({op: 'restore', intent: direction < 0 ? entry.before : entry.after});
393
+ if (result.ok) result = {...result, relaidOut: true};
394
+ }
328
395
  if (!current()) return {ok: false, cancelled: true};
329
396
  if (!result.ok) {
330
397
  publish({error: result.error ?? 'The engine refused the restore.'});
@@ -360,6 +427,7 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
360
427
  publish({error: result.error ?? 'The import failed.'});
361
428
  return result;
362
429
  }
430
+ newView();
363
431
  state = Object.freeze({...state, scene: null, highlight: null, selection: null, details: null, hover: null,
364
432
  search: null, focus: null, peek: null, hide: {}, steps: 0});
365
433
  await settle({}, current);
@@ -376,7 +444,8 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
376
444
 
377
445
  /**
378
446
  * Shows the next `count` (default `page`) children of `container`'s `+N more` box; on the last page the container is
379
- * whole again. `container` may also be the rest's id (`rest:<container>`).
447
+ * whole again. A collapsed container opens in part with its first page. `container` may also be the rest's id
448
+ * (`rest:<container>`).
380
449
  */
381
450
  showRest(container, count = page) {
382
451
  const id = container.startsWith('rest:') ? container.slice(5) : container;
@@ -619,51 +688,96 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
619
688
 
620
689
  /**
621
690
  * The view as a value to keep or share: the decisions (the engine's intent: open groups, pages, filter, options), the
622
- * highlight and the selection, and the digest of the graph it belongs to. `encodeBookmark` makes it text for a URL.
691
+ * highlight and the selection, and the digest of the graph it belongs to. `encodeBookmark` makes it text for a URL;
692
+ * `compactBookmark` gives a much shorter one.
623
693
  */
624
694
  bookmark() {
625
695
  return enqueue(async () => {
626
696
  if (!session.snapshot) return {ok: false, error: 'Nothing imported yet.'};
627
- const h = state.highlight;
628
- const highlight = h ? {kind: h.kind, ...(h.kind === 'trace' ? {from: h.from, to: h.to} : {nodeId: h.nodeId}),
629
- ...(h.init ? {init: h.init} : {})} : null;
630
- const bookmark = {version: 1, digest: await digest(), intent: await intent(),
631
- ...(highlight ? {highlight} : {}), ...(state.selection ? {selection: state.selection} : {})};
632
- return {ok: true, bookmark};
697
+ return {ok: true, bookmark: {version: 1, digest: await digest(), intent: await intent(), ...marks()}};
633
698
  });
634
699
  },
635
700
 
636
701
  /**
637
- * Opens a bookmark on the current graph (a step for `back`): its decisions, highlight and selection. A bookmark of
638
- * another graph (another digest) is refused unless `force`.
702
+ * Provisional: the view as a short text for a URL, `{ok, text}` (`b1.…`, base64url), made by the engine (operation
703
+ * `compactBookmark`): only what differs from the view as it was imported, every id once, with the highlight and the
704
+ * selection. `openBookmark(text)` opens it.
705
+ */
706
+ compactBookmark() {
707
+ return enqueue(async () => {
708
+ if (!session.snapshot) return {ok: false, error: 'Nothing imported yet.'};
709
+ await readDefaults();
710
+ const answer = await session.apply(withDefaults({op: 'compactBookmark', ...marks()}));
711
+ if (!answer.ok) publish({error: answer.error ?? 'No bookmark.'});
712
+ return answer;
713
+ });
714
+ },
715
+
716
+ /**
717
+ * Opens a bookmark on the current graph (a step for `back`): its decisions, highlight and selection. `bookmark` is the
718
+ * value of `bookmark()` or a text (of `compactBookmark` or `encodeBookmark`). A bookmark in the long form of another
719
+ * graph is refused unless `force`: one with another digest that the engine does not find to be this graph with the
720
+ * bookmark's own shapes, directions, strategies, routing and ports (`readBookmark`, `sameSource`). A compact one, and
721
+ * a forced one of another graph, is read against the graph (`readBookmark`): what names an id the graph no longer has
722
+ * is left out, and the result says so (`missing`, `ignored`, `sameSource`, `sameDefaults`).
639
723
  */
640
724
  openBookmark(bookmark, {force = false} = {}) {
641
725
  return enqueue(async current => {
642
726
  if (!session.snapshot) return {ok: false, error: 'Nothing imported yet.'};
643
- if (bookmark?.version !== 1 || typeof bookmark.intent !== 'object') return {ok: false, error: 'Not a view bookmark.'};
644
- const now = bookmark.digest && !force ? await digest() : null;
645
- if (now && bookmark.digest !== now) {
727
+ const compact = typeof bookmark === 'string' && compactText.test(bookmark);
728
+ let opened = bookmark;
729
+ if (typeof bookmark === 'string' && !compact) {
730
+ try { opened = decodeBookmark(bookmark); } catch { opened = null; }
731
+ }
732
+ if (!compact && (opened?.version !== 1 || typeof opened.intent !== 'object')) {
733
+ return {ok: false, error: 'Not a view bookmark.'};
734
+ }
735
+ const now = !compact && opened.digest ? await digest() : null;
736
+ let other = false;
737
+ let read = null;
738
+ if (now && opened.digest !== now) {
739
+ // The digest is of the graph with the shapes, directions and so on of the bookmarked view: the engine says
740
+ // whether this is that graph.
741
+ read = await session.apply({op: 'readBookmark', bookmark: opened});
742
+ if (!current()) return {ok: false, cancelled: true};
743
+ other = !(read.ok && read.sameSource);
744
+ }
745
+ if (other && !force) {
646
746
  const error = 'The bookmark belongs to another graph.';
647
747
  publish({error});
648
748
  return {ok: false, error};
649
749
  }
650
750
  stopRefinement('cancelled');
651
751
  const before = await intent();
652
- const result = await session.apply({op: 'restore', intent: bookmark.intent});
752
+ await readDefaults(before);
753
+ let report = {};
754
+ if (compact || other) {
755
+ if (compact) read = await session.apply(withDefaults({op: 'readBookmark', text: bookmark}));
756
+ if (!current()) return {ok: false, cancelled: true};
757
+ if (!read.ok) {
758
+ publish({error: read.error ?? 'The engine refused the bookmark.'});
759
+ return read;
760
+ }
761
+ const {sameSource, sameDefaults, missing, ignored} = read;
762
+ report = {sameSource, sameDefaults, missing, ignored};
763
+ opened = read.bookmark;
764
+ }
765
+ const beforeMark = await mark();
766
+ const result = await session.apply({op: 'restore', intent: opened.intent});
653
767
  if (!current()) return {ok: false, cancelled: true};
654
768
  if (!result.ok) {
655
769
  publish({error: result.error ?? 'The engine refused the bookmark.'});
656
- return result;
770
+ return {...result, ...report};
657
771
  }
658
772
  const after = await intent();
659
773
  if (!same(before, after)) {
660
- back.push({label: 'Open bookmark', before, after});
774
+ back.push({label: 'Open bookmark', before, after, beforeMark, afterMark: await mark()});
661
775
  if (back.length > historyLimit) back.shift();
662
776
  forward = [];
663
777
  }
664
- state = Object.freeze({...state, highlight: bookmark.highlight ?? null, selection: bookmark.selection ?? null});
665
- await settle({hide: bookmark.intent.hidden ?? {}}, current);
666
- return result;
778
+ state = Object.freeze({...state, highlight: opened.highlight ?? null, selection: opened.selection ?? null});
779
+ await settle({hide: opened.intent.hidden ?? {}}, current);
780
+ return {...result, ...report};
667
781
  });
668
782
  },
669
783
 
@@ -688,7 +802,7 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
688
802
  * `remember: false`, for steps that change no decision, such as settling).
689
803
  */
690
804
  apply(request, label = request.op, {remember = true, merge = false} = {}) {
691
- return change(label, () => session.apply(request), () => ({}), remember, merge);
805
+ return change(label, () => session.apply(request), () => ({}), remember, merge, request.op === 'settle');
692
806
  },
693
807
 
694
808
  /**
@@ -700,6 +814,8 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
700
814
  // With `remember` (a label) the change from the session's snapshot to this one is remembered for `back`.
701
815
  stopRefinement('cancelled');
702
816
  const before = remember && session.snapshot ? await intent() : null;
817
+ if (!forget && session.snapshot) await beforeChange(before);
818
+ const beforeMark = before ? await mark() : null;
703
819
  const result = await session.load(snapshot, {reset: forget});
704
820
  if (!current()) return {ok: false, cancelled: true};
705
821
  if (!result.ok) {
@@ -707,6 +823,7 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
707
823
  return result;
708
824
  }
709
825
  if (forget) {
826
+ newView();
710
827
  back = [];
711
828
  forward = [];
712
829
  state = Object.freeze({...state, highlight: null, selection: null, details: null, hover: null, search: null,
@@ -714,7 +831,7 @@ export function createViewController(session, {page = 12, historyLimit = 50, sce
714
831
  } else if (before) {
715
832
  const after = await intent();
716
833
  if (!same(before, after)) {
717
- back.push({label: remember, before, after});
834
+ back.push({label: remember, before, after, beforeMark, afterMark: await mark()});
718
835
  if (back.length > historyLimit) back.shift();
719
836
  forward = [];
720
837
  }
package/wasm-client.js CHANGED
@@ -56,7 +56,8 @@ export async function createEngine(bytes,{onPublish}={}) {
56
56
  return {...result,...viewsOf(listed,index=>api.lw_session_column(id,index),false)};
57
57
  };
58
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
59
+ // `y`, `r`, `kind`, `edges`, `links`, and with `edgeData` `edgeKind` and `edgeWeight`; a continuation with
60
+ // `positionsOnly` only `x`, `y` and `r`), in an answer shaped
60
61
  // like the JSON one. `copy` (default false) copies them out of the module's memory, for a host that keeps them past
61
62
  // its next request; views are valid only until then.
62
63
  const overview=(request,{copy=false}={})=>{