@kgdiff/viewer 0.4.0 → 0.5.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.
Files changed (84) hide show
  1. package/dist/context.d.ts +42 -0
  2. package/dist/context.d.ts.map +1 -0
  3. package/dist/context.js +87 -0
  4. package/dist/context.js.map +1 -0
  5. package/dist/controller.d.ts +26 -185
  6. package/dist/controller.d.ts.map +1 -1
  7. package/dist/controller.js +45 -1155
  8. package/dist/controller.js.map +1 -1
  9. package/dist/element.d.ts +6 -3
  10. package/dist/element.d.ts.map +1 -1
  11. package/dist/element.js +49 -229
  12. package/dist/element.js.map +1 -1
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/pipeline.d.ts.map +1 -1
  17. package/dist/pipeline.js +3 -2
  18. package/dist/pipeline.js.map +1 -1
  19. package/dist/root.d.ts +54 -0
  20. package/dist/root.d.ts.map +1 -0
  21. package/dist/root.js +265 -0
  22. package/dist/root.js.map +1 -0
  23. package/dist/schedule.d.ts +22 -0
  24. package/dist/schedule.d.ts.map +1 -0
  25. package/dist/schedule.js +41 -0
  26. package/dist/schedule.js.map +1 -0
  27. package/dist/session.d.ts +253 -0
  28. package/dist/session.d.ts.map +1 -0
  29. package/dist/session.js +1239 -0
  30. package/dist/session.js.map +1 -0
  31. package/dist/standalone/kgdiff-viewer-compute.js +1 -1
  32. package/dist/standalone/kgdiff-viewer.js +4 -4
  33. package/dist/styles.d.ts +13 -6
  34. package/dist/styles.d.ts.map +1 -1
  35. package/dist/styles.js +217 -248
  36. package/dist/styles.js.map +1 -1
  37. package/dist/theme.d.ts +25 -0
  38. package/dist/theme.d.ts.map +1 -0
  39. package/dist/theme.js +149 -0
  40. package/dist/theme.js.map +1 -0
  41. package/dist/ui/change-list.d.ts +18 -0
  42. package/dist/ui/change-list.d.ts.map +1 -0
  43. package/dist/ui/change-list.js +331 -0
  44. package/dist/ui/change-list.js.map +1 -0
  45. package/dist/ui/context.d.ts +19 -5
  46. package/dist/ui/context.d.ts.map +1 -1
  47. package/dist/ui/context.js.map +1 -1
  48. package/dist/ui/filters.d.ts +9 -0
  49. package/dist/ui/filters.d.ts.map +1 -0
  50. package/dist/ui/filters.js +68 -0
  51. package/dist/ui/filters.js.map +1 -0
  52. package/dist/ui/header.js +2 -2
  53. package/dist/ui/header.js.map +1 -1
  54. package/dist/ui/search.d.ts +13 -0
  55. package/dist/ui/search.d.ts.map +1 -0
  56. package/dist/ui/search.js +191 -0
  57. package/dist/ui/search.js.map +1 -0
  58. package/dist/ui/sidebar.d.ts +8 -16
  59. package/dist/ui/sidebar.d.ts.map +1 -1
  60. package/dist/ui/sidebar.js +15 -539
  61. package/dist/ui/sidebar.js.map +1 -1
  62. package/dist/ui/stage.js +1 -1
  63. package/dist/ui/stage.js.map +1 -1
  64. package/dist/ui/swatch.js +1 -1
  65. package/dist/ui/swatch.js.map +1 -1
  66. package/package.json +6 -6
  67. package/src/context.ts +106 -0
  68. package/src/controller.ts +70 -1257
  69. package/src/element.ts +52 -243
  70. package/src/index.ts +3 -1
  71. package/src/pipeline.ts +4 -1
  72. package/src/root.ts +308 -0
  73. package/src/schedule.ts +43 -0
  74. package/src/session.ts +1386 -0
  75. package/src/styles.ts +225 -253
  76. package/src/theme.ts +167 -0
  77. package/src/ui/change-list.ts +401 -0
  78. package/src/ui/context.ts +21 -5
  79. package/src/ui/filters.ts +79 -0
  80. package/src/ui/header.ts +2 -2
  81. package/src/ui/search.ts +220 -0
  82. package/src/ui/sidebar.ts +28 -668
  83. package/src/ui/stage.ts +1 -1
  84. package/src/ui/swatch.ts +1 -1
@@ -1,22 +1,12 @@
1
- import { KgdiffError } from '@kgdiff/core';
2
1
  import { labelFootprint, } from '@kgdiff/renderer';
3
- import { buildScene, computeFocus, createViewState, createVisualResolver, frameBounds, getTheme, } from '@kgdiff/scene';
4
- import { computeNow, computeStatus, loadCompute } from './compute-loader.js';
2
+ import { createViewState, frameBounds, } from '@kgdiff/scene';
5
3
  import { chromeInsets, FRAME_PADDING, freeView, NO_INSETS, zoomFit, } from './framing.js';
6
- import { translate } from './i18n.js';
7
- import { buildList, EMPTY_LIST, stepHunk } from './list-model.js';
8
- import { readPayload, runLoad } from './pipeline.js';
9
- import { LEGACY_CHANGES_MODE, toLocale, toMode, toPalette, toScope, toTheme } from './prefs.js';
10
4
  import { renderBackend } from './renderer-port.js';
11
- import { ReplayClock } from './replay.js';
12
- import { ReviewStore, reviewKey } from './review-store.js';
13
- import { SearchIndex } from './search.js';
5
+ import { DiffSession, padRect, } from './session.js';
14
6
  /** Camera follow is suppressed this long after the user moved the camera (ms). */
15
7
  export const USER_CAMERA_GRACE = 2000;
16
8
  /** The camera follows when less than this share of the target bounds is in view. */
17
9
  export const FOLLOW_COVERAGE = 0.7;
18
- /** Spotlight emphasis restarts here when switching directly between two hunks. */
19
- const SWITCH_EMPHASIS = 0.35;
20
10
  /** Flights to a change never zoom in further, so its neighbourhood stays readable. */
21
11
  export const FLY_MAX_ZOOM = 1.8;
22
12
  /** Fitting everything never zooms in further (the renderer's default). */
@@ -25,8 +15,6 @@ export const FIT_MAX_ZOOM = 2.5;
25
15
  const MINIMAP_INTERVAL = 200;
26
16
  /** Everything counts as in view (the minimap hides) from this share of the content bounds on. */
27
17
  export const OVERVIEW_COVERAGE = 0.98;
28
- class Superseded extends Error {
29
- }
30
18
  /** Share of `bounds` inside `view`, in [0, 1]. */
31
19
  export function coverage(bounds, view) {
32
20
  const w = Math.min(bounds.x + bounds.width, view.x + view.width) - Math.max(bounds.x, view.x);
@@ -41,41 +29,7 @@ export function coverage(bounds, view) {
41
29
  }
42
30
  return w > 0 && h > 0 ? (w * h) / area : 0;
43
31
  }
44
- const ease = (u) => 1 - (1 - u) ** 3;
45
- export class ViewerController {
46
- status = 'idle';
47
- /** Steps of the current load, in order; `step` is the running one. */
48
- steps = [];
49
- step = null;
50
- error = null;
51
- data = null;
52
- layout = null;
53
- scene = null;
54
- resolver = null;
55
- list = EMPTY_LIST;
56
- mode = 'overlay';
57
- scope = 'all';
58
- themePreference = 'auto';
59
- palette = 'default';
60
- locale = 'en';
61
- systemDark = true;
62
- reducedMotion = false;
63
- /** Preferences set explicitly by the embedder (a report's `view` does not override them). */
64
- explicit = new Set();
65
- selectedHunk = -1;
66
- selectedNode = -1;
67
- /** An edge emphasized from the detail panel (drawn as hovered). */
68
- pinnedEdge = -1;
69
- hoverNode = -1;
70
- hoverEdge = -1;
71
- hoverGroup = -1;
72
- families = new Set();
73
- hops = 1;
74
- expanded = new Set();
75
- focus = null;
76
- clock = null;
77
- split = 0.5;
78
- emphasis = 1;
32
+ export class ViewerController extends DiffSession {
79
33
  /**
80
34
  * Keep the view fitted (embeds without controls): fit again when the canvas is resized unless
81
35
  * the user moved the camera since, and at the start of every loop.
@@ -83,26 +37,16 @@ export class ViewerController {
83
37
  autoFit = false;
84
38
  /** Canvas clicks select (and double clicks fly); off for embeds without controls. */
85
39
  selectOnClick = true;
86
- #labelsInside = false;
87
40
  /** The whole content is in view (the minimap has nothing to add). */
88
41
  overview = true;
89
- #review = null;
90
- #searchIndex = null;
42
+ #labelsInside = false;
91
43
  #renderer = null;
92
44
  #minimap = null;
93
45
  #unbind = [];
94
46
  #frames = { main: null, before: null, after: null };
95
- #fadingHunk = -1;
96
- #emphasisAnim = null;
97
- #rafId = 0;
98
- #lastTick = 0;
99
- #frameDirty = false;
100
47
  #minimapDirty = true;
101
48
  #lastMinimap = Number.NEGATIVE_INFINITY;
102
49
  #lastUserCamera = Number.NEGATIVE_INFINITY;
103
- #followed = '';
104
- #loadToken = 0;
105
- #pendingHunk = null;
106
50
  #boundsCache = null;
107
51
  #chrome = null;
108
52
  /** Camera kept across detach / attach (element moved in the DOM). */
@@ -112,252 +56,11 @@ export class ViewerController {
112
56
  /** The user panned or zoomed since the last fit. */
113
57
  #userMoved = false;
114
58
  #fitPadding = FRAME_PADDING;
115
- /** A finished replay starts again this long (ms) after its end; null: it plays once. */
116
- #loopDelay = null;
117
- /** When a finished looping replay starts again (`deps.now()` time), else NaN. */
118
- #restartAt = Number.NaN;
119
- /** Playback is held (pointer over the graph); `#resume`: it was playing and continues after. */
120
- #held = false;
121
- #resume = false;
122
- #listeners = new Set();
123
- #pendingTopics = new Set();
124
- #flushQueued = false;
125
- #destroyed = false;
126
- #host;
127
- #deps;
59
+ #now;
128
60
  constructor(host, deps) {
129
- this.#host = host;
130
- this.#deps = deps;
131
- }
132
- // ─── Subscriptions ────────────────────────────────────────────────────────
133
- subscribe(listener) {
134
- this.#listeners.add(listener);
135
- return () => this.#listeners.delete(listener);
136
- }
137
- #notify(...topics) {
138
- for (const t of topics)
139
- this.#pendingTopics.add(t);
140
- if (this.#flushQueued)
141
- return;
142
- this.#flushQueued = true;
143
- queueMicrotask(() => this.flush());
144
- }
145
- /** Deliver pending notifications now (also used by tests). */
146
- flush() {
147
- this.#flushQueued = false;
148
- if (this.#pendingTopics.size === 0)
149
- return;
150
- const topics = this.#pendingTopics;
151
- this.#pendingTopics = new Set();
152
- for (const fn of this.#listeners)
153
- fn(topics);
154
- }
155
- // ─── Derived state ────────────────────────────────────────────────────────
156
- get themeName() {
157
- if (this.themePreference === 'auto')
158
- return this.systemDark ? 'dark' : 'light';
159
- return this.themePreference;
160
- }
161
- get theme() {
162
- try {
163
- return getTheme(this.themeName, this.palette);
164
- }
165
- catch {
166
- return getTheme('dark', 'default');
167
- }
168
- }
169
- get diff() {
170
- return this.data?.diff ?? null;
171
- }
172
- get hunkCount() {
173
- return this.scene?.hunks.length ?? 0;
174
- }
175
- isReviewed(hunkId) {
176
- return this.#review?.has(hunkId) ?? false;
177
- }
178
- reviewState() {
179
- return this.#review?.state() ?? { reviewed: [], total: 0 };
180
- }
181
- search(query, limit) {
182
- const diff = this.diff;
183
- if (!diff)
184
- return [];
185
- this.#searchIndex ??= new SearchIndex(diff);
186
- return this.#searchIndex.search(query, limit);
187
- }
188
- // ─── Loading ──────────────────────────────────────────────────────────────
189
- async load(options) {
190
- const text = (s) => typeof s === 'object' && s !== null && typeof s.text === 'string';
191
- const parse = text(options?.before) || text(options?.after);
192
- await this.#run(parse ? ['parse', 'match', 'layout', 'scene'] : ['match', 'layout', 'scene'], (onStep) => runLoad(options, onStep));
193
- }
194
- async loadPayload(payload) {
195
- await this.#run(['match', 'layout', 'scene'], (onStep) => readPayload(payload, onStep));
196
- }
197
- async #run(planned, work) {
198
- const token = ++this.#loadToken;
199
- this.pause();
200
- this.status = 'loading';
201
- this.error = null;
202
- this.steps = planned;
203
- this.step = null;
204
- this.#notify('status');
205
- const onStep = async (step) => {
206
- if (token !== this.#loadToken || this.#destroyed)
207
- throw new Superseded();
208
- this.step = step;
209
- this.#notify('status');
210
- this.flush();
211
- await this.#deps.yieldToPaint();
212
- if (token !== this.#loadToken || this.#destroyed)
213
- throw new Superseded();
214
- };
215
- try {
216
- const loaded = await work(onStep);
217
- await onStep('scene');
218
- this.#install(loaded);
219
- }
220
- catch (error) {
221
- if (error instanceof Superseded) {
222
- throw new DOMException('Superseded by a newer load.', 'AbortError');
223
- }
224
- const err = error instanceof Error ? error : new KgdiffError('invalid-input', String(error));
225
- if (token === this.#loadToken)
226
- this.fail(err);
227
- throw err;
228
- }
229
- }
230
- /** Show an error state (bad payload, failed load). */
231
- fail(error) {
232
- this.#loadToken++;
233
- this.clock?.pause();
234
- this.#restartAt = Number.NaN;
235
- this.#resume = false;
236
- this.status = 'error';
237
- this.error = error;
238
- this.step = null;
239
- // Nothing stale stays on screen next to the error.
240
- this.data = null;
241
- this.layout = null;
242
- this.scene = null;
243
- this.resolver = null;
244
- this.list = EMPTY_LIST;
245
- this.clock = null;
246
- this.focus = null;
247
- this.#review = null;
248
- this.selectedHunk = this.selectedNode = this.pinnedEdge = -1;
249
- this.#notify('status', 'data', 'selection', 'filters', 'review', 'replay', 'focus');
250
- this.#host.error(error);
251
- }
252
- #install(loaded) {
253
- const { diff, layout, view } = loaded;
254
- this.data = loaded;
255
- this.layout = layout;
256
- this.#searchIndex = null;
257
- this.families.clear();
258
- this.expanded.clear();
259
- this.hops = Math.max(0, Math.min(2, loaded.layoutOptions?.contextHops ?? 1));
260
- this.selectedHunk = -1;
261
- this.selectedNode = -1;
262
- this.pinnedEdge = -1;
263
- this.#fadingHunk = -1;
264
- this.emphasis = 1;
265
- this.#emphasisAnim = null;
266
- this.hoverNode = this.hoverEdge = this.hoverGroup = -1;
267
- this.split = 0.5;
268
- this.clock = null;
269
- this.#followed = '';
270
- if (view) {
271
- if (view.theme && !this.explicit.has('theme'))
272
- this.themePreference = view.theme;
273
- if (view.palette && !this.explicit.has('palette'))
274
- this.palette = view.palette;
275
- if (view.locale && !this.explicit.has('locale'))
276
- this.locale = view.locale;
277
- }
278
- const previousMode = this.mode;
279
- const previousScope = this.scope;
280
- if (!this.explicit.has('mode'))
281
- this.mode = view?.mode ?? 'overlay';
282
- if (layout.scope === 'changes') {
283
- // Only the changes are laid out: there is no whole graph to show.
284
- this.scope = 'changes';
285
- }
286
- else if (!this.explicit.has('scope')) {
287
- const threshold = loaded.layoutOptions?.largeGraphThreshold ?? 3000;
288
- this.scope = view?.scope ?? (diff.nodes.length > threshold ? 'changes' : 'all');
289
- }
290
- this.#review = new ReviewStore(this.#deps.storage, reviewKey(diff.delta.base.hash, diff.delta.target.hash), diff.hunks.map((h) => h.id));
291
- this.#rebuildScene();
292
- this.status = 'ready';
293
- this.step = null;
294
- if (layout.scope === 'changes' && computeStatus() === 'unknown') {
295
- // Learn early whether out-of-layout groups can be expanded (standalone reports).
296
- loadCompute().then(() => this.#notify('focus'), () => this.#notify('focus'));
297
- }
298
- this.#notify('status', 'data', 'mode', 'selection', 'filters', 'review', 'replay', 'theme', 'locale', 'focus', 'swipe', 'overview');
299
- // A new diff starts fitted, after the UI has shown its chrome (the notification above is
300
- // delivered first) and once the canvas has a size (see `layoutChanged`).
301
- this.#needsFit = true;
302
- this.#savedCamera = null;
303
- queueMicrotask(() => this.layoutChanged());
304
- this.#host.ready(diff.stats);
305
- if (this.mode !== previousMode || this.scope !== previousScope) {
306
- this.#host.mode(this.mode, this.scope);
307
- }
308
- const pending = this.#pendingHunk;
309
- this.#pendingHunk = null;
310
- if (pending !== null)
311
- this.selectHunkById(pending.id, { fly: pending.fly });
312
- else
313
- this.#autoplay();
314
- }
315
- /** (Re)build scene, resolver, list, clock and focus; selection is carried over by id. */
316
- #rebuildScene() {
317
- const data = this.data;
318
- const layout = this.layout;
319
- if (!data || !layout)
320
- return;
321
- const old = this.scene;
322
- const keepHunk = old && this.selectedHunk >= 0 ? old.hunks[this.selectedHunk]?.id : undefined;
323
- const keepNode = old && this.selectedNode >= 0 ? old.nodes[this.selectedNode]?.id : undefined;
324
- const keepEdge = old && this.pinnedEdge >= 0 ? old.edges[this.pinnedEdge]?.id : undefined;
325
- const scene = buildScene(data.diff, layout, { theme: this.theme, locale: this.locale });
326
- this.scene = scene;
327
- this.resolver = createVisualResolver(scene);
328
- this.#frames.main = this.#frames.before = this.#frames.after = null;
329
- const prevClock = this.clock;
330
- this.clock = new ReplayClock(scene.timeline);
331
- if (prevClock) {
332
- this.clock.setSpeed(prevClock.speed);
333
- this.clock.seek(prevClock.t);
334
- if (prevClock.playing)
335
- this.clock.play();
336
- }
337
- this.selectedHunk = keepHunk !== undefined ? (scene.hunkIndex.get(keepHunk) ?? -1) : -1;
338
- this.selectedNode = keepNode !== undefined ? (scene.nodeIndex.get(keepNode) ?? -1) : -1;
339
- this.pinnedEdge = keepEdge !== undefined ? (scene.edgeIndex.get(keepEdge) ?? -1) : -1;
340
- this.#fadingHunk = -1;
341
- this.hoverNode = this.hoverEdge = this.hoverGroup = -1;
342
- this.list = buildList(scene, this.families);
343
- this.#updateFocus();
344
- this.#renderer?.setTheme(scene.theme);
345
- this.#minimapDirty = true;
346
- this.invalidate();
347
- }
348
- #updateFocus() {
349
- const scene = this.scene;
350
- if (!scene || this.scope !== 'changes') {
351
- this.focus = null;
352
- return;
353
- }
354
- const expanded = new Set();
355
- for (const id of this.expanded) {
356
- const i = scene.nodeIndex.get(id);
357
- if (i !== undefined)
358
- expanded.add(i);
359
- }
360
- this.focus = computeFocus(scene, { hops: this.hops, expanded });
61
+ super(host, deps);
62
+ this.#now = deps.now;
63
+ this.addView(this);
361
64
  }
362
65
  // ─── Renderer ─────────────────────────────────────────────────────────────
363
66
  attach(stage, minimapHost) {
@@ -386,9 +89,7 @@ export class ViewerController {
386
89
  // A pending initial fit still runs after re-attach (`layoutChanged`), overriding this.
387
90
  if (this.#renderer && this.status === 'ready')
388
91
  this.#savedCamera = this.#renderer.camera.get();
389
- if (this.#rafId)
390
- this.#deps.cancelFrame(this.#rafId);
391
- this.#rafId = 0;
92
+ this.sleep();
392
93
  for (const fn of this.#unbind.splice(0))
393
94
  fn();
394
95
  this.#minimap?.destroy();
@@ -397,9 +98,8 @@ export class ViewerController {
397
98
  this.#renderer = null;
398
99
  }
399
100
  destroy() {
400
- this.#destroyed = true;
101
+ super.destroy();
401
102
  this.detach();
402
- this.#listeners.clear();
403
103
  }
404
104
  get camera() {
405
105
  return this.#renderer?.camera ?? null;
@@ -433,7 +133,7 @@ export class ViewerController {
433
133
  return;
434
134
  }
435
135
  // A selection made before the first layout (deep link, `kgdiff-ready` handler) wins.
436
- const target = this.#selectionBounds();
136
+ const target = this.selectionBounds();
437
137
  if (target) {
438
138
  if (!this.#frameInsets(target, FLY_MAX_ZOOM))
439
139
  return;
@@ -449,86 +149,12 @@ export class ViewerController {
449
149
  }
450
150
  /** The user panned / zoomed: suspend replay camera follow for `USER_CAMERA_GRACE`. */
451
151
  noteUserCamera() {
452
- this.#lastUserCamera = this.#deps.now();
152
+ this.#lastUserCamera = this.#now();
453
153
  this.#userMoved = true;
454
154
  }
455
- // ─── Frame loop ───────────────────────────────────────────────────────────
456
- /** Redraw on the next animation frame. */
457
- invalidate() {
458
- this.#frameDirty = true;
459
- this.#schedule();
460
- }
461
- #schedule() {
462
- if (this.#rafId !== 0 || this.#destroyed)
463
- return;
464
- this.#rafId = this.#deps.requestFrame(this.#tick) || 0;
465
- }
466
- #tick = () => {
467
- this.#rafId = 0;
468
- if (this.#destroyed)
469
- return;
470
- const now = this.#deps.now();
471
- const dt = this.#lastTick > 0 ? now - this.#lastTick : 0;
472
- let animating = false;
473
- const clock = this.clock;
474
- if (clock?.playing && this.mode === 'replay') {
475
- clock.advance(dt);
476
- this.#frameDirty = true;
477
- this.#notify('replay');
478
- this.#follow();
479
- if (clock.playing)
480
- animating = true;
481
- else if (clock.finished)
482
- this.#ended();
483
- }
484
- if (!Number.isNaN(this.#restartAt) && !this.#held) {
485
- if (now >= this.#restartAt)
486
- this.#loopAgain();
487
- else
488
- animating = true;
489
- }
490
- if (this.#emphasisAnim) {
491
- const a = this.#emphasisAnim;
492
- const u = a.duration > 0 ? Math.min(1, (now - a.start) / a.duration) : 1;
493
- this.emphasis = a.from + (a.to - a.from) * ease(u);
494
- this.#frameDirty = true;
495
- if (u >= 1) {
496
- this.#emphasisAnim = null;
497
- if (this.#fadingHunk >= 0) {
498
- this.#fadingHunk = -1;
499
- this.emphasis = 1;
500
- }
501
- }
502
- else
503
- animating = true;
504
- }
505
- if (this.#frameDirty)
506
- this.draw(now);
507
- if (animating) {
508
- this.#lastTick = now;
509
- this.#schedule();
510
- }
511
- else
512
- this.#lastTick = 0;
513
- };
514
- #view(layer) {
515
- const selected = this.selectedHunk >= 0 ? this.selectedHunk : this.#fadingHunk;
516
- return createViewState({
517
- layer,
518
- t: this.clock?.t ?? 0,
519
- selectedHunk: selected,
520
- hoveredNode: this.hoverNode,
521
- hoveredEdge: this.hoverEdge >= 0 ? this.hoverEdge : this.pinnedEdge,
522
- selectedNode: this.selectedNode,
523
- focus: this.focus,
524
- families: this.families,
525
- reducedMotion: this.reducedMotion,
526
- emphasis: this.emphasis,
527
- });
528
- }
155
+ // ─── SessionView ──────────────────────────────────────────────────────────
529
156
  /** Resolve the current view and hand it to the renderer (and the minimap). */
530
- draw(now = this.#deps.now()) {
531
- this.#frameDirty = false;
157
+ draw(now = this.#now()) {
532
158
  const resolver = this.resolver;
533
159
  const renderer = this.#renderer;
534
160
  if (!resolver || !renderer || this.status !== 'ready')
@@ -536,14 +162,14 @@ export class ViewerController {
536
162
  const f = this.#frames;
537
163
  let mapFrame;
538
164
  if (this.mode === 'swipe') {
539
- f.before = resolver.resolve(this.#view('before'), f.before ?? undefined);
540
- f.after = resolver.resolve(this.#view('after'), f.after ?? undefined);
165
+ f.before = resolver.resolve(this.viewState('before'), f.before ?? undefined);
166
+ f.after = resolver.resolve(this.viewState('after'), f.after ?? undefined);
541
167
  renderer.setFrame({ split: this.split, before: f.before, after: f.after });
542
168
  mapFrame = f.after;
543
169
  }
544
170
  else {
545
171
  const layer = this.mode === 'replay' ? 'replay' : 'union';
546
- f.main = resolver.resolve(this.#view(layer), f.main ?? undefined);
172
+ f.main = resolver.resolve(this.viewState(layer), f.main ?? undefined);
547
173
  renderer.setFrame(f.main);
548
174
  mapFrame = f.main;
549
175
  }
@@ -555,259 +181,41 @@ export class ViewerController {
555
181
  this.#lastMinimap = now;
556
182
  }
557
183
  }
558
- #startEmphasis(from) {
559
- if (this.reducedMotion) {
560
- this.emphasis = 1;
561
- this.#emphasisAnim = null;
562
- this.#fadingHunk = -1;
563
- return;
564
- }
565
- this.emphasis = from;
566
- this.#emphasisAnim = {
567
- from,
568
- to: 1,
569
- start: this.#deps.now(),
570
- duration: this.theme.motion.base,
571
- };
572
- }
573
- #fadeOutEmphasis(hunk) {
574
- if (this.reducedMotion || hunk < 0) {
575
- this.#fadingHunk = -1;
576
- this.#emphasisAnim = null;
577
- this.emphasis = 1;
578
- return;
579
- }
580
- this.#fadingHunk = hunk;
581
- this.#emphasisAnim = {
582
- from: this.emphasis,
583
- to: 0,
584
- start: this.#deps.now(),
585
- duration: this.theme.motion.base,
586
- };
587
- }
588
- // ─── View: mode × scope ───────────────────────────────────────────────────
589
- /** Whether the scope is fixed to `changes` (the layout covers only the changes). */
590
- get scopeLocked() {
591
- return this.layout?.scope === 'changes';
592
- }
593
- /** Switch how the versions are compared. The legacy `changes` means overlay + `changes` scope. */
594
- setMode(value) {
595
- if (value === LEGACY_CHANGES_MODE) {
596
- this.setView('overlay', 'changes');
597
- return;
598
- }
599
- const mode = toMode(value);
600
- if (mode !== null)
601
- this.setView(mode, this.scope);
602
- }
603
- /** Show the whole graph or only the changes, in any mode. */
604
- setScope(value) {
605
- const scope = toScope(value);
606
- if (scope !== null)
607
- this.setView(this.mode, scope);
184
+ sceneChanged() {
185
+ const f = this.#frames;
186
+ f.main = f.before = f.after = null;
187
+ this.#renderer?.setTheme(this.scene?.theme ?? this.theme);
188
+ this.#minimapDirty = true;
608
189
  }
609
- /** Toggle the `changes` scope (key `4`); says why when the scope is locked. */
610
- toggleScope() {
611
- if (this.scopeLocked) {
612
- this.#host.announce(translate(this.locale, 'scope.locked'));
613
- return;
614
- }
615
- this.setScope(this.scope === 'changes' ? 'all' : 'changes');
190
+ installed() {
191
+ // Fitted after the UI has shown its chrome (the session's notification is delivered
192
+ // first) and once the canvas has a size (see `layoutChanged`).
193
+ this.#needsFit = true;
194
+ this.#savedCamera = null;
195
+ queueMicrotask(() => this.layoutChanged());
616
196
  }
617
- /** Set mode and scope together (one notification, one `kgdiff-mode` event). */
618
- setView(mode, scope) {
619
- const nextScope = this.scopeLocked ? 'changes' : scope;
620
- const modeChanged = mode !== this.mode;
621
- const scopeChanged = nextScope !== this.scope;
622
- if (!modeChanged && !scopeChanged)
623
- return;
624
- this.mode = mode;
625
- this.scope = nextScope;
626
- if (mode !== 'replay') {
627
- this.clock?.pause();
628
- this.#restartAt = Number.NaN;
629
- this.#resume = false;
630
- }
631
- this.#followed = '';
632
- if (scopeChanged) {
633
- this.#updateFocus();
634
- this.#updateOverview();
635
- }
197
+ drawnChanged() {
198
+ this.#updateOverview();
636
199
  this.#minimapDirty = true;
637
- this.#notify('mode', 'focus', 'replay');
638
- this.invalidate();
639
- if (this.status === 'ready') {
640
- this.#host.mode(mode, nextScope);
641
- const parts = [];
642
- if (modeChanged) {
643
- parts.push(translate(this.locale, 'announce.mode', { mode: translate(this.locale, `mode.${mode}`) }));
644
- }
645
- if (scopeChanged) {
646
- parts.push(translate(this.locale, nextScope === 'changes' ? 'scope.on' : 'scope.off'));
647
- }
648
- this.#host.announce(parts.join(' · '));
649
- }
650
- // Switching to replay starts a looping replay; toggling the scope leaves playback alone.
651
- if (modeChanged && mode === 'replay')
652
- this.#autoplay();
653
200
  }
654
- // ─── Selection ────────────────────────────────────────────────────────────
655
- selectHunkById(id, options = {}) {
656
- if (id === null) {
657
- this.#pendingHunk = null;
658
- this.clearSelection();
659
- return;
660
- }
661
- const scene = this.scene;
662
- if (!scene || this.status !== 'ready') {
663
- this.#pendingHunk = { id, fly: options.fly ?? true };
664
- return;
665
- }
666
- const h = scene.hunkIndex.get(id);
667
- if (h !== undefined)
668
- this.selectHunk(h, options);
669
- }
670
- /**
671
- * Select hunk `h` (scene index; -1 clears). `node` focuses one of its nodes in the detail
672
- * panel. `fly` (default true) brings it into view. In replay, seeks to the end of its window.
673
- */
674
- selectHunk(h, options = {}) {
675
- const scene = this.scene;
676
- if (!scene)
677
- return;
678
- if (h < 0 || h >= scene.hunks.length) {
679
- this.clearSelection();
680
- return;
681
- }
682
- const node = options.node ?? -1;
683
- const prev = this.selectedHunk;
684
- const changed = prev !== h || this.selectedNode !== node;
685
- this.selectedHunk = h;
686
- this.selectedNode = node;
687
- this.pinnedEdge = -1;
688
- if (prev !== h) {
689
- this.#fadingHunk = -1;
690
- this.#startEmphasis(prev >= 0 ? SWITCH_EMPHASIS : 0);
691
- if (this.mode === 'replay' && this.clock) {
692
- const end = this.clock.windowEnd(h);
693
- this.clock.pause();
694
- this.#restartAt = Number.NaN;
695
- this.#resume = false;
696
- if (end !== null)
697
- this.clock.seek(end);
698
- this.#followed = '';
699
- this.#notify('replay');
700
- }
701
- }
702
- if (options.fly ?? true)
703
- this.flyToHunk(h);
704
- this.invalidate();
705
- if (!changed)
706
- return;
707
- this.#notify('selection');
708
- const hunk = scene.hunks[h];
709
- if (!hunk)
710
- return;
711
- const nodeId = node >= 0 ? (scene.nodes[node]?.id ?? null) : null;
712
- this.#host.select(hunk.id, nodeId);
713
- if (prev !== h) {
714
- const rank = this.list.rank.get(h);
715
- this.#host.announce(translate(this.locale, 'announce.change', {
716
- i: (rank ?? h) + 1,
717
- n: rank !== undefined ? this.list.order.length : scene.hunks.length,
718
- title: hunk.title,
719
- }));
720
- }
201
+ show(bounds) {
202
+ this.#flyTo(bounds);
721
203
  }
722
- /** Select a node: its hunk when it has one, else the node itself. */
723
- selectNode(i, options = {}) {
724
- const scene = this.scene;
725
- const n = scene?.nodes[i];
726
- if (!scene || !n)
727
- return;
728
- if (n.hunk >= 0) {
729
- this.selectHunk(n.hunk, { ...options, node: i });
730
- return;
731
- }
732
- const prev = this.selectedHunk;
733
- if (prev < 0 && this.selectedNode === i) {
734
- if (options.fly)
735
- this.flyToNode(i);
204
+ /** Follow `bounds` (replay): fly unless the user steered recently or it is mostly visible. */
205
+ follow(bounds) {
206
+ if (this.#now() - this.#lastUserCamera < USER_CAMERA_GRACE)
736
207
  return;
737
- }
738
- this.selectedHunk = -1;
739
- this.selectedNode = i;
740
- this.pinnedEdge = -1;
741
- if (prev >= 0)
742
- this.#fadeOutEmphasis(prev);
743
- if (options.fly)
744
- this.flyToNode(i);
745
- this.invalidate();
746
- this.#notify('selection');
747
- this.#host.select(null, n.id);
748
- this.#host.announce(translate(this.locale, 'announce.node', {
749
- label: n.label,
750
- status: translate(this.locale, `status.${n.status}`),
751
- }));
752
- }
753
- clearSelection() {
754
- if (this.selectedHunk < 0 && this.selectedNode < 0 && this.pinnedEdge < 0)
208
+ const free = this.#freeWorld(bounds);
209
+ if (!free || coverage(bounds, free) >= FOLLOW_COVERAGE)
755
210
  return;
756
- const prev = this.selectedHunk;
757
- this.selectedHunk = -1;
758
- this.selectedNode = -1;
759
- this.pinnedEdge = -1;
760
- this.#fadeOutEmphasis(prev);
761
- this.invalidate();
762
- this.#notify('selection');
763
- this.#host.select(null, null);
764
- this.#host.announce(translate(this.locale, 'announce.cleared'));
765
- }
766
- next() {
767
- this.#stepSelection(1);
768
- }
769
- prev() {
770
- this.#stepSelection(-1);
771
- }
772
- #stepSelection(direction) {
773
- const h = stepHunk(this.list, this.selectedHunk, direction);
774
- if (h >= 0)
775
- this.selectHunk(h);
211
+ this.#flyTo(bounds);
776
212
  }
777
- first() {
778
- const h = this.list.order[0];
779
- if (h !== undefined)
780
- this.selectHunk(h);
213
+ looped() {
214
+ if (this.autoFit)
215
+ void this.fit();
781
216
  }
782
- last() {
783
- const h = this.list.order[this.list.order.length - 1];
784
- if (h !== undefined)
785
- this.selectHunk(h);
786
- }
787
- /** Emphasize an edge (from the detail panel) and fly to it. */
788
- pinEdge(j) {
789
- const scene = this.scene;
790
- const e = scene?.edges[j];
791
- if (!scene || !e)
792
- return;
793
- this.pinnedEdge = j;
794
- const ids = [e.s, e.t, e.sb, e.tb];
795
- let x0 = Number.POSITIVE_INFINITY;
796
- let y0 = Number.POSITIVE_INFINITY;
797
- let x1 = Number.NEGATIVE_INFINITY;
798
- let y1 = Number.NEGATIVE_INFINITY;
799
- for (const i of ids) {
800
- const n = scene.nodes[i];
801
- if (!n)
802
- continue;
803
- x0 = Math.min(x0, n.x - n.r);
804
- y0 = Math.min(y0, n.y - n.r);
805
- x1 = Math.max(x1, n.x + n.r);
806
- y1 = Math.max(y1, n.y + n.r);
807
- }
808
- if (x0 <= x1)
809
- this.#flyTo(padRect({ x: x0, y: y0, width: x1 - x0, height: y1 - y0 }));
810
- this.invalidate();
217
+ viewport() {
218
+ return this.#renderer?.camera.viewport() ?? null;
811
219
  }
812
220
  // ─── Camera ───────────────────────────────────────────────────────────────
813
221
  /** Insets keeping `bounds` clear of the chrome over the canvas, or null before layout. */
@@ -836,76 +244,6 @@ export class ViewerController {
836
244
  const insets = this.#frameInsets(bounds, FLY_MAX_ZOOM) ?? NO_INSETS;
837
245
  return freeView(camera.viewport(), camera.get().k, insets);
838
246
  }
839
- /** “Change 3 of 23: …” for a replayed hunk, “Restructured: 722 changes” for a chapter. */
840
- #announceTarget(kind, index) {
841
- const scene = this.scene;
842
- const clock = this.clock;
843
- if (!scene || !clock)
844
- return;
845
- if (kind === 'chapter') {
846
- const ch = scene.timeline.chapters[index];
847
- if (!ch)
848
- return;
849
- this.#host.announce(translate(this.locale, 'announce.chapter', {
850
- phase: translate(this.locale, `phase.${ch.phase}`),
851
- n: ch.hunks.length,
852
- }));
853
- return;
854
- }
855
- const hunk = scene.hunks[index];
856
- const order = clock.timeline.windows.findIndex((w) => w.hunk === index);
857
- if (!hunk || order < 0)
858
- return;
859
- this.#host.announce(translate(this.locale, 'announce.change', {
860
- i: order + 1,
861
- n: clock.total,
862
- title: hunk.title,
863
- }));
864
- }
865
- /** Follow `hunks` (replay): fly unless the user steered recently or they are mostly visible. */
866
- #followHunks(hunks) {
867
- const scene = this.scene;
868
- if (!scene || hunks.length === 0)
869
- return;
870
- if (this.#deps.now() - this.#lastUserCamera < USER_CAMERA_GRACE)
871
- return;
872
- const bounds = frameBounds(scene, hunks);
873
- const free = this.#freeWorld(bounds);
874
- if (!free || coverage(bounds, free) >= FOLLOW_COVERAGE)
875
- return;
876
- this.#flyTo(bounds);
877
- }
878
- #hunkBounds(h) {
879
- const scene = this.scene;
880
- return scene?.hunks[h] ? frameBounds(scene, [h]) : null;
881
- }
882
- #nodeBounds(i) {
883
- const n = this.scene?.nodes[i];
884
- return n ? padRect({ x: n.x - n.r, y: n.y - n.r, width: 2 * n.r, height: 2 * n.r }) : null;
885
- }
886
- /** Camera target of the current selection, or null. */
887
- #selectionBounds() {
888
- if (this.selectedHunk >= 0)
889
- return this.#hunkBounds(this.selectedHunk);
890
- if (this.selectedNode >= 0)
891
- return this.#nodeBounds(this.selectedNode);
892
- return null;
893
- }
894
- flyToHunk(h) {
895
- const b = this.#hunkBounds(h);
896
- if (b)
897
- this.#flyTo(b);
898
- }
899
- flyToNode(i) {
900
- const b = this.#nodeBounds(i);
901
- if (b)
902
- this.#flyTo(b);
903
- }
904
- flyToSelection() {
905
- const b = this.#selectionBounds();
906
- if (b)
907
- this.#flyTo(b);
908
- }
909
247
  /**
910
248
  * Fit everything visible (the focus in changes-only mode), labels included, into the free part
911
249
  * of the canvas. Before the canvas is laid out it falls back to the renderer's own fit.
@@ -984,47 +322,15 @@ export class ViewerController {
984
322
  if (next === this.overview)
985
323
  return;
986
324
  this.overview = next;
987
- this.#notify('overview');
325
+ this.notify('overview');
988
326
  }
989
327
  zoom(direction) {
990
328
  this.noteUserCamera();
991
329
  this.#renderer?.camera.zoomBy(direction > 0 ? 1.4 : 1 / 1.4);
992
330
  }
993
- /** Replay: fly to the playing hunk / chapter when it changes and is mostly out of view. */
994
- #follow() {
995
- const scene = this.scene;
996
- const clock = this.clock;
997
- const camera = this.#renderer?.camera;
998
- if (!scene || !clock || !camera)
999
- return;
1000
- const target = clock.activeTarget();
1001
- if (target.index < 0)
1002
- return;
1003
- const key = `${target.kind}:${target.index}`;
1004
- if (key === this.#followed)
1005
- return;
1006
- this.#followed = key;
1007
- this.#announceTarget(target.kind, target.index);
1008
- this.#followHunks(target.kind === 'chapter'
1009
- ? (scene.timeline.chapters[target.index]?.hunks ?? [])
1010
- : [target.index]);
1011
- }
1012
331
  // ─── Canvas events ────────────────────────────────────────────────────────
1013
332
  #onHover(pick) {
1014
- const node = pick?.type === 'node' ? pick.index : -1;
1015
- const edge = pick?.type === 'edge' ? pick.index : -1;
1016
- const group = pick?.type === 'collapsed' ? pick.index : -1;
1017
- if (node === this.hoverNode && edge === this.hoverEdge && group === this.hoverGroup)
1018
- return;
1019
- this.hoverNode = node;
1020
- this.hoverEdge = edge;
1021
- this.hoverGroup = group;
1022
- this.#notify('hover');
1023
- this.invalidate();
1024
- }
1025
- /** Clear hover state (pointer left the canvas). */
1026
- clearHover() {
1027
- this.#onHover(null);
333
+ this.setHover(pick?.type === 'node' ? pick.index : -1, pick?.type === 'edge' ? pick.index : -1, pick?.type === 'collapsed' ? pick.index : -1);
1028
334
  }
1029
335
  #onCanvasClick(pick) {
1030
336
  if (!this.selectOnClick)
@@ -1063,416 +369,6 @@ export class ViewerController {
1063
369
  else
1064
370
  this.flyToNode(pick.index);
1065
371
  }
1066
- // ─── Filters, focus ───────────────────────────────────────────────────────
1067
- toggleFamily(family) {
1068
- if (this.families.has(family))
1069
- this.families.delete(family);
1070
- else
1071
- this.families.add(family);
1072
- this.#filtersChanged();
1073
- }
1074
- /** Replace the family filter (empty = all). Setting the current set again clears it. */
1075
- setFamilies(families) {
1076
- const same = families.length === this.families.size && families.every((f) => this.families.has(f));
1077
- this.families.clear();
1078
- if (!same)
1079
- for (const f of families)
1080
- this.families.add(f);
1081
- this.#filtersChanged();
1082
- }
1083
- #filtersChanged() {
1084
- if (this.scene)
1085
- this.list = buildList(this.scene, this.families);
1086
- this.#minimapDirty = true;
1087
- this.#notify('filters');
1088
- this.invalidate();
1089
- }
1090
- setHops(hops) {
1091
- const h = Math.max(0, Math.min(2, Math.round(hops)));
1092
- if (h === this.hops)
1093
- return;
1094
- this.hops = h;
1095
- this.#updateFocus();
1096
- this.#updateOverview();
1097
- this.#minimapDirty = true;
1098
- this.#notify('focus');
1099
- this.invalidate();
1100
- }
1101
- /**
1102
- * Expand collapsed group `index` of the current focus: its in-scene members become visible
1103
- * and, for a `changes`-scoped layout, the neighbours left out of the layout are placed with
1104
- * `extendLayout` (nothing already placed moves) and the scene is rebuilt.
1105
- */
1106
- expandGroup(index) {
1107
- const group = this.focus?.collapsed[index];
1108
- const scene = this.scene;
1109
- if (!group || !scene)
1110
- return;
1111
- const ids = group.nodes.map((i) => scene.nodes[i]?.id).filter(isString);
1112
- if (!this.canExpand(index)) {
1113
- // Without the layout engine only the members already laid out can be shown.
1114
- if (ids.length > 0)
1115
- void this.#expandIds(ids, []);
1116
- return;
1117
- }
1118
- const owner = group.id.startsWith('near:')
1119
- ? group.id.slice(5)
1120
- : group.id.startsWith('component:')
1121
- ? group.id.slice(10)
1122
- : null;
1123
- void this.#expandIds(ids, owner !== null ? [owner, ...ids] : ids);
1124
- }
1125
- /**
1126
- * The collapsed group nearest the selection (else the view center), or -1. Groups that can
1127
- * be expanded at least partly come first.
1128
- */
1129
- nearestGroup() {
1130
- const groups = this.focus?.collapsed ?? [];
1131
- if (groups.length === 0)
1132
- return -1;
1133
- const sel = this.#selectionBounds();
1134
- const view = this.#renderer?.camera.viewport();
1135
- const at = sel ?? view ?? this.scene?.bounds;
1136
- const cx = at ? at.x + at.width / 2 : 0;
1137
- const cy = at ? at.y + at.height / 2 : 0;
1138
- let best = -1;
1139
- let bestScore = Number.POSITIVE_INFINITY;
1140
- groups.forEach((g, i) => {
1141
- const usable = this.canExpand(i) || g.nodes.length > 0;
1142
- const score = Math.hypot(g.x - cx, g.y - cy) + (usable ? 0 : 1e12);
1143
- if (score < bestScore) {
1144
- bestScore = score;
1145
- best = i;
1146
- }
1147
- });
1148
- return best;
1149
- }
1150
- /** Expand the group nearest the selection (keyboard `e`); announces what happened. */
1151
- expandNearest() {
1152
- const i = this.nearestGroup();
1153
- const group = i >= 0 ? this.focus?.collapsed[i] : undefined;
1154
- if (!group || (!this.canExpand(i) && group.nodes.length === 0)) {
1155
- this.#host.announce(translate(this.locale, group ? 'focus.expandUnavailable' : 'announce.nothingHidden'));
1156
- return;
1157
- }
1158
- this.expandGroup(i);
1159
- this.#host.announce(translate(this.locale, 'announce.expanded', { label: group.label }));
1160
- }
1161
- /**
1162
- * Whether collapsed group `index` can be expanded completely: always, unless some members lie
1163
- * outside a `changes`-scoped layout and the layout engine is known to be unavailable
1164
- * (standalone report without the compute add-on).
1165
- */
1166
- canExpand(index) {
1167
- const group = this.focus?.collapsed[index];
1168
- if (!group)
1169
- return false;
1170
- const outside = this.layout?.scope === 'changes' && group.count > group.nodes.length;
1171
- return !outside || computeStatus() !== 'unavailable';
1172
- }
1173
- /**
1174
- * Make `ids` visible, placing those outside the layout, plus the out-of-layout neighbours of
1175
- * `neighboursOf`. Resolves once done (the layout engine may load lazily first).
1176
- */
1177
- #expandIds(ids, neighboursOf) {
1178
- const data = this.data;
1179
- const layout = this.layout;
1180
- if (!data || !layout)
1181
- return Promise.resolve();
1182
- for (const id of ids)
1183
- this.expanded.add(id);
1184
- const missing = new Set();
1185
- if (layout.scope === 'changes') {
1186
- for (const id of ids)
1187
- if (!layout.positions.has(id))
1188
- missing.add(id);
1189
- for (const id of neighboursOf) {
1190
- for (const e of data.diff.index.edgesOf(id)) {
1191
- for (const end of [e.source, e.target, e.sourceBefore, e.targetBefore]) {
1192
- if (end !== undefined && !layout.positions.has(end))
1193
- missing.add(end);
1194
- }
1195
- }
1196
- }
1197
- }
1198
- if (missing.size === 0) {
1199
- this.#focusChanged();
1200
- return Promise.resolve();
1201
- }
1202
- const place = () => {
1203
- const compute = computeNow();
1204
- const current = this.layout;
1205
- if (!compute || !current || this.data !== data)
1206
- return;
1207
- const todo = [...missing].filter((id) => !current.positions.has(id));
1208
- if (todo.length > 0) {
1209
- this.layout = compute.extendLayout(data.diff, current, todo, data.layoutOptions);
1210
- for (const id of todo)
1211
- this.expanded.add(id);
1212
- this.#rebuildScene();
1213
- this.#notify('data', 'selection', 'replay');
1214
- }
1215
- this.#focusChanged();
1216
- };
1217
- if (computeNow()) {
1218
- place();
1219
- return Promise.resolve();
1220
- }
1221
- // Standalone reports load the layout engine on demand.
1222
- return loadCompute().then(place, () => this.#focusChanged());
1223
- }
1224
- #focusChanged() {
1225
- this.#updateFocus();
1226
- this.#updateOverview();
1227
- this.#minimapDirty = true;
1228
- this.#notify('focus');
1229
- this.invalidate();
1230
- }
1231
- /** Bring a union node into the scene and the focus (search results), then select it. */
1232
- revealNode(id) {
1233
- if (!this.data || !this.scene)
1234
- return Promise.resolve();
1235
- const select = () => {
1236
- const i = this.scene?.nodeIndex.get(id);
1237
- if (i !== undefined)
1238
- this.selectNode(i, { fly: true });
1239
- };
1240
- if (this.scene.nodeIndex.has(id) && this.#isVisible(id)) {
1241
- select();
1242
- return Promise.resolve();
1243
- }
1244
- return this.#expandIds([id], []).then(select);
1245
- }
1246
- #isVisible(id) {
1247
- const i = this.scene?.nodeIndex.get(id);
1248
- return i !== undefined && (this.focus === null || this.focus.nodes[i] === 1);
1249
- }
1250
- // ─── Replay ───────────────────────────────────────────────────────────────
1251
- play() {
1252
- const clock = this.clock;
1253
- if (!clock || this.status !== 'ready')
1254
- return;
1255
- if (this.mode !== 'replay')
1256
- this.setMode('replay');
1257
- this.#restartAt = Number.NaN;
1258
- this.#resume = false;
1259
- clock.play();
1260
- this.#followed = '';
1261
- this.#lastTick = 0;
1262
- this.#notify('replay');
1263
- this.invalidate();
1264
- }
1265
- /** Pause; a looping replay stays paused (until `play`, a new diff or loop turned on again). */
1266
- pause() {
1267
- this.#restartAt = Number.NaN;
1268
- this.#resume = false;
1269
- if (!this.clock?.playing)
1270
- return;
1271
- this.clock.pause();
1272
- this.#notify('replay');
1273
- this.invalidate();
1274
- }
1275
- togglePlay() {
1276
- if (this.clock?.playing)
1277
- this.pause();
1278
- else
1279
- this.play();
1280
- }
1281
- /**
1282
- * Play the replay over and over: `delay` ms after it ends it starts again; null plays it
1283
- * once. Turning the loop on starts a replay that is shown but not playing.
1284
- */
1285
- setLoop(delay) {
1286
- const was = this.#loopDelay;
1287
- this.#loopDelay = delay === null ? null : Number.isFinite(delay) ? Math.max(0, delay) : 0;
1288
- if (this.#loopDelay === null)
1289
- this.#restartAt = Number.NaN;
1290
- else if (was === null)
1291
- this.#autoplay();
1292
- }
1293
- get loopDelay() {
1294
- return this.#loopDelay;
1295
- }
1296
- /**
1297
- * Hold playback while the pointer rests on the graph (`pause-on-hover`): a playing replay
1298
- * pauses and continues on release; a pending loop restart waits for the release, then the
1299
- * full loop delay.
1300
- */
1301
- hold(held) {
1302
- if (held === this.#held)
1303
- return;
1304
- this.#held = held;
1305
- const clock = this.clock;
1306
- if (held) {
1307
- if (!clock?.playing)
1308
- return;
1309
- clock.pause();
1310
- this.#resume = true;
1311
- this.#notify('replay');
1312
- this.invalidate();
1313
- return;
1314
- }
1315
- if (!Number.isNaN(this.#restartAt) && this.#loopDelay !== null) {
1316
- this.#restartAt = this.#deps.now() + this.#loopDelay;
1317
- this.#schedule();
1318
- }
1319
- if (this.#resume)
1320
- this.play();
1321
- }
1322
- /** Looping and showing a replay that is not playing: start it (or after the hold). */
1323
- #autoplay() {
1324
- if (this.#loopDelay === null || this.status !== 'ready' || this.mode !== 'replay')
1325
- return;
1326
- if (!this.clock || this.clock.playing || !Number.isNaN(this.#restartAt))
1327
- return;
1328
- if (this.#held)
1329
- this.#resume = true;
1330
- else
1331
- this.play();
1332
- }
1333
- /** Playback reached the end: announce it, tell the host and arm the loop restart. */
1334
- #ended() {
1335
- this.#host.announce(translate(this.locale, 'announce.finished'));
1336
- const loop = this.#loopDelay !== null;
1337
- // Armed first, so a `kgdiff-replay-end` listener can still cancel it (pause, loop off).
1338
- if (loop)
1339
- this.#restartAt = this.#deps.now() + (this.#loopDelay ?? 0);
1340
- this.#host.replayEnd(loop);
1341
- }
1342
- #loopAgain() {
1343
- this.#restartAt = Number.NaN;
1344
- if (this.autoFit)
1345
- void this.fit();
1346
- this.clock?.seek(0);
1347
- this.play();
1348
- }
1349
- seek(t) {
1350
- const clock = this.clock;
1351
- if (!clock)
1352
- return;
1353
- this.#restartAt = Number.NaN;
1354
- clock.seek(t);
1355
- this.#notify('replay');
1356
- this.#follow();
1357
- this.invalidate();
1358
- }
1359
- stepReplay(direction) {
1360
- const clock = this.clock;
1361
- if (!clock)
1362
- return;
1363
- clock.step(direction);
1364
- this.#restartAt = Number.NaN;
1365
- this.#resume = false;
1366
- this.#followed = '';
1367
- // Follow (and announce) the hunk that just completed: stops sit at window ends.
1368
- const w = clock.timeline.windows[clock.position() - 1];
1369
- if (w) {
1370
- if (clock.timeline.mode === 'chapters')
1371
- this.#announceTarget('chapter', w.chapter);
1372
- else
1373
- this.#announceTarget('hunk', w.hunk);
1374
- this.#followHunks(clock.timeline.mode === 'chapters'
1375
- ? (clock.timeline.chapters[w.chapter]?.hunks ?? [w.hunk])
1376
- : [w.hunk]);
1377
- }
1378
- this.#notify('replay');
1379
- this.invalidate();
1380
- }
1381
- restart() {
1382
- this.clock?.seek(0);
1383
- this.play();
1384
- }
1385
- cycleSpeed() {
1386
- this.clock?.cycleSpeed();
1387
- this.#notify('replay');
1388
- }
1389
- setSpeed(speed) {
1390
- this.clock?.setSpeed(speed);
1391
- this.#notify('replay');
1392
- }
1393
- // ─── Swipe ────────────────────────────────────────────────────────────────
1394
- setSplit(split) {
1395
- const s = Number.isFinite(split) ? Math.min(1, Math.max(0, split)) : 0.5;
1396
- if (s === this.split)
1397
- return;
1398
- this.split = s;
1399
- this.#notify('swipe');
1400
- if (this.mode === 'swipe')
1401
- this.invalidate();
1402
- }
1403
- // ─── Review ───────────────────────────────────────────────────────────────
1404
- setReviewed(hunkId, reviewed) {
1405
- const review = this.#review;
1406
- if (!review?.setReviewed(hunkId, reviewed))
1407
- return;
1408
- const progress = review.state();
1409
- this.#notify('review');
1410
- this.#host.review(hunkId, reviewed, progress);
1411
- const text = translate(this.locale, 'review.progress', {
1412
- done: progress.reviewed.length,
1413
- total: progress.total,
1414
- });
1415
- this.#host.announce(translate(this.locale, reviewed ? 'announce.reviewed' : 'announce.unreviewed', {
1416
- progress: text,
1417
- }));
1418
- }
1419
- /** Another tab changed review progress (`storage` event): re-read it. */
1420
- syncReview(key) {
1421
- if (this.#review?.reload(key))
1422
- this.#notify('review');
1423
- }
1424
- toggleReviewed(hunkId) {
1425
- const id = hunkId ?? (this.selectedHunk >= 0 ? this.scene?.hunks[this.selectedHunk]?.id : undefined);
1426
- if (id !== undefined)
1427
- this.setReviewed(id, !this.isReviewed(id));
1428
- }
1429
- // ─── Appearance ───────────────────────────────────────────────────────────
1430
- #appearance(apply) {
1431
- const name = this.themeName;
1432
- const palette = this.palette;
1433
- const locale = this.locale;
1434
- apply();
1435
- const themeChanged = name !== this.themeName || palette !== this.palette;
1436
- const localeChanged = locale !== this.locale;
1437
- if (themeChanged || localeChanged) {
1438
- if (this.data)
1439
- this.#rebuildScene();
1440
- else
1441
- this.#renderer?.setTheme(this.theme);
1442
- }
1443
- if (themeChanged)
1444
- this.#notify('theme');
1445
- if (localeChanged)
1446
- this.#notify('locale', 'data');
1447
- }
1448
- setThemePreference(pref) {
1449
- this.#appearance(() => {
1450
- this.themePreference = toTheme(pref) ?? 'auto';
1451
- });
1452
- this.#notify('theme');
1453
- }
1454
- setPalette(palette) {
1455
- this.#appearance(() => {
1456
- this.palette = toPalette(palette) ?? 'default';
1457
- });
1458
- }
1459
- setLocale(locale) {
1460
- this.#appearance(() => {
1461
- this.locale = toLocale(locale) ?? 'en';
1462
- });
1463
- }
1464
- setSystemDark(dark) {
1465
- this.#appearance(() => {
1466
- this.systemDark = dark;
1467
- });
1468
- }
1469
- setReducedMotion(reduced) {
1470
- this.reducedMotion = reduced;
1471
- this.invalidate();
1472
- }
1473
- }
1474
- function isString(x) {
1475
- return x !== undefined;
1476
372
  }
1477
373
  function sameInsets(a, b) {
1478
374
  return a.top === b.top && a.right === b.right && a.bottom === b.bottom && a.left === b.left;
@@ -1499,10 +395,4 @@ function focusBounds(scene, focus) {
1499
395
  return frameBounds(scene);
1500
396
  return padRect({ x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, 160, 1.12);
1501
397
  }
1502
- /** Pad a small rect so a node is shown with its neighbourhood. */
1503
- function padRect(r, min = 200, ratio = 1.4) {
1504
- const w = Math.max(min, r.width * ratio);
1505
- const h = Math.max(min, r.height * ratio);
1506
- return { x: r.x + r.width / 2 - w / 2, y: r.y + r.height / 2 - h / 2, width: w, height: h };
1507
- }
1508
398
  //# sourceMappingURL=controller.js.map