@whzxc/agent-design-gallery 0.14.1 → 0.16.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 (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +51 -14
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
package/public/app.js CHANGED
@@ -1,32 +1,78 @@
1
- import { createAnnotations, createContextMenu, formatElementReference, READABLE_ANNOTATION_SCALE } from './annotations.js';
1
+ import { recordVisit, createHistoryFilter } from './recent-updates.js';
2
+ import { createContextMenu } from './context-menu.js';
3
+ import { createComments } from './comments.js';
4
+ import { attachComment, commentElement, commentLabel, placeComment } from './comment-anchors.js';
2
5
  import { initSwitcher, updateSwitcherLabels } from './switcher.js';
3
6
  import { dataFetch, keyURL, isUnauthorized } from './auth.js';
4
- import { Labels } from "./labels.js";
5
- import { fitArea, fitView, packingSnapshot, restorePacking } from "./layout.js";
7
+ import { blockForAsset, fitArea, fitView, specimenPaintCrop } from "./layout.js";
6
8
  import { icon, hydrateIcons } from "./icons.js";
7
9
  hydrateIcons();
8
- import { prepare, imageURL, arrange, groupAssets, evictPreviews, metadataContext, measuredMetadata, previewAddress, compactPreparedSource, scopeKind, scopeTarget } from "./assets.js";
10
+ import { fetchSource, prepare, imageURL, arrange, groupAssets, evictPreviews, metadataContext, measuredMetadata, previewAddress, compactPreparedSource, scopeKind, scopeTarget } from "./assets.js";
9
11
  import { sourceRelationships, relatedSources } from './relationships.js';
10
- import { hitSelection, frameBox, exportFrames } from './selection.js';
11
- import { groupTokens, renderTokenTable } from './token-catalog.js';
12
- import { renderReview } from './review.js';
12
+ import { contains, hitSelection, frameBox, exportFrames } from './selection.js';
13
+ import { groupTokens, renderTokenTable, tokenBoardSection } from './token-catalog.js';
13
14
  import { readViewRoute, viewURL } from './view-route.js';
15
+ import { createBoardLayer } from './boards.js';
16
+ import { installMotionSpecimens } from './motion-specimens.js';
17
+ import { boardElement, createFrameCards, frameKey, placePlayButton, playButton, prototypeFlows, renderPrototype } from './view-boards.js';
14
18
  import { createArranger } from './arrangement.js';
15
19
  const arranger = createArranger();
16
20
  window.addEventListener('pagehide',()=>arranger.close());
17
21
  // ARC's gallery layout and camera model, decoupled from its React runtime.
18
22
  const $ = (selector) => document.querySelector(selector);
23
+ const copyTimers = new WeakMap();
24
+ function flashCopied(button) {
25
+ if (!button) return;
26
+ const holder = button.querySelector('[data-icon]');
27
+ button.dataset.copied = 'true';
28
+ if (holder) holder.innerHTML = icon('check', Number(holder.dataset.size) || 12);
29
+ clearTimeout(copyTimers.get(button));
30
+ copyTimers.set(button, setTimeout(() => {
31
+ delete button.dataset.copied;
32
+ if (holder) holder.innerHTML = icon(holder.dataset.icon || 'copy', Number(holder.dataset.size) || 12);
33
+ }, 1200));
34
+ }
19
35
  const viewport = $(".gallery-viewport"),
20
36
  canvas = $("#drawings"),
21
37
  ctx = canvas.getContext("2d"),
22
38
  background = $("#canvas-background"),
23
39
  backgroundContext = background.getContext("2d", { alpha: false });
40
+ const boardLayer = createBoardLayer(viewport, (path, title, button) => {
41
+ const asset = assets.find(a => a.path === path);
42
+ if (asset) selectSource(asset);
43
+ navigator.clipboard.writeText(title).then(() => {
44
+ flashCopied(button);
45
+ if ($('#error').textContent.startsWith('Cannot copy name:')) error('');
46
+ }, failure => error(`Cannot copy name: ${failure.message}`));
47
+ }, {
48
+ onSelectFrame(source, frameName) {
49
+ const item = assets.find(a => a.path === source && (a.component || a.shown[0]?.name === frameName));
50
+ const part = item?.parts.find(p => p.name === frameName);
51
+ if (item && part) selectFrame(item, part);
52
+ else if (item) selectSource(item);
53
+ },
54
+ onFocusFrame: locateFrame,
55
+ onCopyError(failure) {
56
+ if (failure) error(`Cannot copy token name: ${failure.message}`);
57
+ else if ($('#error').textContent.startsWith('Cannot copy token name:')) error('');
58
+ },
59
+ });
60
+ installMotionSpecimens($('#board-chrome'));
61
+ function locateFrame(source, frameName) {
62
+ const item = assets.find(a => a.path === source && (a.component || a.shown[0]?.name === frameName));
63
+ const part = item?.parts.find(p => p.name === frameName);
64
+ if (item && part) inspectForm(item, part);
65
+ }
24
66
  let manifest,
25
67
  catalog = null,
68
+ derivedLanding = false,
26
69
  tokenManifest = null,
27
- reviewManifest = null,
28
70
  tokenCategory = null,
71
+ tokenList = false,
72
+ tokenSearchWasBoard = false,
73
+ tokenHeight = 0,
29
74
  pendingNavigation = null,
75
+ commentUI = null,
30
76
  groups = [],
31
77
  assets = [],
32
78
  world = { x: 0, y: 0, width: 1, height: 1 },
@@ -45,16 +91,6 @@ let raf = 0,
45
91
  loading = 0,
46
92
  queued = [],
47
93
  palette = {};
48
- const labelLayer = new Labels($("#labels"), copyError => {
49
- if (copyError) error(`Cannot copy name: ${copyError.message}`);
50
- else if ($('#error').textContent.startsWith('Cannot copy name:')) error('');
51
- }, target => {
52
- const a=assets.find(a=>a.path===target.path && (target.form===undefined || a.component || a.shown[0].id===target.form));
53
- if (target.form !== undefined) selectFrame(a,a?.parts.find(p=>p.id===target.form));
54
- else selectSource(a);
55
- });
56
- document.fonts.ready.then(() => {labelLayer.metrics.clear();requestDraw()});
57
- let labelsDirty = true, labelObstacles = null;
58
94
  let drawingDirty = true, drawingView = null, drawingMargin = 0, drawingReady = 0, drawingCount = 0;
59
95
  const zoomValue = $("#zoom-value"), zoomOutput = $("output");
60
96
  const cache = new Map(),
@@ -80,10 +116,20 @@ function cacheWrite(url,data,raw=false) {
80
116
  uploadPromises.add(promise);promise.finally(()=>uploadPromises.delete(promise));
81
117
  pumpUploads();return promise;
82
118
  }
119
+ async function uploadCache(task) {
120
+ const headers = {'Content-Type':task.raw ? 'image/svg+xml' : 'application/json'};
121
+ let body = task.raw ? task.data : JSON.stringify(task.data);
122
+ if (body.length >= 16384 && typeof CompressionStream === 'function') {
123
+ const compressed = new Blob([body]).stream().pipeThrough(new CompressionStream('gzip'));
124
+ body = await new Response(compressed).arrayBuffer();
125
+ headers['Content-Encoding'] = 'gzip';
126
+ }
127
+ return dataFetch(task.url, {method:'POST',headers,body});
128
+ }
83
129
  function pumpUploads() {
84
130
  while(uploadActive<3&&uploadQueue.length) {
85
131
  const task=uploadQueue.shift();uploadActive++;
86
- dataFetch(task.url,{method:'POST',headers:{'Content-Type':task.raw?'image/svg+xml':'application/json'},body:task.raw?task.data:JSON.stringify(task.data)})
132
+ uploadCache(task)
87
133
  .then(response=>{if(response.status===409)return false;if(!response.ok)throw Error(`Derived cache HTTP ${response.status}`);return true})
88
134
  .catch(()=>{cacheFailures++;return false})
89
135
  .then(result=>{uploadActive--;cacheWrites--;task.resolve(result);pumpUploads()});
@@ -113,6 +159,14 @@ function decorateMetadata(asset,metadata) {
113
159
  }
114
160
  return entry;
115
161
  }
162
+ async function readSourceMetadata(asset, theme, signal) {
163
+ if (!asset.hash || !asset.metadataRefs?.[theme]) return;
164
+ const query = new URLSearchParams({ theme, context: metadataContext() });
165
+ const response = await dataFetch(`metadata/${asset.hash}?${query}`, { signal });
166
+ if (!response.ok) return;
167
+ const { metadata, previewIds } = await response.json();
168
+ return decorateMetadata({ ...asset, previewIds: { ...asset.previewIds, [theme]: previewIds } }, metadata);
169
+ }
116
170
  function persistSource(entry,theme) {
117
171
  if(!entry.hash || entry.onlyFrame)return Promise.resolve(false);
118
172
  const query=new URLSearchParams({theme,context:metadataContext()});
@@ -139,10 +193,24 @@ let route = {}, routeError;
139
193
  try { route = readViewRoute(new URL(location.href)); }
140
194
  catch (error) { routeError = error; }
141
195
  let initialLink = route.target, strictRoute = route.strict, queryView = !!route.isolated;
142
- let scopeRequest = fixtureName ? 'all' : (route.base && route.scope === 'default' ? 'review' : route.scope ?? 'default'), onlyFrame = route.onlyFrame ?? null;
196
+ let scopeRequest = fixtureName ? 'all' : (route.scope ?? 'default'), onlyFrame = route.onlyFrame ?? null;
143
197
  let initializedScope, initializedFrame, scopeEntry;
144
198
  const currentItem = () => inspection || assets.find((a) => a.id === selectedId);
199
+ function sameView(a, b) {
200
+ return !!a && !!b && a.x === b.x && a.y === b.y && a.scale === b.scale;
201
+ }
145
202
  function remember() {
203
+ const prev = history.at(-1);
204
+ if (prev &&
205
+ prev.scope === initializedScope &&
206
+ (prev.onlyFrame ?? null) === (onlyFrame ?? null) &&
207
+ prev.active === active &&
208
+ prev.selected === selected &&
209
+ prev.selectedForm === selectedForm &&
210
+ (prev.selectedElement?.id ?? null) === (selectedElement?.id ?? null) &&
211
+ sameView(prev.view, view)) {
212
+ return;
213
+ }
146
214
  history.push({
147
215
  view: { ...view },
148
216
  scope: initializedScope,
@@ -159,6 +227,17 @@ function remember() {
159
227
  });
160
228
  if (history.length > 40) history.shift();
161
229
  }
230
+ function exitIsolation(record = true) {
231
+ const data = catalog ?? manifest;
232
+ const asset = data?.assets?.[0];
233
+ const seg = asset?.layer ?? asset?.path?.split('/')[0];
234
+ const next = data?.layers?.length === 1
235
+ ? `layer:${data.layers[0]}`
236
+ : seg && ['components', 'modules', 'surfaces', 'arch'].includes(seg) && (!data?.layers || data.layers.includes(seg))
237
+ ? `layer:${seg}`
238
+ : 'all';
239
+ changeScope(next, null, record);
240
+ }
162
241
  function back() {
163
242
  if (catalog) return;
164
243
  const old = history.pop();
@@ -166,6 +245,10 @@ function back() {
166
245
  changeScope(initializedScope, null, false);
167
246
  return;
168
247
  }
248
+ if (!old && ['group', 'asset'].includes(scopeKind(initializedScope))) {
249
+ exitIsolation(false);
250
+ return;
251
+ }
169
252
  if (old) {
170
253
  if (old.scope && (old.scope !== initializedScope || (old.onlyFrame ?? null) !== onlyFrame)) {
171
254
  changeScope(old.scope, old, false);
@@ -179,22 +262,43 @@ function back() {
179
262
  function changeScope(next, entry = null, record = true) {
180
263
  const nextFrame = entry?.onlyFrame ?? null;
181
264
  if (next === scopeRequest && nextFrame === onlyFrame) return;
182
- if ((initializedScope || tokenManifest || reviewManifest) && !catalog) {
183
- if (record && !tokenManifest && !reviewManifest && next !== 'tokens' && next !== 'review') remember();
265
+ if (frameFilter !== 'all') setFrameFilter('all', false, false);
266
+ const wasOverlay = scopeRequest === 'tokens' || !!tokenManifest;
267
+ const nextOverlay = next === 'tokens';
268
+ const preserveSearch = !fixtureState && !wasOverlay && !nextOverlay && ['all', 'layer'].includes(scopeKind(next)) && !!$("#search").value.trim();
269
+ if ((initializedScope || tokenManifest) && !catalog) {
270
+ if (next === 'tokens' && manifest && !tokenManifest) manifest.view = { ...view };
271
+ if (record && !tokenManifest && next !== 'tokens') remember();
184
272
  void persistPreferences();
185
273
  }
186
274
  scopeRequest = next;
187
275
  onlyFrame = nextFrame;
188
- queryView = entry?.queryView ?? (next !== 'review' && !['all', 'layer'].includes(scopeKind(next)));
276
+ queryView = entry?.queryView ?? !['all', 'layer'].includes(scopeKind(next));
189
277
  strictRoute = false;
190
278
  scopeEntry = entry;
191
279
  initialLink = null;
192
280
  pendingNavigation = null;
193
- if (searchReturn) sidebar = searchReturn.sidebar;
194
- searchReturn = null;
195
- $("#search").value = '';
281
+ tokenSearchWasBoard = false;
282
+ if (!preserveSearch) {
283
+ if (searchReturn) sidebar = searchReturn.sidebar;
284
+ searchReturn = null;
285
+ $("#search").value = '';
286
+ }
196
287
  void refresh(true);
197
288
  }
289
+ function setTokenList(next) {
290
+ if (next === tokenList) return;
291
+ if (!next && !tokenManifest?.tokenBoard) return;
292
+ tokenList = next;
293
+ tokenSearchWasBoard = false;
294
+ updateChrome();
295
+ renderNav();
296
+ if (!tokenList && tokenHeight && world.height <= 1) {
297
+ world = { x: 0, y: 0, width: tokenManifest.tokenBoard.width, height: tokenHeight };
298
+ frame(world);
299
+ }
300
+ requestDraw();
301
+ }
198
302
  function toggleSidebar(value = !sidebar) {
199
303
  sidebar = value;
200
304
  updateChrome();
@@ -202,32 +306,79 @@ function toggleSidebar(value = !sidebar) {
202
306
  }
203
307
  function updateChrome() {
204
308
  updateSwitcherLabels();
205
- const opened = !!(reviewManifest ?? tokenManifest ?? catalog ?? manifest)?.directory;
206
- const showTokens = !!tokenManifest;
207
- const showReview = !!reviewManifest;
208
- const canInspect = opened && !showTokens && !showReview && !!selected;
209
- $('.gallery').classList.toggle('tokens-mode', showTokens || showReview);
210
- $('#token-catalog').hidden = !showTokens;
211
- $('#review-page').hidden = !showReview;
212
- viewport.inert = showTokens || showReview;
213
- $('#sidebar').hidden = !opened || showReview || !sidebar;
214
- $('#sidebar-toggle').hidden = showReview;
215
- $('.search-divider').hidden = showReview;
216
- $('.search-field').hidden = showReview;
217
- $('#annotate').hidden = showReview;
218
- $('#inspect').hidden = showReview;
309
+ const data = tokenManifest ?? catalog ?? manifest;
310
+ const opened = !!data?.directory;
219
311
  $('#app-bar').hidden = !opened;
312
+ $('#frame-filter').hidden=!!tokenManifest || !opened;
313
+ const derived = !tokenManifest && frameFilter !== 'all';
314
+ $('#view-board').hidden = !opened || !derived;
315
+ $('.gallery').classList.toggle('derived-mode', derived);
316
+ const showTokens = !!tokenManifest && tokenList;
317
+ $('#token-list-toggle').hidden = !tokenManifest;
318
+ $('#token-list-toggle').disabled = !tokenManifest?.tokenBoard;
319
+ $('#token-list-toggle').textContent = tokenList ? 'Board view' : 'List view';
320
+ const tokenToggle = $('#token-view-toggle');
321
+ tokenToggle.hidden = !tokenManifest || !!fixtureState;
322
+ tokenToggle.disabled = !tokenManifest?.tokenBoard;
323
+ const tokenMode = tokenList ? 'board' : 'list';
324
+ if (tokenToggle.dataset.mode !== tokenMode) {
325
+ tokenToggle.dataset.mode = tokenMode;
326
+ tokenToggle.innerHTML = `${icon(tokenList ? 'layout-grid' : 'list', 14)}<span>${tokenList ? 'Board view' : 'List view'}</span>`;
327
+ }
328
+ $('#token-board-button').hidden = !tokenManifest?.tokenBoard || !!fixtureState;
329
+ const isolation = $('#scope-isolation');
330
+ const showIsolation = !fixtureState && !tokenManifest && !!data?.scope && (['group', 'asset'].includes(scopeKind(data.scope)) || !!onlyFrame);
331
+ isolation.hidden = !showIsolation;
332
+ if (showIsolation) {
333
+ const label = onlyFrame ? `${scopeLabel(data.scope)} · ${onlyFrame}` : scopeLabel(data.scope);
334
+ if (isolation.dataset.label !== label) {
335
+ isolation.dataset.label = label;
336
+ isolation.innerHTML = `${icon('square-dashed', 12)}<span></span>${icon('x', 12)}`;
337
+ isolation.querySelector('span').textContent = label;
338
+ isolation.setAttribute('aria-label', `Exit isolated scope: ${label}`);
339
+ isolation.dataset.tooltip = 'Show full layer';
340
+ }
341
+ }
342
+ const canInspect = opened && !showTokens && !derived && !!selected;
343
+ $('.gallery').classList.toggle('tokens-mode', showTokens);
344
+ $('#token-catalog').hidden = !showTokens;
345
+ viewport.inert = showTokens || derived;
346
+ viewport.setAttribute('aria-hidden', String(derived));
347
+ $('#sidebar').hidden = !opened || !sidebar || derived;
348
+ $('#sidebar-toggle').hidden = derived;
349
+ $('.search-field').hidden = derived;
350
+ $('.search-divider').hidden = derived;
351
+ $('#scope-isolation').hidden ||= derived;
352
+ const allArch = assets.length > 0 && assets.every(a => a.path.endsWith('.mmd'));
353
+ const canComment = opened && !tokenManifest && !derived && scopeRequest !== 'layer:arch' && !allArch;
354
+ const unavailableReason = canComment ? ''
355
+ : tokenManifest ? 'Tokens take no comments.'
356
+ : scopeRequest === 'layer:arch' || assets.some(a => a.path.endsWith('.mmd')) ? 'Architecture diagrams take no comments.'
357
+ : '';
358
+ $('#comment-tool').hidden = !!tokenManifest && !!fixtureState;
359
+ $('#comment-tool').disabled = !canComment;
360
+ $('#comment-tool').dataset.tooltip = canComment || !unavailableReason ? 'Comment (C)' : unavailableReason;
361
+ commentUI?.setAvailable?.(canComment, unavailableReason);
220
362
  if (fixtureState) $('#app-directory .switcher-chevron').hidden = false;
221
363
  $('#tools').hidden = !opened;
222
- $('.zoom').hidden = !opened || showTokens || showReview;
364
+ $('#comments-toggle').hidden = derived;
365
+ $('#inspect').hidden = derived;
366
+ $('.zoom').hidden = !opened || showTokens || derived;
223
367
  $('#source').hidden = !canInspect || !inspector;
224
368
  $('#inspect').disabled = !canInspect;
225
369
  $('#inspect').setAttribute('aria-expanded', String(canInspect && inspector));
226
- $('#arrange').hidden = showTokens || showReview;
227
- if (!opened || showReview) $('#minimap').hidden = true;
228
- $('#sidebar-toggle').setAttribute('aria-expanded', String(opened && !showReview && sidebar));
370
+ $('#arrange').hidden = !!tokenManifest || derived;
371
+ $('#zoom-fit-group').disabled = !!tokenManifest || active === null || !groups[active];
372
+ $('#zoom-fit-selection').disabled = !!tokenManifest || !selected;
373
+ if (!opened) $('#minimap').hidden = true;
374
+ $('#sidebar-toggle').setAttribute('aria-expanded', String(!$('#sidebar').hidden));
375
+ if (derived) positionViewBoard();
229
376
  positionZoomMenu();
230
377
  }
378
+ function positionViewBoard() {
379
+ $('.gallery').style.setProperty('--view-board-top', ($('#app-bar').getBoundingClientRect().bottom + 10) + 'px');
380
+ }
381
+ new ResizeObserver(() => { if (!$('#view-board').hidden) positionViewBoard(); }).observe($('#app-bar'));
231
382
  function positionZoomMenu() {
232
383
  const r = $("#zoom-options").getBoundingClientRect();
233
384
  $("#zoom-menu").style.left = `${r.x + r.width / 2}px`;
@@ -238,9 +389,8 @@ const media = matchMedia("(prefers-color-scheme: dark)");
238
389
  const modifiedDate = new Intl.DateTimeFormat('en-US', {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
239
390
  window.__adg = {
240
391
  ready: false,
241
- get metadataComplete() {return !!reviewManifest || !!tokenManifest || (!!manifest && !manifest.loading);},
242
- get scope() {return (reviewManifest ?? tokenManifest)?.scope ?? initializedScope;},
243
- get review() {return reviewManifest?.review ?? null;},
392
+ get metadataComplete() {return !!tokenManifest || (!!manifest && !manifest.loading && !derivedLanding);},
393
+ get scope() {return tokenManifest?.scope ?? initializedScope;},
244
394
  get cachePending() {return cacheWrites+loading+queued.length;},
245
395
  get cacheFlush() {return flushCache();},
246
396
  get cacheFailures() {return cacheFailures;},
@@ -248,7 +398,7 @@ window.__adg = {
248
398
  return { ...view };
249
399
  },
250
400
  get assets() {
251
- return reviewManifest || tokenManifest ? 0 : assets.length;
401
+ return tokenManifest ? 0 : assets.length;
252
402
  },
253
403
  get previews() {
254
404
  return {entries: cache.size, decoded: [...cache.values()].filter(e => e.image).length,
@@ -293,7 +443,7 @@ async function api(url, data, keepalive = false, signal) {
293
443
  return result;
294
444
  }
295
445
  function preferences() {
296
- if (reviewManifest || tokenManifest || onlyFrame) return { theme };
446
+ if (tokenManifest || onlyFrame) return { theme };
297
447
  return {
298
448
  view,
299
449
  scope: initializedScope,
@@ -343,91 +493,59 @@ function restoreSelection(target) {
343
493
  }
344
494
  function persistPreferences(keepalive = false) {
345
495
  clearTimeout(saveTimer);
346
- if (fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
496
+ if (fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
347
497
  return api('preferences', preferences(), keepalive).catch(e => error(e.message));
348
498
  }
349
499
  function save() {
350
- if(fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
500
+ if(fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
351
501
  clearTimeout(saveTimer);
352
502
  saveTimer = setTimeout(persistPreferences, 220);
353
503
  }
354
504
  window.addEventListener('pagehide', () => void persistPreferences(true));
355
505
  document.addEventListener('visibilitychange', () => {if (document.hidden) void persistPreferences(true)});
356
- const layoutData = data => onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data;
506
+ const layoutData = data => onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, sourceComponent: !!asset.component, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data;
357
507
  function layout(data, preserve = false, options = {}) {
358
508
  const endArrangement = globalThis.__adgTiming?.span('arrangement', undefined, {sources:data.assets.length,provisional:!!options.provisional});
359
- const previous = assets,
360
- previousGroups = groups,
361
- result = arrange(layoutData(data),options);
509
+ const activeKey = groups[active]?.key;
510
+ const previousGroups = groups,
511
+ result = arrange(layoutData(data),{...options, previousGroups: preserve ? previousGroups : undefined});
362
512
  groups = result.groups;
513
+ if (activeKey) {
514
+ const index = groups.findIndex(group => group.key === activeKey);
515
+ active = index < 0 ? null : index;
516
+ }
363
517
  assets = result.items;
518
+ hoveredPlay = null;
364
519
  world = result.world;
365
- if (preserve) {
366
- const previousById = new Map(previous.map(item => [item.id, item]));
367
- const currentIds = new Set(assets.map(item => item.id));
368
- const previousByTitle = new Map();
369
- for (const group of previousGroups) if (!previousByTitle.has(group.title)) previousByTitle.set(group.title, group);
370
- for (const group of groups) {
371
- const old = previousByTitle.get(group.title);
372
- if (old) {
373
- group.x = old.x;
374
- group.y = old.y;
375
- }
376
- }
377
- const occupied = previous.filter((p) => currentIds.has(p.id));
378
- const shape = (a) =>
379
- JSON.stringify(a.shown.map(p => [p.width, p.height]));
380
- for (const a of assets) {
381
- const old = previousById.get(a.id);
382
- if (old) {
383
- a.x = old.x;
384
- a.y = old.y;
385
- }
386
- if (
387
- old &&
388
- (shape(old) === shape(a) ||
389
- (a.width <= old.width && a.height <= old.height))
390
- ) {
391
- a.width = old.width;
392
- a.height = old.height;
393
- continue;
394
- }
395
- const group = groups[a.group];
396
- a.x = old?.x ?? group.x + 64;
397
- a.y =
398
- Math.max(
399
- group.y + 104,
400
- ...occupied
401
- .filter((p) => previousGroups[p.group]?.title === group.title)
402
- .map((p) => p.y + p.height),
403
- ) + 112;
404
- let collision;
405
- while (
406
- (collision = occupied.find(
407
- (p) =>
408
- p.id !== a.id &&
409
- a.x < p.x + p.width + 20 &&
410
- a.x + a.width + 20 > p.x &&
411
- a.y < p.y + p.height + 20 &&
412
- a.y + a.height + 20 > p.y,
413
- ))
414
- )
415
- a.y = collision.y + collision.height + 112;
416
- const index = occupied.findIndex((p) => p.id === a.id);
417
- if (index >= 0) occupied[index] = a;
418
- else occupied.push(a);
419
- }
420
- for (const g of groups) {
421
- const list = assets.filter((a) => groups[a.group] === g);
422
- g.width = Math.max(g.width, ...list.map((a) => a.x + a.width - g.x + 64));
423
- g.height = Math.max(
424
- g.height,
425
- ...list.map((a) => a.y + a.height - g.y + 64),
426
- );
520
+ if (data.scope === 'all' && data.tokenBoard && tokenHeight) {
521
+ const offset = tokenHeight + 480;
522
+ for (const group of groups) group.y += offset;
523
+ for (const asset of assets) {
524
+ asset.y += offset;
525
+ if (asset.well) asset.well.y += offset;
427
526
  }
428
- world.width = Math.max(1, ...groups.map((g) => g.x + g.width));
429
- world.height = Math.max(1, ...groups.map((g) => g.y + g.height));
527
+ world.height += offset;
528
+ world.width = Math.max(world.width, 1680);
430
529
  }
530
+ if(motionProjection!==data.motionFrames)setMotionProjection(data.motionFrames);
531
+ boardLayer.update(groups, assets, data);
532
+ if (frameFilter !== 'all') renderFrameView();
533
+ boardLayer.tokens(data.scope === 'all' ? data.tokenBoard : null, h => {
534
+ if (Math.abs(tokenHeight-h)>1) {
535
+ const firstMeasurement = !tokenHeight;
536
+ const previousSelection = firstMeasurement ? selectedBox() : null;
537
+ tokenHeight=h;
538
+ layout(data, preserve, options);
539
+ const nextSelection = previousSelection ? selectedBox() : null;
540
+ if (nextSelection) {
541
+ commit({ ...view,
542
+ x: view.x - (nextSelection.x - previousSelection.x) * view.scale,
543
+ y: view.y - (nextSelection.y - previousSelection.y) * view.scale,
544
+ });
545
+ } else if (firstMeasurement && !preserve && !data.view) frame(world);
546
+ requestDraw();
547
+ }
548
+ });
431
549
  renderNav();
432
550
  $("#asset-access").replaceChildren(
433
551
  ...assets.map((a) => {
@@ -437,11 +555,21 @@ function layout(data, preserve = false, options = {}) {
437
555
  return b;
438
556
  }),
439
557
  );
440
- $("#empty").hidden = !!assets.length || !data.directory;
441
- if (!assets.length) $("#empty").textContent = scopedUI(data) ? 'No assets in this scope.' : 'No SVG files in this directory.';
558
+ $("#empty").hidden = !!assets.length || !!data.tokenBoard || !data.directory;
559
+ if (!assets.length) $("#empty").textContent = scopedUI(data) ? 'No assets in this scope.' : 'No design sources in this directory.';
442
560
  endArrangement?.({items:assets.length});
443
561
  if (assets.length) globalThis.__adgTiming?.mark('first-layout');
444
562
  }
563
+ function assetTitle(path = '') {
564
+ const parts = path.split('/');
565
+ const filename = parts.at(-1) ?? '';
566
+ return filename === 'index.tsx' && parts.length > 1
567
+ ? parts.at(-2)
568
+ : filename.replace(/\.(tsx|svg|mmd)$/i, '');
569
+ }
570
+ function displayName(a) {
571
+ return a?.path ? assetTitle(a.path) : a?.name ?? '';
572
+ }
445
573
  function makeRow(name, label, count, className = 'tree-row') {
446
574
  const button = document.createElement('button'); button.className = className;
447
575
  button.innerHTML = icon(name, 14);
@@ -451,8 +579,8 @@ function makeRow(name, label, count, className = 'tree-row') {
451
579
  }
452
580
  function searchResults(query) {
453
581
  const entries = (catalog ?? manifest).assets;
454
- const files = entries.filter(a => a.name.toLowerCase().includes(query)).map(a => ({ a }));
455
- const forms = entries.flatMap(a => a.name.toLowerCase().includes(query) ? [] : (a.parts ?? []).filter(p => p.name.toLowerCase().includes(query)).map(p => ({ a, p })));
582
+ const files = entries.filter(a => displayName(a).toLowerCase().includes(query)).map(a => ({ a }));
583
+ const forms = entries.flatMap(a => displayName(a).toLowerCase().includes(query) ? [] : (a.parts ?? []).filter(p => p.name.toLowerCase().includes(query)).map(p => ({ a, p })));
456
584
  return [...files, ...forms];
457
585
  }
458
586
  function navigate(action) {
@@ -462,17 +590,15 @@ function navigate(action) {
462
590
  function scopedUI(data) { return !!data.layers && (!data.fixture || !!data.fixture.scope); }
463
591
  function scopeLabel(scope) {
464
592
  const target = scopeTarget(scope);
465
- if (scope === 'review') return 'Review';
466
593
  if (scope === 'all') return 'All designs';
467
594
  if (scope === 'tokens') return 'Tokens';
468
595
  if (scopeKind(scope) === 'layer') return target[0].toUpperCase() + target.slice(1);
469
- if (scopeKind(scope) === 'asset') return target.split('/').at(-1).replace(/\.(tsx|svg)$/i,'');
596
+ if (scopeKind(scope) === 'asset') return assetTitle(target);
470
597
  return target;
471
598
  }
472
599
  function renderScopeTabs(data) {
473
600
  const tabs = $('#scope-tabs');
474
- const hasBase = new URL(location.href).searchParams.has('base');
475
- const choices = [...(hasBase ? ['review'] : []), ...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
601
+ const choices = [...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
476
602
  const signature = JSON.stringify([data.scope, choices]);
477
603
  $('#sidebar').classList.toggle('scoped', scopedUI(data));
478
604
  if (tabs.dataset.signature === signature) return;
@@ -502,6 +628,7 @@ $('#scope-tabs').addEventListener('keydown', event => {
502
628
  : step ? tabs[(index + step + tabs.length) % tabs.length] : null;
503
629
  if (!target) return;
504
630
  event.preventDefault();
631
+ event.stopPropagation();
505
632
  target.focus();
506
633
  target.click();
507
634
  });
@@ -518,24 +645,21 @@ function scopeAction(kind, key, label) {
518
645
  }
519
646
  function navFile(a, options = {}) {
520
647
  const { indent=false, isolate=false } = options;
521
- const item=makeRow((a.component ?? a.path.startsWith('components/'))?'component':'app-window',a.name,undefined,'tree-row file');
648
+ const label = displayName(a);
649
+ const item=makeRow((a.component ?? a.path.startsWith('components/'))?'component':'app-window',label,undefined,'tree-row file');
522
650
  item.dataset.navkey=`file:${a.path}`;
523
651
  item.setAttribute('aria-current',String(selected===a.path));
524
652
  item.onclick=()=>navigate(()=>focusAsset(assets.find(x=>x.path===a.path)));
525
653
  if (!isolate) return item;
526
654
  const row=document.createElement('div');row.className='scope-row';
527
655
  if (indent) row.classList.add('scope-row-indent');
528
- row.append(item,scopeAction('asset',a.path,a.name));
656
+ row.append(item,scopeAction('asset',a.path,label));
529
657
  return row;
530
658
  }
531
659
  function renderNav() {
532
- const data = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
660
+ const data = tokenManifest ?? catalog ?? manifest;
533
661
  if (!data) return;
534
662
  renderScopeTabs(data);
535
- if (reviewManifest) {
536
- requestDraw();
537
- return;
538
- }
539
663
  const scoped = scopedUI(data), kind = scoped ? scopeKind(data.scope) : null;
540
664
  const focusKey = document.activeElement?.dataset.navkey;
541
665
  const query = $("#search").value.trim().toLowerCase(), nodes = [];
@@ -552,6 +676,16 @@ function renderNav() {
552
676
  button.setAttribute('aria-current', String(tokenCategory === category));
553
677
  button.onclick = () => {
554
678
  tokenCategory = category;
679
+ if (!tokenList) {
680
+ if (!category) {
681
+ frame(world);
682
+ } else {
683
+ const slug = tokenBoardSection(category);
684
+ const box = slug && boardLayer.tokenSection(slug);
685
+ if (box) commit(fitView(slug === 'motion' ? { ...box, height: Math.min(box.height, 650) } : box, fitArea(width, height, sidebar, false), 24));
686
+ else setTokenList(true);
687
+ }
688
+ }
555
689
  $('.token-scroll').scrollTop = 0;
556
690
  renderNav();
557
691
  };
@@ -560,22 +694,35 @@ function renderNav() {
560
694
  addCategory('All tokens', 'layout-grid', data.tokenGroups.reduce((total, group) => total + group.rows.length, 0), null);
561
695
  const rule = document.createElement('div'); rule.className = 'rule'; nodes.push(rule);
562
696
  for (const {label, glyph, rows} of data.tokenGroups) addCategory(label, glyph, rows.length, label);
697
+ if (!tokenList && data.motionPatternCount && !data.tokenGroups.some(group => group.label === 'Motion'))
698
+ addCategory('Motion', 'timer', data.motionPatternCount, 'Motion');
563
699
  renderTokenTable($('#token-catalog'), data, tokenCategory, query, copyError => {
564
700
  if (copyError) error(`Cannot copy token name: ${copyError.message}`);
565
701
  else if ($('#error').textContent.startsWith('Cannot copy token name:')) error('');
566
702
  });
567
703
  } else if (query) {
568
704
  const results = searchResults(query), heading = document.createElement('h3');
569
- heading.className='search-count'; heading.textContent=`${results.length} ${results.length === 1 ? 'result' : 'results'}`; nodes.push(heading);
705
+ heading.className = 'search-count';
706
+ heading.textContent = results.length === 0 && data.scope && data.scope !== 'all'
707
+ ? `0 results in ${scopeLabel(data.scope)}`
708
+ : `${results.length} ${results.length === 1 ? 'result' : 'results'}`;
709
+ nodes.push(heading);
710
+ if (results.length === 0 && data.scope && data.scope !== 'all') {
711
+ const expand = makeRow('layout-grid', 'Search All designs', undefined, 'tree-row search-result');
712
+ expand.dataset.navkey = 'search:all';
713
+ expand.onclick = () => changeScope('all');
714
+ nodes.push(expand);
715
+ }
570
716
  for (const { a, p } of results) {
717
+ const name = displayName(a);
571
718
  const component = a.component ?? a.path.startsWith('components/');
572
- const button=makeRow(component?'component':'app-window',p ? `${a.name} · ${p.name}` : a.name,p ? 'form' : a.parts ? `${a.parts.length} ${component?'forms':'frames'}` : undefined,'tree-row search-result');
719
+ const button=makeRow(component?'component':'app-window',p ? `${name} · ${p.name}` : name,p ? 'form' : a.parts ? `${a.parts.length} ${component?'forms':'frames'}` : undefined,'tree-row search-result');
573
720
  button.dataset.navkey=`search:${a.path}:${p?.id ?? ''}`;
574
721
  button.setAttribute('aria-current',String(selected===a.path && (!p || selectedForm===p.id)));
575
722
  button.onclick=()=>navigate(()=>p ? inspectForm(a,p) : focusAsset(assets.find(item=>item.path===a.path)));
576
723
  if (scoped && kind!=='asset' && !p) {
577
724
  const row=document.createElement('div');row.className='scope-row';
578
- row.append(button,scopeAction('asset',a.path,a.name));nodes.push(row);
725
+ row.append(button,scopeAction('asset',a.path,name));nodes.push(row);
579
726
  } else nodes.push(button);
580
727
  }
581
728
  } else if (kind === 'asset') {
@@ -616,7 +763,7 @@ function renderNav() {
616
763
  requestDraw();
617
764
  }
618
765
  function renderRelationships(source) {
619
- const basename = path => path.split('/').at(-1).replace(/\.tsx$/, '');
766
+ const basename = path => assetTitle(path);
620
767
  for (const [id,direction] of [['uses','uses'],['used-by','usedBy']]) {
621
768
  const entries=relatedSources(manifest?.relationships ?? {},source,direction), directories=new Map();
622
769
  for (const entry of entries) {
@@ -629,7 +776,7 @@ function renderRelationships(source) {
629
776
  const group=document.createElement('section'),heading=document.createElement('h5');
630
777
  heading.className='relationship-directory';heading.textContent=directory;group.append(heading);
631
778
  for (const entry of directories.get(directory)) {
632
- const via=entry.via.map(path=>basename(path)===basename(entry.path)?path.replace(/\.tsx$/,''):basename(path)).join(' → ');
779
+ const via=entry.via.map(path=>basename(path)===basename(entry.path)?path.replace(/(\/index)?\.(tsx|mmd|svg)$/i,''):basename(path)).join(' → ');
633
780
  const button=makeRow(directory==='surfaces'?'app-window':'component',basename(entry.path)+(via?` · via ${via}`:''),undefined,'tree-row relationship-row'+(entry.direct?'':' indirect'));
634
781
  button.dataset.relatedPath=entry.path;button.dataset.direct=String(entry.direct);
635
782
  button.title=entry.path+(entry.via.length?` via ${entry.via.join(' → ')}`:'');
@@ -647,27 +794,319 @@ function renderRelationships(source) {
647
794
  $('#'+id).replaceChildren(...nodes);
648
795
  }
649
796
  }
797
+ const playableFrames = new Map();
798
+ let motionProjection;
799
+ const frameViews = { recent: 'Recently updated', playable: 'Playable' };
800
+ const frameViewParams = new URLSearchParams(location.search);
801
+ const requestedFrameView = frameViewParams.get('view');
802
+ let pendingFlow = requestedFrameView === 'playable' ? frameViewParams.get('flow') : null;
803
+ let frameFilter = Object.hasOwn(frameViews, requestedFrameView) && scopeRequest !== 'tokens' ? requestedFrameView : 'all';
804
+ let viewGeneration = 0, historyContext, lastIndexedAssets, references, sourcePaths;
805
+ const derivedBoard = $('#view-board'), viewContent = $('#view-board-content');
806
+ const cards = createFrameCards(derivedBoard, {
807
+ preview: drawCardPreview,
808
+ show(source, frame) {
809
+ setFrameFilter('all', false);
810
+ navigate(() => {
811
+ locateFrame(source, frame);
812
+ viewport.focus({ preventScroll: true });
813
+ });
814
+ },
815
+ play: startFramePlayer,
816
+ playable: (source, frame) => playableFrames.get(source)?.has(frame),
817
+ });
818
+ const recentFilter = createHistoryFilter(() => { if (frameFilter === 'recent') renderFrameView(); });
819
+ function openRecentHistory(data) {
820
+ if (!data?.directory) return false;
821
+ const identity = JSON.stringify([data.directory, data.scope, onlyFrame]);
822
+ if (identity === historyContext) return false;
823
+ historyContext = identity;
824
+ void recentFilter.open(data.directory, data.scope, onlyFrame);
825
+ return true;
826
+ }
827
+ window.addEventListener('pagehide', () => recentFilter.close());
828
+ let playerInvoker, deferredView;
829
+ async function startFramePlayer(source, frame, invoker) {
830
+ if (playerInvoker) return;
831
+ playerInvoker = invoker;
832
+ updateFramePlay();
833
+ try {
834
+ const { openPlayer } = await import('./player.js');
835
+ const opening = openPlayer({ source, frame, theme: effectiveTheme, invoker });
836
+ const dialog = $('#motion-player');
837
+ if (dialog) {
838
+ dialog.addEventListener('close', () => {
839
+ playerInvoker = null;
840
+ if (deferredView) renderFrameView();
841
+ updateFramePlay();
842
+ }, { once: true });
843
+ }
844
+ await opening;
845
+ } catch (failure) {
846
+ error(failure.message);
847
+ } finally {
848
+ if (!$('#motion-player')) {
849
+ playerInvoker = null;
850
+ updateFramePlay();
851
+ }
852
+ }
853
+ }
854
+
855
+ function frameReferences() {
856
+ const inventory = derivedLanding ? catalog.assets : assets;
857
+ if (inventory !== lastIndexedAssets) {
858
+ lastIndexedAssets = inventory;
859
+ references = new Map();
860
+ sourcePaths = new Set();
861
+ if (derivedLanding) {
862
+ const byPath = new Map(inventory.map(asset => [asset.path, asset]));
863
+ sourcePaths = new Set(byPath.keys());
864
+ const get = key => {
865
+ const [source, name] = JSON.parse(key);
866
+ const asset = byPath.get(source);
867
+ if (!asset || (onlyFrame && name !== onlyFrame)) return;
868
+ return { asset, part: { name } };
869
+ };
870
+ references = { get, has: key => !!get(key) };
871
+ } else {
872
+ for (const asset of assets) {
873
+ sourcePaths.add(asset.path);
874
+ for (const part of asset.shown ?? []) references.set(frameKey(asset.path, part.name), { asset, part });
875
+ }
876
+ }
877
+ }
878
+ return references;
879
+ }
880
+
881
+ function renderFrameView() {
882
+ if (playerInvoker) {
883
+ deferredView = true;
884
+ return;
885
+ }
886
+ deferredView = false;
887
+ const title = frameViews[frameFilter];
888
+ $('#filter-label').textContent = title ?? 'Filter frames';
889
+ $('#filter-toggle').classList.toggle('active', !!title);
890
+ $('#view-board-title').textContent = title ?? '';
891
+ cards.reset();
892
+ delete viewContent.dataset.historyReady;
893
+ if (!title) {
894
+ viewContent.replaceChildren();
895
+ return;
896
+ }
897
+ const focus = viewContent.contains(document.activeElement)
898
+ ? {
899
+ label: document.activeElement.getAttribute('aria-label'),
900
+ frame: document.activeElement.closest('.view-frame')?.dataset,
901
+ flow: document.activeElement.closest('[data-flow-key]')?.dataset.flowKey,
902
+ }
903
+ : null;
904
+ const frames = frameReferences();
905
+ if (frameFilter === 'recent') {
906
+ const scope = manifest?.scope;
907
+ const inScope = (source, frame, chapter) => (!onlyFrame || onlyFrame === frame) && (scope === 'all' ||
908
+ sourcePaths.has(source) || scopeKind(scope) === 'group' && (chapter ?? source.split('/').slice(0, -1).join('/')) === scopeTarget(scope) ||
909
+ scopeKind(scope) === 'layer' && source.split('/')[0] === scopeTarget(scope));
910
+ recentFilter.render(viewContent, { relative: designSource, frames, inScope, card: cards.card });
911
+ } else {
912
+ const flows = prototypeFlows(manifest?.motionEdges ?? [], frames, designSource);
913
+ if (flows.length) {
914
+ renderPrototype(viewContent, flows, frames, { card: cards.card, play: startFramePlayer, title: assetTitle });
915
+ const target = pendingFlow && viewContent.querySelector('[data-flow-key="' + CSS.escape(pendingFlow) + '"]');
916
+ if (target) requestAnimationFrame(() => {
917
+ if (!pendingFlow || frameFilter !== 'playable' || !target.isConnected) return;
918
+ pendingFlow = null;
919
+ target.scrollIntoView({ block: 'start', inline: 'nearest' });
920
+ target.querySelector('.view-board-action').focus({ preventScroll: true });
921
+ });
922
+ }
923
+ else {
924
+ const status = boardElement('p', 'view-board-status', manifest?.loading ? 'Loading frames…' : 'No playable frames in this scope.');
925
+ status.setAttribute('role', 'status');
926
+ viewContent.replaceChildren(status);
927
+ }
928
+ }
929
+ if (focus?.label && document.activeElement === document.body) {
930
+ const replacement = [...viewContent.querySelectorAll('button[aria-label="' + CSS.escape(focus.label) + '"]')].find(button => {
931
+ const frame = button.closest('.view-frame')?.dataset;
932
+ return frame?.frameName === focus.frame?.frameName && frame?.frameSource === focus.frame?.frameSource &&
933
+ button.closest('[data-flow-key]')?.dataset.flowKey === focus.flow;
934
+ });
935
+ (replacement ?? derivedBoard).focus({ preventScroll: true });
936
+ }
937
+ }
938
+ function setFrameFilter(value, focus = true, loadCanvas = true) {
939
+ closeFilterMenu();
940
+ if (value !== frameFilter) {
941
+ viewGeneration++;
942
+ // Discard queued work belonging to cards on the outgoing derived board.
943
+ queued = queued.filter(entry => {
944
+ if (entry.derived === undefined) return true;
945
+ if (cache.get(entry.key) === entry) cache.delete(entry.key);
946
+ entry.finish();
947
+ return false;
948
+ });
949
+ frameFilter = value;
950
+ const url = new URL(location.href);
951
+ if (value !== 'playable') {
952
+ pendingFlow = null;
953
+ url.searchParams.delete('flow');
954
+ }
955
+ if (value === 'all') url.searchParams.delete('view');
956
+ else url.searchParams.set('view', value);
957
+ window.history.replaceState(window.history.state, '', url);
958
+ if (value === 'recent') {
959
+ if (!openRecentHistory(manifest)) renderFrameView();
960
+ } else {
961
+ recentFilter.close();
962
+ historyContext = null;
963
+ renderFrameView();
964
+ }
965
+ derivedBoard.scrollTop = 0;
966
+ updateChrome();
967
+ if (value === 'all') {
968
+ requestDraw(false, false);
969
+ if (derivedLanding && loadCanvas) void refresh(true);
970
+ }
971
+ }
972
+ if (focus) (value === 'all' ? $('#filter-toggle') : derivedBoard).focus({ preventScroll: true });
973
+ }
974
+ function closeFilterMenu() {
975
+ $('#filter-options').hidden = true;
976
+ $('#filter-toggle').setAttribute('aria-expanded', 'false');
977
+ }
978
+ $('#filter-toggle').onclick = () => {
979
+ const menu = $('#filter-options');
980
+ menu.hidden = !menu.hidden;
981
+ $('#filter-toggle').setAttribute('aria-expanded', String(!menu.hidden));
982
+ for (const b of menu.children) b.setAttribute('aria-pressed', String(b.dataset.filter === frameFilter));
983
+ };
984
+ $('#filter-options').onclick = e => {
985
+ if (e.target.dataset.filter) setFrameFilter(e.target.dataset.filter);
986
+ };
987
+ $('#all-frames').onclick = () => setFrameFilter('all');
988
+ $('#frame-filter').addEventListener('keydown', e => {
989
+ if (e.key !== 'Escape' || $('#filter-options').hidden) return;
990
+ e.stopPropagation();
991
+ e.preventDefault();
992
+ closeFilterMenu();
993
+ $('#filter-toggle').focus();
994
+ });
995
+ document.addEventListener('pointerdown', e => {
996
+ if (!e.target.closest('#frame-filter')) closeFilterMenu();
997
+ });
998
+
999
+ const floatingPlays = new Map();
1000
+ let hoveredPlay;
1001
+ function playablePart(asset) {
1002
+ const part = asset?.shown[0];
1003
+ return playableFrames.get(asset?.path)?.has(part?.name) ? part : null;
1004
+ }
1005
+
1006
+ function canvasPlayPosition(asset, part, toolbars) {
1007
+ const content = frameBox(asset, part), scale = view.scale;
1008
+ if (scale < .18 || content.width * scale < 64 || content.height * scale < 40) return;
1009
+ const screen = box => ({
1010
+ x: view.x + box.x * scale, y: view.y + box.y * scale,
1011
+ width: box.width * scale, height: box.height * scale
1012
+ });
1013
+ const card = screen(asset.well ?? content);
1014
+ const size = Math.min(32, Math.max(20, 24 * Math.sqrt(scale)));
1015
+ const position = placePlayButton(card, screen(content), size, { width, height }, toolbars());
1016
+ if (position) return { ...position, size, card };
1017
+ }
1018
+
1019
+ function playHoverAt(x, y) {
1020
+ if (inspection || !playableFrames.size) return;
1021
+ const item = hoveredElement?.asset;
1022
+ if (hoveredElement?.part) {
1023
+ const part = playablePart(item);
1024
+ return part ? { asset: item, part } : null;
1025
+ }
1026
+ if (hoveredPlay) {
1027
+ const position = floatingPlays.get(frameKey(hoveredPlay.asset.path, hoveredPlay.part.name))?.position;
1028
+ if (position?.outside) {
1029
+ const { card, size } = position;
1030
+ const edgeX = Math.max(card.x, Math.min(position.x + size / 2, card.x + card.width));
1031
+ const edgeY = Math.max(card.y, Math.min(position.y + size / 2, card.y + card.height));
1032
+ const bridge = { x: Math.min(position.x, edgeX), y: Math.min(position.y, edgeY),
1033
+ width: Math.max(position.x + size, edgeX) - Math.min(position.x, edgeX),
1034
+ height: Math.max(position.y + size, edgeY) - Math.min(position.y, edgeY) };
1035
+ if (contains(bridge, x, y)) return hoveredPlay;
1036
+ }
1037
+ }
1038
+ const worldX = (x - view.x) / view.scale, worldY = (y - view.y) / view.scale;
1039
+ const asset = assets.findLast(item => playablePart(item) && contains(item.well ?? item, worldX, worldY));
1040
+ if (asset) return { asset, part: playablePart(asset) };
1041
+ }
1042
+
1043
+ function updateFramePlay() {
1044
+ const next = new Map();
1045
+ let toolbars;
1046
+ const visibleToolbars = () => toolbars ??= [...document.querySelectorAll('.floating[role="toolbar"]:not([hidden])')]
1047
+ .map(element => element.getBoundingClientRect()).filter(rect => rect.width && rect.height);
1048
+ function add(asset, part) {
1049
+ if (!part || !playableFrames.get(asset?.path)?.has(part.name)) return;
1050
+ const position = canvasPlayPosition(asset, part, visibleToolbars);
1051
+ if (position) next.set(frameKey(asset.path, part.name), { asset, part, ...position });
1052
+ }
1053
+ if (frameFilter === 'all' && !tokenManifest && !inspection && !commentUI?.active()) {
1054
+ add(hoveredPlay?.asset, hoveredPlay?.part);
1055
+ const item = currentItem();
1056
+ add(item, item?.parts.find(p => p.id === selectedForm));
1057
+ const focused = [...floatingPlays.values()].find(entry => entry.button === document.activeElement);
1058
+ if (focused) {
1059
+ const asset = assets.find(item => item.id === focused.asset.id);
1060
+ if (asset) add(asset, playablePart(asset));
1061
+ }
1062
+ }
1063
+ for (const [key, { button }] of floatingPlays) {
1064
+ if (next.has(key) || button === playerInvoker) continue;
1065
+ button.remove();
1066
+ floatingPlays.delete(key);
1067
+ }
1068
+ for (const [key, position] of next) {
1069
+ const { asset, part, x, y, size, outside } = position;
1070
+ let button = floatingPlays.get(key)?.button;
1071
+ if (!button) {
1072
+ button = playButton(part.name, event => startFramePlayer(asset.path, part.name, event.currentTarget));
1073
+ button.addEventListener('pointerdown', event => event.stopPropagation());
1074
+ button.addEventListener('dblclick', event => event.stopPropagation());
1075
+ button.addEventListener('blur', () => queueMicrotask(updateFramePlay));
1076
+ viewport.append(button);
1077
+ }
1078
+ floatingPlays.set(key, { button, asset, position });
1079
+ button.style.cssText = 'right:auto;left:' + x + 'px;top:' + y + 'px;--frame-play-size:' + size + 'px';
1080
+ button.toggleAttribute('data-outside', outside);
1081
+ }
1082
+ }
1083
+ function setMotionProjection(projection) {
1084
+ motionProjection = projection;
1085
+ playableFrames.clear();
1086
+ for (const [source, names] of Object.entries(projection ?? {})) playableFrames.set(source, new Set(names));
1087
+ }
650
1088
  function selection() {
651
1089
  hoveredElement=null;
652
1090
  if (!selected) inspector = false;
653
1091
  syncSelectionURL();
654
1092
  renderNav(); updateChrome();
655
- $('#back').disabled = !history.length && !onlyFrame;
1093
+ $('#back').disabled = !history.length && !onlyFrame && !['group', 'asset'].includes(scopeKind(initializedScope));
656
1094
  const host=currentItem(), part=host?.parts.find(p=>p.id===selectedForm);
657
1095
  const owner=selectedElement?.owner;
658
1096
  const hasExport=!!owner?.export;
659
1097
  const a=hasExport ? manifest?.assets.find(a=>a.path===owner.source) ?? manifest?.extraAssets?.find(a=>a.path===owner.source) ?? {path:owner.source,parts:[]} : host;
660
1098
  if(a) {
661
- $('#source-name').textContent=hasExport ? owner.export : a.name;$('#source-path').textContent=a.path;
1099
+ const isComponent = a.sourceComponent ?? a.component ?? manifest?.assets.find(x => x.path === a.path)?.component ?? a.path?.startsWith('components/');
1100
+ $('#source-name').textContent=hasExport ? owner.export : displayName(a);$('#source-path').textContent=a.path;
662
1101
  $('#source-path').title=a.path;
663
1102
  $('#frame-detail').hidden=!part;
664
1103
  $('#frame-name').textContent=part?.name ?? '';
665
1104
  const size=selectedElement ?? part;
666
1105
  $('#frame-size').textContent=size?`${Math.round(size.width)} × ${Math.round(size.height)}`:'';
667
- $('#forms-heading').textContent=hasExport?'Frames using this export':a.component?'Forms':'Frames';
1106
+ $('#forms-heading').textContent=hasExport?'Frames using this export':isComponent?'Forms':'Frames';
668
1107
  const forms=hasExport?exportFrames(a,owner):a.parts;
669
1108
  $('#forms').replaceChildren(...forms.map(p=>{
670
- const button=makeRow(a.component?'component':'app-window',p.name,`${Math.round(p.width)} × ${Math.round(p.height)}`);
1109
+ const button=makeRow(isComponent?'component':'app-window',p.name,`${Math.round(p.width)} × ${Math.round(p.height)}`);
671
1110
  button.classList.add('frame-row');button.title=p.name;
672
1111
  button.dataset.frame=p.name;
673
1112
  button.setAttribute('aria-current',String(!hasExport && selectedForm===p.id));
@@ -682,11 +1121,19 @@ function selection() {
682
1121
  }
683
1122
  function selectSource(a) {
684
1123
  if (!a) return;
685
- remember();inspection=null;selected=a.path;selectedId=a.id;selectedForm=null;selectedElement=null;active=a.group;expanded.add(active);selection();
1124
+ const unchanged = !inspection && selected === a.path && selectedId === a.id && selectedForm === null && selectedElement === null && active === a.group;
1125
+ if (!(unchanged && sameView(history.at(-1)?.view, view) && history.at(-1)?.scope === initializedScope)) remember();
1126
+ inspection=null;selected=a.path;selectedId=a.id;selectedForm=null;selectedElement=null;active=a.group;expanded.add(active);selection();
686
1127
  }
687
1128
  function selectFrame(a,p,element=null) {
688
1129
  if (!a || !p) return;
689
- remember();selected=a.path;selectedId=a.id;selectedForm=p.id;active=a.group;selectedElement=element?{...element,owner:elementOwner(element,a.path)}:null;
1130
+ const nextElement = element ? { ...element, owner: elementOwner(element, a.path) } : null;
1131
+ const unchanged = selected === a.path && selectedId === a.id && selectedForm === p.id && active === a.group &&
1132
+ (selectedElement?.id ?? null) === (nextElement?.id ?? null) &&
1133
+ (selectedElement?.owner?.source ?? null) === (nextElement?.owner?.source ?? null) &&
1134
+ (selectedElement?.owner?.export ?? null) === (nextElement?.owner?.export ?? null);
1135
+ if (!(unchanged && sameView(history.at(-1)?.view, view) && history.at(-1)?.scope === initializedScope)) remember();
1136
+ selected=a.path;selectedId=a.id;selectedForm=p.id;active=a.group;selectedElement=nextElement;
690
1137
  expanded.add(active);selection();
691
1138
  }
692
1139
  function clearSelection() { selected=null;selectedId=null;selectedForm=null;selectedElement=null;inspection=null;selection(); }
@@ -699,94 +1146,155 @@ function selectedBox() {
699
1146
  function copyToClipboard(text) {
700
1147
  navigator.clipboard.writeText(text).catch(e => error(e.message));
701
1148
  }
702
- function visibleFrames() {
703
- const displayed = manifest?.renderTheme === effectiveTheme ? (inspection ? [inspection] : assets) : [];
704
- const list = [];
705
- for (const a of displayed) {
706
- if (!visible(a, 320)) continue;
707
- const parts = a.component ? a.parts : a.parts.filter(p => p.id === a.shown[0]?.id);
708
- for (const part of parts) {
709
- const worldBox = frameBox(a, part);
710
- const box = {
711
- x: view.x + worldBox.x * view.scale,
712
- y: view.y + worldBox.y * view.scale,
713
- width: worldBox.width * view.scale,
714
- height: worldBox.height * view.scale,
715
- };
716
- if (box.x + box.width + 280 < 0 || box.x > width + 40 || box.y + box.height + 40 < 0 || box.y > height + 40) continue;
717
- list.push({ asset: a, part, source: a.path, frame: part.name, world: worldBox, box });
718
- }
719
- }
720
- return list;
721
- }
722
- function locateNoteOnCanvas(row, moveCamera = false) {
723
- const run = () => {
724
- const sourceAsset = manifest?.assets.find(a => a.path === row.source);
725
- const part = sourceAsset?.parts.find(p => p.name === row.frame);
726
- const item = assets.find(a => a.path === row.source && (a.component || !part || a.shown[0]?.id === part.id));
727
- if (!item || !part) return false;
728
- const el = row.element ? (part.elements ?? []).find(e => e.id === row.element.id) : null;
729
- inspection = null;
730
- selectFrame(item, part, el);
731
- if (moveCamera) {
732
- frame(frameBox(item, part), 48);
733
- if (view.scale < READABLE_ANNOTATION_SCALE) zoom(READABLE_ANNOTATION_SCALE);
734
- }
735
- return true;
736
- };
737
- if (!run() && moveCamera && initializedScope !== 'all') {
738
- changeScope('all');
739
- pendingNavigation = () => { run(); annotationUI.render(); };
740
- }
741
- }
742
1149
  const contextMenu = createContextMenu($('#context-menu'), {
743
1150
  viewport,
744
1151
  onOverlayChange: () => { hideTooltip(); requestDraw(true, false); },
745
1152
  });
746
- const annotationUI = createAnnotations({
747
- viewport,
748
- panel: $('#annotations-panel'),
749
- toggleButton: $('#annotate'),
750
- contextMenu,
751
- getState: () => {
752
- const a = currentItem(), p = a?.parts.find(part => part.id === selectedForm);
753
- return {
754
- opened: Boolean(manifest?.directory) && !tokenManifest && !reviewManifest,
755
- projectRoot: manifest?.projectRoot ?? manifest?.directory ?? null,
756
- sourcePrefix: manifest?.sourcePrefix ?? '',
757
- revision: manifest?.revision ?? 0,
758
- scope: initializedScope ?? manifest?.scope ?? 'all',
759
- loading: Boolean(manifest?.loading),
760
- view,
761
- moving,
762
- manifestAssets: manifest?.assets ?? [],
763
- selectedFrame: a && p ? { asset: a, part: p, source: a.path, frame: p.name } : null,
764
- visibleFrames: visibleFrames(),
765
- };
766
- },
767
- hitFrameAt: (worldX, worldY) => {
768
- const hit = hitSelection(inspection ? [inspection] : assets, worldX, worldY);
769
- if (!hit?.part) return null;
770
- return { ...hit, frameBox: frameBox(hit.asset, hit.part) };
1153
+ const boardPoint = (x, y) => {
1154
+ const rect = viewport.getBoundingClientRect();
1155
+ return { x: (x - rect.left - view.x) / view.scale, y: (y - rect.top - view.y) / view.scale };
1156
+ };
1157
+ function asScreen(box) {
1158
+ const rect = viewport.getBoundingClientRect();
1159
+ return { x: rect.left + view.x + box.x * view.scale, y: rect.top + view.y + box.y * view.scale,
1160
+ width: box.width * view.scale, height: box.height * view.scale };
1161
+ }
1162
+ const sourcePrefix = () => catalog?.sourcePrefix ?? manifest?.sourcePrefix ?? '';
1163
+ const projectSource = source => {
1164
+ const prefix = sourcePrefix();
1165
+ return !prefix || source.startsWith(prefix + '/') ? source : prefix + '/' + source;
1166
+ };
1167
+ const designSource = source => sourcePrefix() && source.startsWith(sourcePrefix() + '/') ? source.slice(sourcePrefix().length + 1) : source;
1168
+ const commentable = source => !source?.endsWith('.mmd');
1169
+ const sectionBox = (board, block) => ({ x: board.x + block.x, y: board.y + block.y, width: block.w, height: block.h });
1170
+ const boardGroup = (thread, board) => board.layer === thread.anchor.layer && board.title === thread.anchor.chapter;
1171
+ let commentBoards = [];
1172
+ let commentCatalogRun, commentCatalogLoaded;
1173
+ function refreshCommentCatalog() {
1174
+ if (commentCatalogRun) return commentCatalogRun;
1175
+ const catalog = manifest?.scope === 'all' ? Promise.resolve(manifest) : api('manifest');
1176
+ commentCatalogRun = catalog.then(data => {
1177
+ commentBoards = groupAssets(data);
1178
+ commentCatalogLoaded = true;
1179
+ commentUI.render();
1180
+ }).catch(() => {}).finally(() => { commentCatalogRun = null; });
1181
+ return commentCatalogRun;
1182
+ }
1183
+ const commentOwner = (element, fallback) => {
1184
+ if (!element) return null;
1185
+ const owner = elementOwner(element, fallback);
1186
+ return owner.export ? projectSource(owner.source) + '#' + owner.export : null;
1187
+ };
1188
+ function targetOnBoard(x, y, deepest, point = boardPoint(x, y)) {
1189
+ if (tokenManifest || !manifest || manifest.renderTheme !== effectiveTheme) return null;
1190
+ const { x: wx, y: wy } = point;
1191
+ const hit = hitSelection(inspection ? [inspection] : assets, wx, wy, false);
1192
+ const group = hit ? groups[hit.asset.group] : groups.find(board => contains(board, wx, wy));
1193
+ if (!group || group.layer?.toLowerCase() === 'arch') return null;
1194
+ const block = group.blocks?.find(block => contains(sectionBox(group, block), wx, wy));
1195
+ const path = hit?.asset.path ?? block?.asset;
1196
+ if (!commentable(path) || (!path && group.assets?.every(asset => !commentable(asset.path)))) return null;
1197
+ const part = hit?.part;
1198
+ const frameBounds = part ? frameBox(hit.asset, part) : null;
1199
+ const elementHit = part?.elements?.findLast(element => contains(element, wx - frameBounds.x, wy - frameBounds.y));
1200
+ const element = commentElement(part?.elements, elementHit, deepest);
1201
+ const box = element ? { ...element, x: frameBounds.x + element.x, y: frameBounds.y + element.y }
1202
+ : frameBounds ?? (block ? sectionBox(group, block) : group);
1203
+ return { ...placeComment({ source: path ? projectSource(path) : null, frame: part?.name, layer: group.layer,
1204
+ chapter: group.title, box, frameBox: frameBounds, element, owner: commentOwner(element, path),
1205
+ label: path ? commentLabel(path, part?.name) : `${group.layer} / ${group.title}` }, point),
1206
+ x, y, box: asScreen(box) };
1207
+ }
1208
+ function boardAttachment(thread) {
1209
+ const { source, frame: frameName } = thread.anchor;
1210
+ const path = source && designSource(source);
1211
+ const board = groups.find(group => path ? group.blocks?.some(block => block.asset === path) : boardGroup(thread, group));
1212
+ if (!board) return null;
1213
+ const block = board.blocks?.find(block => block.asset === path);
1214
+ const item = (inspection ? [inspection] : assets).find(asset => asset.path === path && asset.shown[0]?.name === frameName);
1215
+ const part = item?.parts.find(part => part.name === frameName);
1216
+ const attached = attachComment(thread, { chapter: board, source: block && sectionBox(board, block),
1217
+ frame: part && frameBox(item, part), elements: part?.elements });
1218
+ return attached && { ...attached, chapter: board.title, layer: board.layer };
1219
+ }
1220
+
1221
+ function locateComment(thread) {
1222
+ if (tokenManifest) return null;
1223
+ const point = boardAttachment(thread);
1224
+ return point && { ...point, ...asScreen({ x: point.x, y: point.y, width: 0, height: 0 }) };
1225
+ }
1226
+ function focusBoardComment(thread) {
1227
+ const point = boardAttachment(thread);
1228
+ if (!point) return false;
1229
+ const target = point.box;
1230
+ if (!contains(target, point.x, point.y)) return false;
1231
+ if (thread.anchor.kind === 'element' && !point.changed) {
1232
+ const scale = view.scale;
1233
+ commit({ scale, x: cameraArea().x + cameraArea().width / 2 - point.x * scale, y: cameraArea().y + cameraArea().height / 2 - point.y * scale });
1234
+ } else frame(target, 48);
1235
+ return true;
1236
+ }
1237
+ let commentNavigation;
1238
+ async function navigateComment(thread) {
1239
+ if (!tokenManifest && focusBoardComment(thread)) return true;
1240
+ const { layer } = commentBoardPlace(thread);
1241
+ const next = layer ? `layer:${layer}` : 'all';
1242
+ if (scopeRequest === next && !manifest?.loading) return false;
1243
+ if (scopeRequest !== next) changeScope(next);
1244
+ commentNavigation?.resolve(false);
1245
+ return new Promise(resolve => { commentNavigation = { thread, scope: next, resolve }; });
1246
+ }
1247
+ function commentBoardOrder(thread) {
1248
+ const { source, frame: frameName } = thread.anchor;
1249
+ const path = source && designSource(source);
1250
+ const boards = commentBoards.length ? commentBoards : groups;
1251
+ const board = boards.findIndex(group => path ? group.assets?.some(asset => asset.path === path) : boardGroup(thread, group));
1252
+ if (board < 0) return Number.MAX_SAFE_INTEGER;
1253
+ const block = boards[board].assets?.findIndex(asset => asset.path === path) ?? -1;
1254
+ const frameIndex = manifest?.assets.find(asset => asset.path === path)?.parts?.findIndex(part => part.name === frameName) ?? -1;
1255
+ return board * 1_000_000 + (block + 1) * 1_000 + frameIndex + 1;
1256
+ }
1257
+ function commentBoardPlace(thread) {
1258
+ const path = thread.anchor.source && designSource(thread.anchor.source);
1259
+ const board = commentBoards.find(group => path ? group.assets.some(asset => asset.path === path) : boardGroup(thread, group));
1260
+ return board ? { layer: board.layer, chapter: board.title } : { changed: commentBoards.length > 0 };
1261
+ }
1262
+ commentUI = createComments({
1263
+ toolButton: $('#comment-tool'), panelButton: $('#comments-toggle'), panel: $('#comments-panel'), layer: $('#comment-layer'),
1264
+ hitTest: targetOnBoard,
1265
+ locate: locateComment, navigate: navigateComment, boardOrder: commentBoardOrder, boardPlace: commentBoardPlace, request: api,
1266
+ onPanelToggle: open => {
1267
+ if (open && inspector) {
1268
+ inspector = false;
1269
+ updateChrome();
1270
+ requestDraw(true, false);
1271
+ }
771
1272
  },
772
- navigateToNote: row => locateNoteOnCanvas(row, true),
773
- selectNoteTarget: row => locateNoteOnCanvas(row, false),
774
- inspectFrame: (a, p, minScale) => inspectForm(a, p, minScale),
775
- onChromeChange: () => { updateChrome(); requestDraw(true, false); },
776
- copyText: copyToClipboard,
777
- fail: e => error(e.message ?? String(e)),
1273
+ });
1274
+ document.addEventListener('keydown', event => commentUI.key(event));
1275
+ $('#comments-toggle').addEventListener('click', () => {
1276
+ if (!commentCatalogLoaded) void refreshCommentCatalog();
1277
+ if (!$('#comments-panel').hidden && inspector) {
1278
+ inspector = false;
1279
+ updateChrome();
1280
+ requestDraw(true, false);
1281
+ }
778
1282
  });
779
1283
  function updateOutlines() {
780
- annotationUI.render();
1284
+ viewport.dataset.hoverHit = String(!!hoveredElement && !commentUI.active());
1285
+ commentUI.reposition();
1286
+ updateFramePlay();
781
1287
  const hover=hoveredElement,origin=hover?.part?frameBox(hover.asset,hover.part):null;
782
- const hoverBox=hover?.element?{...hover.element,x:origin.x+hover.element.x,y:origin.y+hover.element.y}:null;
783
- for (const [id,box] of [['selection-outline',selectedBox()],['hover-outline',hoverBox]]) {
1288
+ const hoverBox=hover?.element?{...hover.element,x:origin.x+hover.element.x,y:origin.y+hover.element.y}:origin;
1289
+ for (const [id,box] of [['selection-outline',selectedBox() ?? (selected ? currentItem() : null)],['hover-outline',hoverBox]]) {
784
1290
  const el=$('#'+id);el.hidden=!box || moving;
785
1291
  if (box) Object.assign(el.style,{left:`${view.x+box.x*view.scale}px`,top:`${view.y+box.y*view.scale}px`,width:`${box.width*view.scale}px`,height:`${box.height*view.scale}px`});
786
1292
  }
787
1293
  }
788
1294
 
789
- function cameraArea() { return fitArea(width, height, false, false); }
1295
+ function cameraArea() {
1296
+ return fitArea(width,height,false,false);
1297
+ }
790
1298
  function fitWorld(area, data) {
791
1299
  if (scopeKind(data?.scope) !== 'asset' || !assets.length) return fitView(world,area);
792
1300
  const x=Math.min(...assets.map(a=>a.x)), y=Math.min(...assets.map(a=>a.y));
@@ -797,9 +1305,19 @@ function fitWorld(area, data) {
797
1305
  function frame(box, padding = 0) {
798
1306
  const target=box===world?'all':groups.includes(box)?'group':'selection';
799
1307
  for(const name of ['all','group','selection']) $("#zoom-fit-"+name).setAttribute('aria-current',String(name===target));
800
- commit(box===world ? fitWorld(cameraArea(),manifest) : fitView(box, cameraArea(), padding));
1308
+ // Fit is a discrete camera placement. Its viewport is already settled.
1309
+ clearTimeout(idleTimer);
1310
+ moving = false;
1311
+ window.__adg.ready = false;
1312
+ view = box===world ? fitWorld(cameraArea(),manifest) : fitView(box, cameraArea(), padding);
1313
+ requestDraw();
1314
+ save();
801
1315
  }
802
1316
  function fit() {
1317
+ if (tokenManifest) {
1318
+ frame(world);
1319
+ return;
1320
+ }
803
1321
  remember();
804
1322
  inspection = null;
805
1323
  selected = null;
@@ -815,7 +1333,7 @@ function focusAsset(a) {
815
1333
  }
816
1334
  function inspectForm(a,p,minScale=0) {
817
1335
  if (!a || !p) return;
818
- const item=assets.find(item=>item.path===a.path && (a.component || item.shown[0].id===p.id));
1336
+ const item=assets.find(item=>item.path===a.path && (item.component || item.shown[0].id===p.id));
819
1337
  if (!item) {
820
1338
  if (initializedScope !== 'all') {
821
1339
  changeScope(`asset:${a.path}`, { target: { path: a.path, form: p.name } });
@@ -836,7 +1354,6 @@ function zoom(scale, x = cameraArea().x + cameraArea().width / 2, y = cameraArea
836
1354
  }
837
1355
  function commit(next) {
838
1356
  window.__adg.ready = false;
839
- labelsDirty ||= view.scale !== next.scale;
840
1357
  view = next;
841
1358
  moving = true;
842
1359
  requestDraw(false, false);
@@ -847,9 +1364,8 @@ function commit(next) {
847
1364
  requestDraw();
848
1365
  }, 150);
849
1366
  }
850
- function requestDraw(labelsChanged = true, drawingChanged = true) {
1367
+ function requestDraw(_labelsChanged = true, drawingChanged = true) {
851
1368
  drawingDirty ||= drawingChanged;
852
- if (labelsChanged) { labelsDirty = true; labelObstacles = null; }
853
1369
  if (!raf) raf = requestAnimationFrame(draw);
854
1370
  }
855
1371
  function visible(a, margin = 0) {
@@ -877,6 +1393,7 @@ function ensureImage(a, p) {
877
1393
  return e;
878
1394
  }
879
1395
  e = { key, asset: a, part: p, theme:effectiveTheme, used: performance.now(), state: "queued" };
1396
+ e.done = new Promise(resolve => { e.finish = resolve; });
880
1397
  cache.set(key, e);
881
1398
  queued.push(e);
882
1399
  queueMicrotask(pump);
@@ -885,13 +1402,15 @@ function ensureImage(a, p) {
885
1402
  function pump() {
886
1403
  // New vector parsing/decoding waits until the gesture settles. Existing exact
887
1404
  // raster previews continue to move with the camera during interaction.
888
- if(moving)return;
889
- queued.sort((a,b)=>Number(visible(b.asset))-Number(visible(a.asset))||
1405
+ if(moving || loading >= 3 || !queued.length)return;
1406
+ if (frameFilter === 'all') queued.sort((a,b)=>Number(visible(b.asset))-Number(visible(a.asset))||
890
1407
  Math.hypot(view.x+(a.asset.x+a.asset.width/2)*view.scale-width/2,view.y+(a.asset.y+a.asset.height/2)*view.scale-height/2)-
891
1408
  Math.hypot(view.x+(b.asset.x+b.asset.width/2)*view.scale-width/2,view.y+(b.asset.y+b.asset.height/2)*view.scale-height/2));
892
1409
  while (loading < 3 && queued.length) {
893
- const e = queued.shift();
894
- if (!cache.has(e.key)) continue;
1410
+ const next = frameFilter === 'all' ? 0 : queued.findIndex(entry => entry.derived === viewGeneration);
1411
+ if (next === -1) break;
1412
+ const [e] = queued.splice(next, 1);
1413
+ if (cache.get(e.key) !== e) { e.finish(); continue; }
895
1414
  loading++;e.state='loading';
896
1415
  void loadPreview(e);
897
1416
  }
@@ -922,7 +1441,9 @@ async function loadPreview(e) {
922
1441
  const decode=async source=>{
923
1442
  if(cache.get(e.key)!==e)return;
924
1443
  while(moving)await new Promise(resolve=>setTimeout(resolve,16));
925
- const img=new Image();e.image=img;img.decoding='async';img.src=source;
1444
+ const img=new Image();e.image=img;img.decoding='async';
1445
+ if (e.visiblePriority) img.fetchPriority='high';
1446
+ img.src=source;
926
1447
  const endDecode = globalThis.__adgTiming?.span('decode', e.asset.path, {crop:e.part.id});
927
1448
  try { await img.decode();e.state='ready'; } finally {endDecode?.();}
928
1449
  };
@@ -949,20 +1470,70 @@ async function loadPreview(e) {
949
1470
  } finally {
950
1471
  endPreview?.({state:e.state});
951
1472
  if(local&&url)URL.revokeObjectURL(url);
952
- loading--;requestDraw(false);pump();
1473
+ e.finish();
1474
+ loading--;
1475
+ if (frameFilter === 'all') requestDraw(false);
1476
+ pump();
1477
+ }
1478
+ }
1479
+
1480
+ async function drawCardPreview({ asset, part }, canvas) {
1481
+ const unavailable = () => {
1482
+ canvas.dataset.preview = 'unavailable';
1483
+ canvas.after(boardElement('span', 'view-board-status', 'Preview unavailable'));
1484
+ };
1485
+ // A direct derived-board link initially has a source inventory. Measure only
1486
+ // sources whose cards enter view until the user opens the full canvas.
1487
+ const theme = effectiveTheme, generation = viewGeneration;
1488
+ if (part.id === undefined) {
1489
+ try {
1490
+ const saved = asset.metadata?.[theme] ?? metadataCache.get(sourceKey(asset, theme));
1491
+ const measured = saved ? decorateMetadata(asset, saved)
1492
+ : await readSourceMetadata(asset, theme) ?? await sourceFor(asset, theme);
1493
+ if (generation !== viewGeneration || !canvas.isConnected) return;
1494
+ metadataCache.set(sourceKey(measured, theme), measuredMetadata(measured));
1495
+ part = measured.parts.find(candidate => candidate.name === part.name);
1496
+ if (!part) { unavailable(); return; }
1497
+ asset = { ...measured, previewCrop: blockForAsset(measured).previewCrop ?? specimenPaintCrop(measured, part) };
1498
+ } catch {
1499
+ if (canvas.isConnected) unavailable();
1500
+ return;
1501
+ }
1502
+ }
1503
+ const crop = asset.previewCrop ?? part;
1504
+ const entry = ensureImage(asset, crop);
1505
+ entry.derived = viewGeneration;
1506
+ queueMicrotask(pump);
1507
+ await entry.done;
1508
+ if (!canvas.isConnected) return;
1509
+ if (entry.state !== 'ready') {
1510
+ unavailable();
1511
+ return;
1512
+ }
1513
+ const scale = Math.min(1, 205 / part.width, 124 / part.height);
1514
+ canvas.width = Math.max(1, Math.round(part.width * scale * 2));
1515
+ canvas.height = Math.max(1, Math.round(part.height * scale * 2));
1516
+ canvas.style.width = canvas.width / 2 + 'px';
1517
+ canvas.style.height = canvas.height / 2 + 'px';
1518
+ canvas.style.aspectRatio = part.width + ' / ' + part.height;
1519
+ const sx = entry.image.width / crop.width, sy = entry.image.height / crop.height;
1520
+ canvas.getContext('2d').drawImage(entry.image, (part.x - crop.x) * sx, (part.y - crop.y) * sy,
1521
+ part.width * sx, part.height * sy, 0, 0, canvas.width, canvas.height);
1522
+ canvas.dataset.preview = 'ready';
1523
+ if (cache.size > 100) {
1524
+ const pending = new Set([...cache.values()].filter(e => e.state === 'queued' || e.state === 'loading').map(e => e.key));
1525
+ evictPreviews(cache, pending);
953
1526
  }
954
1527
  }
955
1528
 
956
1529
  function thumbnail(e, upgrade = false) {
957
1530
  const scale = Math.min(2, view.scale) * dpr;
958
- if (e.bitmap && (!upgrade || e.bitmapScale >= scale)) return e.bitmap;
959
1531
  const limit = Math.min(scale, 4096 / Math.max(e.part.width, e.part.height));
1532
+ if (e.bitmap && (!upgrade || e.bitmapScale >= limit)) return e.bitmap;
960
1533
  const c = document.createElement('canvas');
961
1534
  c.width = Math.max(1, Math.ceil(e.part.width * limit));
962
1535
  c.height = Math.max(1, Math.ceil(e.part.height * limit));
963
- const preview = c.getContext('2d', { alpha: false });
964
- preview.fillStyle = e.asset.background || palette.canvas;
965
- preview.fillRect(0, 0, c.width, c.height);
1536
+ const preview = c.getContext('2d');
966
1537
  preview.drawImage(e.image, 0, 0, c.width, c.height);
967
1538
  e.bitmap = c;
968
1539
  e.bitmapScale = limit;
@@ -993,13 +1564,30 @@ function draw() {
993
1564
  const endDrawing = globalThis.__adgTiming?.span('drawing');
994
1565
  raf = 0;
995
1566
  drawBackground();
996
- if (tokenManifest || reviewManifest) {
1567
+ if (frameFilter !== 'all' && !tokenManifest) {
1568
+ window.__adg.ready = !!manifest && !manifest.loading && !arranger.pending;
1569
+ window.__adg.revision = manifest?.revision;
1570
+ if (window.__adg.ready && manifest?.directory) void recordVisit(manifest.directory);
1571
+ if (!moving && queued.length) pump();
1572
+ endDrawing?.();
1573
+ return;
1574
+ }
1575
+ if (tokenManifest && tokenList) {
997
1576
  window.__adg.ready = true;
998
- window.__adg.revision = (reviewManifest ?? tokenManifest)?.revision;
1577
+ window.__adg.revision = tokenManifest.revision;
999
1578
  if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
1000
1579
  endDrawing?.(); return;
1001
1580
  }
1002
- if (!labelObstacles) readChromeBounds();
1581
+ if (tokenManifest) {
1582
+ boardLayer.camera(view, false);
1583
+ const percentage = `${Math.round(view.scale * 100)}%`;
1584
+ zoomValue.textContent = percentage; zoomOutput.value = percentage;
1585
+ window.__adg.ready = tokenHeight > 0;
1586
+ window.__adg.revision = tokenManifest.revision;
1587
+ if (fixtureState && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
1588
+ drawMap();
1589
+ endDrawing?.(); return;
1590
+ }
1003
1591
  const displayed = manifest?.renderTheme === effectiveTheme ? inspection ? [inspection] : assets : [];
1004
1592
  // Keep a margin around a settled drawing. Pans can move that
1005
1593
  // retained Canvas layer without replaying or resampling the entire scene.
@@ -1008,7 +1596,7 @@ function draw() {
1008
1596
  Math.abs(dx) <= drawingMargin && Math.abs(dy) <= drawingMargin;
1009
1597
  if (!reuse) {
1010
1598
  const zooming = moving && drawingView?.scale !== view.scale;
1011
- drawingMargin = zooming ? 0 : Math.ceil(Math.min(width, height) / 4);
1599
+ drawingMargin = zooming || manifest?.loading ? 0 : Math.ceil(Math.min(width, height) / 4);
1012
1600
  const bufferWidth = Math.round((width + drawingMargin * 2) * dpr), bufferHeight = Math.round((height + drawingMargin * 2) * dpr);
1013
1601
  if (canvas.width !== bufferWidth || canvas.height !== bufferHeight) {
1014
1602
  canvas.width = bufferWidth; canvas.height = bufferHeight;
@@ -1017,22 +1605,25 @@ function draw() {
1017
1605
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1018
1606
  ctx.clearRect(0, 0, width + drawingMargin * 2, height + drawingMargin * 2);
1019
1607
  ctx.save(); ctx.translate(view.x + drawingMargin, view.y + drawingMargin); ctx.scale(view.scale, view.scale);
1020
- if (!inspection && scopeKind(manifest?.scope)!=='asset') for (const g of groups) {
1608
+ const boardPalette = boardLayer.palette();
1609
+ if (!inspection) for (const g of groups) {
1021
1610
  if (!visible(g, drawingMargin)) continue;
1022
- rounded(g.x, g.y, g.width, g.height, 16 / view.scale, palette['surface-section']);
1023
- ctx.strokeStyle = palette.border; ctx.lineWidth = 1 / view.scale; ctx.stroke();
1611
+ rounded(g.x, g.y, g.width, g.height, 0, boardPalette.surface || palette.surface);
1612
+ for (const section of g.blocks) for (const specimen of section.frames) {
1613
+ const well = specimen.well;
1614
+ rounded(g.x+section.x+well.x, g.y+section.y+well.y, well.w, well.h, parseFloat(boardPalette["radius-card"]) || 12, boardPalette.canvas || palette.canvas);
1615
+ }
1024
1616
  }
1025
1617
  let ready = 0, count = 0;
1026
1618
  for (const a of displayed) {
1027
1619
  if (!visible(a, drawingMargin)) continue;
1028
- const parts = placements(a).map(pos => ({ ...pos, image: ensureImage(a, pos.part) }));
1029
- const raster = moving || view.scale < .8;
1030
- ctx.beginPath(); ctx.roundRect(a.x, a.y, a.width, a.height, Math.min(6 / view.scale, a.width / 2, a.height / 2));
1031
- // Cached previews already contain the asset background; avoid painting it twice.
1032
- if (!raster || parts.some(pos => pos.image.state !== 'ready')) {
1033
- ctx.fillStyle = a.background || palette.canvas; ctx.fill();
1034
- }
1035
- ctx.save(); ctx.clip();
1620
+
1621
+ const parts = placements(a).map(pos => ({ ...pos, image: ensureImage(a, a.previewCrop ?? pos.part) }));
1622
+ ctx.save();
1623
+ const well = a.well ?? a;
1624
+ ctx.beginPath();
1625
+ ctx.roundRect(well.x, well.y, well.width, well.height, parseFloat(boardPalette['radius-card']) || 12);
1626
+ ctx.clip();
1036
1627
  const inViewport = visible(a);
1037
1628
  for (const pos of parts) {
1038
1629
  if (inViewport) count++;
@@ -1040,20 +1631,19 @@ function draw() {
1040
1631
  if (e.state !== 'ready') continue;
1041
1632
  if (inViewport) ready++;
1042
1633
  const source = moving ? thumbnail(e) : view.scale < .8 ? thumbnail(e, true) : e.image;
1043
- if (moving) {
1044
- const left = Math.max(pos.x, (-view.x - drawingMargin) / view.scale);
1045
- const top = Math.max(pos.y, (-view.y - drawingMargin) / view.scale);
1046
- const right = Math.min(pos.x + pos.part.width, (width + drawingMargin - view.x) / view.scale);
1047
- const bottom = Math.min(pos.y + pos.part.height, (height + drawingMargin - view.y) / view.scale);
1048
- const sx = source.width / pos.part.width, sy = source.height / pos.part.height;
1049
- ctx.drawImage(source, (left-pos.x)*sx, (top-pos.y)*sy, (right-left)*sx, (bottom-top)*sy, left, top, right-left, bottom-top);
1050
- } else ctx.drawImage(source, pos.x, pos.y, pos.part.width, pos.part.height);
1634
+ const crop = a.previewCrop ?? pos.part;
1635
+ const paint = a.paintCrop ?? pos.part;
1636
+ const sx = source.width / crop.width, sy = source.height / crop.height;
1637
+ ctx.drawImage(source, (paint.x-crop.x)*sx, (paint.y-crop.y)*sy, paint.width*sx, paint.height*sy,
1638
+ pos.x+paint.x-pos.part.x, pos.y+paint.y-pos.part.y, paint.width, paint.height);
1051
1639
  if (inViewport) globalThis.__adgTiming?.paint('first-content', {source:a.path,crop:pos.part.id});
1052
1640
  }
1053
1641
  ctx.restore();
1054
- const chosen = selected === a.path && selectedForm === null;
1055
- ctx.strokeStyle = chosen ? palette.accent : palette.border;
1056
- ctx.lineWidth = (chosen ? 2 : 1) / view.scale; ctx.stroke();
1642
+ if (a.layer?.toLowerCase() === 'surfaces' || a.path.startsWith('surfaces/')) {
1643
+ ctx.strokeStyle = boardPalette.border || palette.border;
1644
+ ctx.lineWidth = 1;
1645
+ ctx.strokeRect(a.x, a.y, a.width, a.height);
1646
+ }
1057
1647
  }
1058
1648
  ctx.restore();
1059
1649
  drawingReady = ready; drawingCount = count;
@@ -1061,11 +1651,12 @@ function draw() {
1061
1651
  }
1062
1652
  canvas.style.transform = `translate(${view.x - drawingView.x - drawingMargin}px,${view.y - drawingView.y - drawingMargin}px)`;
1063
1653
  updateOutlines();
1064
- drawLabels(displayed);
1654
+ boardLayer.camera(view, !!inspection || !!tokenManifest);
1065
1655
  const percentage = `${Math.round(view.scale * 100)}%`;
1066
1656
  if (zoomValue.textContent !== percentage) zoomValue.textContent = percentage;
1067
1657
  if (zoomOutput.value !== percentage) zoomOutput.value = percentage;
1068
1658
  window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving && !arranger.pending;
1659
+ if (window.__adg.ready && manifest?.directory) void recordVisit(manifest.directory);
1069
1660
  if(fixtureState && fixtureApplied && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
1070
1661
  window.__adg.revision = manifest?.revision;
1071
1662
  window.__adg.visibleReady = drawingReady; window.__adg.visibleCount = drawingCount;
@@ -1074,78 +1665,13 @@ function draw() {
1074
1665
  if(!moving&&queued.length)pump();
1075
1666
  if (cache.size > 100) {
1076
1667
  const activeKeys = new Set(displayed.filter(a => visible(a, drawingMargin))
1077
- .flatMap(a => placements(a).map(({part}) => assetURL(a, part))));
1668
+ .flatMap(a => placements(a).map(({part}) => assetURL(a, a.previewCrop ?? part))));
1078
1669
  evictPreviews(cache, activeKeys);
1079
1670
  }
1080
1671
  endDrawing?.();
1081
1672
  }
1082
1673
  function backgroundColor() { return backgroundChoice === 'theme' ? palette.canvas : backgroundColors[backgroundChoice]; }
1083
1674
 
1084
- function readChromeBounds() {
1085
- const vr = viewport.getBoundingClientRect();
1086
- labelObstacles = [];
1087
- for (const el of document.querySelectorAll('.floating, :popover-open, dialog[open], #tooltip:not([hidden])')) {
1088
- if (el.hidden) continue;
1089
- const style = getComputedStyle(el);
1090
- if (style.visibility === 'hidden' || style.display === 'none') continue;
1091
- const r = el.getBoundingClientRect(), box = { x:r.x-vr.x, y:r.y-vr.y, width:r.width, height:r.height };
1092
- labelObstacles.push(box);
1093
- }
1094
- }
1095
- function drawLabels(displayed) {
1096
- if (!labelsDirty && labelLayer.pan(view)) return;
1097
- const candidates = [], screen = box => ({ x: view.x + box.x * view.scale, y: view.y + box.y * view.scale });
1098
- const caption = Number.parseFloat(palette['text-caption']), meta = Number.parseFloat(palette['text-meta']), section = Number.parseFloat(palette['text-section']);
1099
- const part = (text, size, weight, color, gap = 0) => ({ text, size, weight, color, gap });
1100
- const title = (...args) => ({...part(...args),copyText:args[0]});
1101
- const sourceTitle = (a,...args) => ({...title(...args),selection:{path:a.path}});
1102
- const frameTitle = (a,p,...args) => ({...title(...args),selection:{path:a.path,form:p.id}});
1103
- const modified = a => a.modified ? [{...part(a.modified.text,meta,400,palette['text-tertiary'],10),...a.modified,optional:true}] : [];
1104
- const heading = (x, y, right) => {
1105
- const half = meta * .6;
1106
- let left = Math.max(8, x), edge = Math.min(width - 8, right);
1107
- const center = Math.max(8 + half, y);
1108
- for (const obstacle of labelObstacles) {
1109
- if (center + half <= obstacle.y || center - half >= obstacle.y + obstacle.height) continue;
1110
- if (obstacle.x + obstacle.width <= left || obstacle.x >= edge) continue;
1111
- if (obstacle.x - 12 - left >= edge - obstacle.x - obstacle.width - 12) edge = obstacle.x - 12;
1112
- else left = obstacle.x + obstacle.width + 12;
1113
- }
1114
- return {x:left,y:center,slot:Math.max(0,edge-left),pinned:left !== x || center !== y};
1115
- };
1116
- if (!inspection && scopeKind(manifest?.scope)!=='asset') for (const g of groups) {
1117
- if (!visible(g)) continue;
1118
- const p = screen(g);
1119
- candidates.push({ id: `section:${g.title}`, x: p.x, y: p.y - 16, slot: g.width * view.scale, parts: [title(g.title, section, 650, palette.text), {...part(`${g.assets.length} assets`, meta, 400, palette['text-tertiary'], 8),optional:true}] });
1120
- }
1121
- if (view.scale >= .2) {
1122
- const flows = new Set();
1123
- const labeled = selectedId ? [...displayed].sort((a,b) => Number(b.id === selectedId) - Number(a.id === selectedId)) : displayed;
1124
- for (const a of labeled) {
1125
- if (!visible(a)) continue;
1126
- const p = screen(a), chosen = selectedId === a.id;
1127
- if (a.kind === 'set' || inspection) {
1128
- candidates.push({ id: `set:${a.id}`, ...heading(p.x,p.y-12,p.x+(a.width+64)*view.scale-10),
1129
- parts:[sourceTitle(a,inspection ? a.shown[0].name : a.name,meta,550,chosen ? palette.text : palette['text-secondary']), ...(!inspection ? [{ ...part(`${a.parts.length} ${a.parts.length === 1 ? 'form' : 'forms'}`,meta,400,palette['text-tertiary'],6), optional: true },...modified(a)] : [])] });
1130
- if (!inspection && view.scale >= .75 && a.parts.length > 1) {
1131
- const crop = a.shown[0];
1132
- candidates.push(...a.parts.map(form => ({ id:`form:${a.id}:${form.id}`,x:p.x+(form.x-crop.x)*view.scale,y:p.y+(form.y-crop.y)*view.scale-9.5,slot:Infinity,height:13,paddingRight:6,within:{x:p.x,y:p.y,width:a.width*view.scale,height:a.height*view.scale},
1133
- parts:[frameTitle(a,form,form.name,caption,400,palette['text-tertiary'])] })));
1134
- }
1135
- } else {
1136
- if (!flows.has(a.path)) {
1137
- flows.add(a.path);
1138
- const family = displayed.filter(item => item.path === a.path), first = family[0];
1139
- const origin = screen(first), right = Math.max(...family.map(item => item.x+item.width));
1140
- candidates.push({ id:`flow:${a.path}`,...heading(origin.x,origin.y-34,origin.x+(right-first.x)*view.scale),parts:[sourceTitle(a,a.name,meta,600,palette['text-secondary']),{...part(`${a.parts.length} ${a.parts.length === 1 ? 'frame' : 'frames'}`,meta,400,palette['text-tertiary'],6),optional:true},...modified(a)] });
1141
- }
1142
- candidates.push({ id:`frame:${a.id}`,x:p.x,y:p.y-12,slot:(a.width+64)*view.scale,parts:[frameTitle(a,a.shown[0],a.shown[0].name,caption,chosen?550:400,chosen?palette.text:palette['text-tertiary'])] });
1143
- }
1144
- }
1145
- }
1146
- labelLayer.update(candidates,labelObstacles,width,height,palette['font-ui'],view);
1147
- labelsDirty = false;
1148
- }
1149
1675
  function mapGeometry() {
1150
1676
  const scale=Math.min(168/world.width,100/world.height);
1151
1677
  return {scale,x:(200-world.width*scale)/2,y:(132-world.height*scale)/2};
@@ -1154,10 +1680,15 @@ function drawMap() {
1154
1680
  const map=$("#minimap");if(map.hidden)return;
1155
1681
  if(map.width!==200*dpr||map.height!==132*dpr){map.width=200*dpr;map.height=132*dpr}
1156
1682
  const c=map.getContext('2d'),{scale:s,x,y}=mapGeometry();c.setTransform(dpr,0,0,dpr,0,0);c.clearRect(0,0,200,132);
1157
- for(const g of groups){c.fillStyle=palette['surface-section'];c.strokeStyle=palette.border;c.beginPath();c.roundRect(x+g.x*s,y+g.y*s,g.width*s,g.height*s,4);c.fill();c.stroke()}
1683
+ const boxes = tokenManifest
1684
+ ? [{ x: 0, y: 0, width: world.width, height: world.height }]
1685
+ : manifest?.scope === 'all' && manifest.tokenBoard && tokenHeight
1686
+ ? [{ x: 0, y: 0, width: manifest.tokenBoard.width, height: tokenHeight }, ...groups]
1687
+ : groups;
1688
+ for(const g of boxes){c.fillStyle=palette['surface-section'];c.strokeStyle=palette.border;c.beginPath();c.roundRect(x+g.x*s,y+g.y*s,g.width*s,g.height*s,4);c.fill();c.stroke()}
1158
1689
  c.strokeStyle=palette.accent;c.lineWidth=1;
1159
1690
  const area=cameraArea();
1160
- c.strokeRect(x+(area.x-view.x)/view.scale*s,y+(area.y-view.y)/view.scale*s,area.width/view.scale*s,area.height/view.scale*s);
1691
+ c.strokeRect(x+(area.x-view.x)/view.scale*s,y+(area.y-view.y)/view.scale*s,Math.max(6,area.width/view.scale*s),Math.max(6,area.height/view.scale*s));
1161
1692
  }
1162
1693
 
1163
1694
  function applyTheme() {
@@ -1173,9 +1704,17 @@ function applyTheme() {
1173
1704
  );
1174
1705
  palette.raised = css.getPropertyValue("--surface-sunken").trim();
1175
1706
  palette.muted = css.getPropertyValue("--text-secondary").trim();
1176
- for (const sheet of document.styleSheets) for(const rule of sheet.cssRules ?? []) {
1177
- if(rule.selectorText === ':root' && rule.style.getPropertyValue('--canvas')) backgroundColors.light=rule.style.getPropertyValue('--canvas').trim();
1178
- if(rule.selectorText === ':root[data-theme="dark"]' && rule.style.getPropertyValue('--canvas')) backgroundColors.dark=rule.style.getPropertyValue('--canvas').trim();
1707
+ for (const sheet of document.styleSheets) {
1708
+ let rules;
1709
+ try { rules = sheet.cssRules; } catch { continue; }
1710
+ for (const rule of rules ?? []) {
1711
+ if (rule.selectorText === ':root' && rule.style.getPropertyValue('--canvas')) {
1712
+ backgroundColors.light = rule.style.getPropertyValue('--canvas').trim();
1713
+ }
1714
+ if (rule.selectorText === ':root[data-theme="dark"]' && rule.style.getPropertyValue('--canvas')) {
1715
+ backgroundColors.dark = rule.style.getPropertyValue('--canvas').trim();
1716
+ }
1717
+ }
1179
1718
  }
1180
1719
  backgroundColors.neutral=`color-mix(in srgb, ${backgroundColors.light} 50%, ${backgroundColors.dark})`;
1181
1720
  updateChoices();
@@ -1184,13 +1723,14 @@ function applyTheme() {
1184
1723
  for (const b of $("#themes").children)
1185
1724
  b.onclick = () => {
1186
1725
  theme = b.dataset.theme;
1726
+ localStorage.setItem('adg-theme', theme);
1187
1727
  applyTheme();
1188
- if (!reviewManifest) void refresh(true);
1728
+ void refresh(true);
1189
1729
  save();
1190
1730
  };
1191
1731
  media.addEventListener("change", () => {
1192
1732
  applyTheme();
1193
- if (!reviewManifest) void refresh(true);
1733
+ void refresh(true);
1194
1734
  });
1195
1735
  viewport.addEventListener(
1196
1736
  "wheel",
@@ -1216,23 +1756,30 @@ viewport.addEventListener(
1216
1756
  );
1217
1757
  viewport.addEventListener("pointerdown", (e) => {
1218
1758
  if (e.button !== 0 && e.button !== 1) return;
1219
- if(e.target.closest('.annotation-layer'))return;
1220
1759
  e.preventDefault();
1221
1760
  viewport.focus({ preventScroll: true });
1222
1761
  pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
1223
1762
  if (pointers.size === 1)
1224
- gesture = { x: e.clientX, y: e.clientY, moved: false };
1763
+ gesture = { x: e.clientX, y: e.clientY, button: e.button, moved: false };
1225
1764
  else gesture.moved = true;
1226
1765
  viewport.setPointerCapture(e.pointerId);
1227
1766
  });
1228
1767
  viewport.addEventListener("pointermove", (e) => {
1229
1768
  const old = pointers.get(e.pointerId);
1230
1769
  if (!old) {
1231
- const rect=viewport.getBoundingClientRect();
1232
- hoveredElement=hitSelection(inspection?[inspection]:assets,(e.clientX-rect.left-view.x)/view.scale,(e.clientY-rect.top-view.y)/view.scale);
1770
+ if (commentUI.active()) {
1771
+ hoveredElement = hoveredPlay = null;
1772
+ commentUI.hover(e.clientX, e.clientY, e.altKey);
1773
+ updateOutlines();
1774
+ return;
1775
+ }
1776
+ if (e.target.closest('.frame-play')) return;
1777
+ const rect = viewport.getBoundingClientRect(), x = e.clientX - rect.left, y = e.clientY - rect.top;
1778
+ hoveredElement = hitSelection(inspection ? [inspection] : assets, (x - view.x) / view.scale, (y - view.y) / view.scale);
1779
+ hoveredPlay = playHoverAt(x, y);
1233
1780
  updateOutlines();return;
1234
1781
  }
1235
- hoveredElement=null;updateOutlines();
1782
+ hoveredElement=hoveredPlay=null;commentUI.hover();updateOutlines();
1236
1783
  const before = [...pointers.values()];
1237
1784
  pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
1238
1785
  if (Math.hypot(e.clientX - gesture.x, e.clientY - gesture.y) > 4)
@@ -1261,18 +1808,21 @@ viewport.addEventListener("pointermove", (e) => {
1261
1808
  });
1262
1809
  }
1263
1810
  });
1264
- viewport.addEventListener('pointerleave',()=>{hoveredElement=null;updateOutlines()});
1811
+ viewport.addEventListener('pointerleave',()=>{hoveredElement=hoveredPlay=null;commentUI.hover();updateOutlines()});
1265
1812
  function up(e) {
1266
1813
  if (!pointers.delete(e.pointerId)) return;
1267
- if (e.type === "pointerup" && !gesture.moved) {
1814
+ if (e.type === "pointerup" && !gesture.moved && gesture.button === 0) {
1268
1815
  const rect = viewport.getBoundingClientRect(),
1269
1816
  x = (e.clientX - rect.left - view.x) / view.scale,
1270
1817
  y = (e.clientY - rect.top - view.y) / view.scale;
1271
1818
  const hit=hitSelection(inspection?[inspection]:assets,x,y);
1272
- if(annotationUI.active()) { annotationUI.click(x,y); return; }
1273
- if(hit?.part) selectFrame(hit.asset,hit.part,hit.element);
1274
- else if(hit) selectSource(hit.asset);
1275
- else clearSelection();
1819
+ if (commentUI.active()) commentUI.click(e.clientX, e.clientY, e.altKey);
1820
+ else {
1821
+ commentUI?.dismiss?.();
1822
+ if(hit?.part) selectFrame(hit.asset,hit.part,hit.element);
1823
+ else if(hit) selectSource(hit.asset);
1824
+ else clearSelection();
1825
+ }
1276
1826
  }
1277
1827
  if (viewport.hasPointerCapture(e.pointerId))
1278
1828
  viewport.releasePointerCapture(e.pointerId);
@@ -1280,41 +1830,23 @@ function up(e) {
1280
1830
  }
1281
1831
  for (const event of ["pointerup", "pointercancel", "lostpointercapture"])
1282
1832
  viewport.addEventListener(event, up);
1283
- function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnFocus = viewport }) {
1833
+ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, deepest, returnFocus = viewport }) {
1284
1834
  const a = currentItem(), p = a?.parts.find(part => part.id === selectedForm), el = selectedElement;
1835
+ const placement = targetOnBoard(screenX, screenY, deepest, worldPoint ?? undefined);
1836
+ const comment = placement && placement.anchor.kind !== 'chapter' ? [{ label: 'Comment', action: () => commentUI.place(placement) }] : [];
1285
1837
  if (a && p && el) {
1286
- const fb = frameBox(a, p);
1287
1838
  const owner = elementOwner(el, a.path);
1288
- const fx = worldPoint ? Math.max(0, Math.min(1, (worldPoint.x - fb.x) / fb.width)) : (p.width > 0 ? Math.max(0, Math.min(1, (el.x + el.width / 2) / p.width)) : 0.5);
1289
- const fy = worldPoint ? Math.max(0, Math.min(1, (worldPoint.y - fb.y) / fb.height)) : (p.height > 0 ? Math.max(0, Math.min(1, (el.y + el.height / 2) / p.height)) : 0.5);
1290
- const ex = worldPoint && el.width > 0 ? Math.max(0, Math.min(1, (worldPoint.x - (fb.x + el.x)) / el.width)) : 0.5;
1291
- const ey = worldPoint && el.height > 0 ? Math.max(0, Math.min(1, (worldPoint.y - (fb.y + el.y)) / el.height)) : 0.5;
1292
1839
  contextMenu.open([
1293
- {
1294
- label: 'Annotate here',
1295
- action: () => annotationUI.annotateAt({
1296
- source: a.path,
1297
- frame: p.name,
1298
- fx,
1299
- fy,
1300
- element: { id: el.id, owner, x: ex, y: ey },
1301
- returnFocus,
1302
- }),
1303
- },
1840
+ ...comment,
1304
1841
  {
1305
1842
  label: 'Copy element reference',
1306
- action: () => copyToClipboard(formatElementReference({
1307
- sourcePrefix: manifest?.sourcePrefix ?? '',
1308
- source: a.path,
1309
- owner,
1310
- frame: p.name,
1311
- elementId: el.id,
1312
- })),
1843
+ action: () => copyToClipboard(`source=${projectSource(a.path)} export=${owner?.export ? (owner.source === a.path ? owner.export : `${projectSource(owner.source)}#${owner.export}`) : 'none'} frame=${JSON.stringify(p.name)} element=${el.id}`),
1313
1844
  },
1314
1845
  {
1315
1846
  label: 'Show in Inspector',
1316
1847
  action: () => {
1317
1848
  inspector = true;
1849
+ commentUI?.closePanel?.();
1318
1850
  selection();
1319
1851
  $('#copy-path')?.focus({ preventScroll: true });
1320
1852
  },
@@ -1324,6 +1856,7 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1324
1856
  disabled: !owner?.export,
1325
1857
  action: async () => {
1326
1858
  inspector = true;
1859
+ commentUI?.closePanel?.();
1327
1860
  if (owner?.source && !manifest?.assets.some(item => item.path === owner.source) && !manifest?.extraAssets?.some(item => item.path === owner.source)) {
1328
1861
  try {
1329
1862
  const loaded = await sourceFor({ path: owner.source, version: manifest?.revision ?? 0 }, effectiveTheme);
@@ -1339,6 +1872,7 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1339
1872
  label: 'Show usages',
1340
1873
  action: () => {
1341
1874
  inspector = true;
1875
+ commentUI?.closePanel?.();
1342
1876
  selection();
1343
1877
  $('#used-by-heading')?.scrollIntoView({ block: 'nearest' });
1344
1878
  ($('#used-by button') ?? $('#copy-path'))?.focus({ preventScroll: true });
@@ -1348,41 +1882,31 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1348
1882
  return;
1349
1883
  }
1350
1884
  if (a && p) {
1351
- const fb = frameBox(a, p);
1352
- const fx = worldPoint ? Math.max(0, Math.min(1, (worldPoint.x - fb.x) / fb.width)) : 0.5;
1353
- const fy = worldPoint ? Math.max(0, Math.min(1, (worldPoint.y - fb.y) / fb.height)) : 0.5;
1354
1885
  contextMenu.open([
1355
- {
1356
- label: 'Annotate frame',
1357
- action: () => annotationUI.annotateAt({ source: a.path, frame: p.name, fx, fy, element: null, returnFocus }),
1358
- },
1886
+ ...comment,
1359
1887
  { label: 'Copy frame name', action: () => copyToClipboard(p.name) },
1360
1888
  { label: 'Copy source path', action: () => copyToClipboard(a.path) },
1361
1889
  {
1362
1890
  label: 'Show in Inspector',
1363
1891
  action: () => {
1364
1892
  inspector = true;
1893
+ commentUI?.closePanel?.();
1365
1894
  selection();
1366
1895
  $('#copy-frame')?.focus({ preventScroll: true });
1367
1896
  },
1368
1897
  },
1369
1898
  { label: 'Fit frame', action: () => frame(frameBox(a, p), 24) },
1370
- {
1371
- label: 'Copy open annotations as agent prompt',
1372
- disabled: annotationUI.countOpenForFrame(a.path, p.name) === 0,
1373
- action: () => annotationUI.copyOpenForFrame(a.path, p.name),
1374
- },
1375
1899
  ], { x: screenX, y: screenY, returnFocus });
1376
1900
  return;
1377
1901
  }
1378
1902
  contextMenu.open([
1903
+ ...comment,
1379
1904
  { label: 'Fit all', action: () => fit() },
1380
1905
  { label: 'Arrange current group', action: () => $('#arrange').click() },
1381
1906
  ], { x: screenX, y: screenY, returnFocus });
1382
1907
  }
1383
1908
  viewport.addEventListener('contextmenu', e => {
1384
- if (reviewManifest || tokenManifest || !manifest?.directory) return;
1385
- if (e.target.closest('.annotation-point, .annotation-card')) return;
1909
+ if (tokenManifest || !manifest?.directory) return;
1386
1910
  e.preventDefault();
1387
1911
  viewport.focus({ preventScroll: true });
1388
1912
  const rect = viewport.getBoundingClientRect();
@@ -1392,22 +1916,13 @@ viewport.addEventListener('contextmenu', e => {
1392
1916
  if (hit?.part) selectFrame(hit.asset, hit.part, hit.element);
1393
1917
  else if (hit) selectSource(hit.asset);
1394
1918
  else clearSelection();
1395
- openSelectionContextMenu({ worldPoint: { x: wx, y: wy }, screenX: e.clientX, screenY: e.clientY, returnFocus: viewport });
1919
+ openSelectionContextMenu({ worldPoint: { x: wx, y: wy }, screenX: e.clientX, screenY: e.clientY, deepest: e.altKey, returnFocus: viewport });
1396
1920
  });
1397
1921
  document.addEventListener('keydown', e => {
1398
1922
  if (!(e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) return;
1399
- if (reviewManifest || tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1923
+ if (frameFilter !== 'all' || tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1400
1924
  e.preventDefault();
1401
1925
  const activeEl = document.activeElement;
1402
- const noteEl = activeEl?.closest?.('[data-annotation-id]');
1403
- if (noteEl) {
1404
- const row = annotationUI.getRow(noteEl.dataset.annotationId);
1405
- if (row) {
1406
- const r = noteEl.getBoundingClientRect();
1407
- annotationUI.openNoteMenu(row, { x: r.left + r.width / 2, y: r.top + r.height / 2, returnFocus: activeEl });
1408
- return;
1409
- }
1410
- }
1411
1926
  const box = selectedBox();
1412
1927
  const vr = viewport.getBoundingClientRect();
1413
1928
  const sx = box ? vr.left + view.x + (box.x + box.width / 2) * view.scale : vr.left + width / 2;
@@ -1415,16 +1930,30 @@ document.addEventListener('keydown', e => {
1415
1930
  openSelectionContextMenu({ worldPoint: null, screenX: sx, screenY: sy, returnFocus: activeEl instanceof HTMLElement ? activeEl : viewport });
1416
1931
  });
1417
1932
  document.addEventListener("keydown", (e) => {
1418
- if (e.metaKey || e.ctrlKey || e.altKey || e.target.matches("input,textarea,[contenteditable]") || document.querySelector("dialog[open], :popover-open")) return;
1933
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey ||
1934
+ (tokenManifest && tokenList) ||
1935
+ e.target.matches("input,textarea,select,[contenteditable]") ||
1936
+ document.querySelector("dialog[open], :popover-open")) return;
1937
+ if (frameFilter !== 'all') return;
1938
+ if (!tokenManifest && !e.repeat && e.key.toLowerCase() === 'p') {
1939
+ const item = currentItem(), part = item?.parts.find(p => p.id === selectedForm);
1940
+ if (playableFrames.get(item?.path)?.has(part?.name)) {
1941
+ e.preventDefault();
1942
+ void startFramePlayer(item.path, part.name, document.activeElement);
1943
+ }
1944
+ return;
1945
+ }
1946
+ const inPanel = !!e.target.closest('#sidebar, #source, #comments-panel, #scope-tabs, #token-catalog');
1419
1947
  const v = view;
1420
- if (e.key === "+" || e.key === "=") zoom(v.scale * 1.25);
1948
+ if (e.key === "Enter") {
1949
+ if (tokenManifest || inPanel || e.target.closest('button,a,[role="button"]')) return;
1950
+ const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);if(p) inspectForm(a,p);else focusAsset(a);
1951
+ }
1952
+ else if (inPanel) return;
1953
+ else if (e.key === "+" || e.key === "=") zoom(v.scale * 1.25);
1421
1954
  else if (e.key === "-") zoom(v.scale / 1.25);
1422
1955
  else if (e.key === "0") fit();
1423
1956
  else if (e.key === "Escape") return;
1424
- else if (e.key === "Enter") {
1425
- if (e.target.closest('button,a,[role="button"]')) return;
1426
- const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);if(p) inspectForm(a,p);else focusAsset(a);
1427
- }
1428
1957
  else if (e.key === "1") zoom(1);
1429
1958
  else if (e.key.startsWith("Arrow"))
1430
1959
  commit({
@@ -1435,10 +1964,14 @@ document.addEventListener("keydown", (e) => {
1435
1964
  else return;
1436
1965
  e.preventDefault();
1437
1966
  });
1438
- viewport.addEventListener("dblclick", () => {
1439
- const a = currentItem();
1440
- const p=a?.parts.find(p=>p.id===selectedForm);
1441
- if (p) inspectForm(a,p); else if(a) focusAsset(a);
1967
+ viewport.addEventListener("dblclick", event => {
1968
+ if (commentUI.active()) return;
1969
+ const rect = viewport.getBoundingClientRect();
1970
+ const x = (event.clientX - rect.left - view.x) / view.scale;
1971
+ const y = (event.clientY - rect.top - view.y) / view.scale;
1972
+ const hit = hitSelection(inspection ? [inspection] : assets, x, y);
1973
+ if (hit?.part) inspectForm(hit.asset, hit.part);
1974
+ else if (hit) focusAsset(hit.asset);
1442
1975
  });
1443
1976
  for (const [id, action] of Object.entries({
1444
1977
  "zoom-fit-all": fit,
@@ -1452,14 +1985,21 @@ for (const [id, action] of Object.entries({
1452
1985
  action();
1453
1986
  };
1454
1987
  $("#back").onclick = back;
1455
- $('#sidebar-toggle').onclick = () => toggleSidebar();
1988
+ $("#scope-isolation").onclick = () => exitIsolation(true);
1989
+ $("#token-view-toggle").onclick = () => setTokenList(!tokenList);
1990
+ $("#token-board-button").onclick = () => setTokenList(false);
1991
+ $('#sidebar-toggle').onclick = () => {
1992
+ if(frameFilter!=='all' && !tokenManifest){setFrameFilter('all');toggleSidebar(true);$('#sidebar-toggle').focus();}
1993
+ else toggleSidebar();
1994
+ };
1456
1995
  $('#inspect').onclick = () => {
1457
1996
  inspector = !inspector;
1997
+ if (inspector) commentUI?.closePanel?.();
1458
1998
  updateChrome();
1459
1999
  requestDraw(true, false);
1460
2000
  };
1461
- $('#copy-path').onclick=()=>navigator.clipboard.writeText($('#source-path').textContent).catch(e=>error(e.message));
1462
- $('#copy-frame').onclick=()=>navigator.clipboard.writeText($('#frame-name').textContent).catch(e=>error(e.message));
2001
+ $('#copy-path').onclick=()=>navigator.clipboard.writeText($('#source-path').textContent).then(()=>flashCopied($('#copy-path')),e=>error(e.message));
2002
+ $('#copy-frame').onclick=()=>navigator.clipboard.writeText($('#frame-name').textContent).then(()=>flashCopied($('#copy-frame')),e=>error(e.message));
1463
2003
  $("#fullscreen").onclick = () => {
1464
2004
  $("#more-menu").hidePopover();
1465
2005
  const p = document.fullscreenElement
@@ -1477,59 +2017,69 @@ $("#map-toggle").onclick = () => {
1477
2017
  $("#map-toggle").setAttribute("aria-pressed", String(!$("#minimap").hidden));
1478
2018
  requestDraw();
1479
2019
  };
1480
- $("#minimap").onclick = e => {
1481
- const {scale:s,x,y}=mapGeometry(),r=e.target.getBoundingClientRect(),area=cameraArea();
1482
- remember();inspection=null;selection();
2020
+ let minimapDragging = false;
2021
+ function scrubMinimap(e) {
2022
+ const map = $("#minimap");
2023
+ const {scale:s,x,y}=mapGeometry(),r=map.getBoundingClientRect(),area=cameraArea();
1483
2024
  commit({...view,x:area.x+area.width/2-(e.clientX-r.left-x)/s*view.scale,y:area.y+area.height/2-(e.clientY-r.top-y)/s*view.scale});
1484
- };
2025
+ }
2026
+ $("#minimap").addEventListener("pointerdown", e => {
2027
+ if (e.button !== 0) return;
2028
+ e.preventDefault();
2029
+ minimapDragging = true;
2030
+ $("#minimap").setPointerCapture(e.pointerId);
2031
+ if (!tokenManifest) {
2032
+ remember();
2033
+ inspection = null;
2034
+ selection();
2035
+ }
2036
+ scrubMinimap(e);
2037
+ });
2038
+ $("#minimap").addEventListener("pointermove", e => {
2039
+ if (!minimapDragging) return;
2040
+ scrubMinimap(e);
2041
+ });
2042
+ for (const event of ["pointerup", "pointercancel", "lostpointercapture"]) {
2043
+ $("#minimap").addEventListener(event, e => {
2044
+ if (!minimapDragging) return;
2045
+ minimapDragging = false;
2046
+ if ($("#minimap").hasPointerCapture(e.pointerId)) $("#minimap").releasePointerCapture(e.pointerId);
2047
+ requestDraw();
2048
+ });
2049
+ }
1485
2050
  $("#shortcuts").onclick = () => {
1486
2051
  $("#more-menu").hidePopover();
1487
2052
  $("#keys").showModal();
1488
2053
  };
1489
2054
  $("#arrange").onclick = async () => {
1490
2055
  const data=manifest,previousCatalog=catalog;
2056
+ if (!data) return;
1491
2057
  window.__adg.ready=false;
1492
2058
  let placed;
1493
2059
  try {if(!data.loading)placed=await arranger.arrange(layoutData(data));}
1494
2060
  catch(failure){if(failure.name!=='AbortError')error(failure.message);requestDraw();return;}
1495
- if(manifest!==data || catalog!==previousCatalog || tokenManifest || reviewManifest){requestDraw();return;}
1496
- const old = assets,
1497
- oldGroups = groups;
2061
+ if(manifest!==data || catalog!==previousCatalog || tokenManifest){requestDraw();return;}
1498
2062
  layout(manifest,false,{placed,provisional:!!data.loading});
1499
- if (active !== null) {
1500
- const g = groups[active],
1501
- prev = oldGroups[active],
1502
- dx = prev.x - g.x,
1503
- dy = prev.y - g.y;
1504
- for (const a of assets) {
1505
- if (a.group === active) {
1506
- a.x += dx;
1507
- a.y += dy;
1508
- } else {
1509
- const before = old.find((b) => b.id === a.id);
1510
- if (before)
1511
- Object.assign(a, {
1512
- x: before.x,
1513
- y: before.y,
1514
- width: before.width,
1515
- height: before.height,
1516
- });
1517
- }
1518
- }
1519
- groups = groups.map((g, i) =>
1520
- i === active ? { ...g, x: prev.x, y: prev.y } : oldGroups[i],
1521
- );
1522
- }
1523
- world.width = Math.max(1, ...groups.map((g) => g.x + g.width));
1524
- world.height = Math.max(1, ...groups.map((g) => g.y + g.height));
1525
2063
  $("#more-menu").hidePopover();
1526
2064
  selection();
1527
2065
  };
1528
2066
  $("#search").oninput = () => {
2067
+ const hasQuery = !!$("#search").value.trim();
1529
2068
  if (tokenManifest) {
2069
+ if (hasQuery && !tokenList) {
2070
+ tokenSearchWasBoard = true;
2071
+ tokenList = true;
2072
+ updateChrome();
2073
+ requestDraw();
2074
+ } else if (!hasQuery && tokenSearchWasBoard) {
2075
+ tokenList = false;
2076
+ tokenSearchWasBoard = false;
2077
+ updateChrome();
2078
+ requestDraw();
2079
+ }
1530
2080
  $('.token-scroll').scrollTop = 0;
1531
- } else if ($("#search").value.trim()) {
1532
- searchReturn ??= { view: { ...view }, sidebar, active, selected, selectedId, selectedForm, selectedElement, inspection };
2081
+ } else if (hasQuery) {
2082
+ searchReturn ??= { scope: initializedScope, view: { ...view }, sidebar, active, selected, selectedId, selectedForm, selectedElement, inspection };
1533
2083
  toggleSidebar(true);
1534
2084
  } else if (searchReturn) {
1535
2085
  toggleSidebar(searchReturn.sidebar);
@@ -1538,10 +2088,43 @@ $("#search").oninput = () => {
1538
2088
  renderNav();
1539
2089
  };
1540
2090
  $("#search-clear").onclick=()=>{$("#search").value="";$("#search").oninput();$("#search").focus()};
2091
+ function moduleRows() {
2092
+ if ($("#sidebar").hidden) return [];
2093
+ return [...$("#modules").querySelectorAll("button:is(.tree-row, .group-name):not(:disabled)")].filter(el => el.offsetParent !== null);
2094
+ }
1541
2095
  $("#search").onkeydown = (e) => {
1542
- if (e.key === "Enter")
2096
+ if (e.key === "Enter") {
1543
2097
  $("#modules .search-result")?.click();
2098
+ return;
2099
+ }
2100
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
2101
+ const rows = moduleRows();
2102
+ if (!rows.length) return;
2103
+ e.preventDefault();
2104
+ e.stopPropagation();
2105
+ (e.key === "ArrowDown" ? rows[0] : rows.at(-1)).focus();
2106
+ }
1544
2107
  };
2108
+ $("#modules").addEventListener("keydown", (e) => {
2109
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
2110
+ const rows = moduleRows();
2111
+ if (!rows.length) return;
2112
+ const current = e.target.closest(".scope-row, .group-row")?.querySelector("button:is(.tree-row, .group-name)") ?? e.target;
2113
+ const index = rows.indexOf(current);
2114
+ if (index < 0) return;
2115
+ e.preventDefault();
2116
+ e.stopPropagation();
2117
+ if (e.key === "ArrowDown") {
2118
+ if (index + 1 < rows.length) rows[index + 1].focus();
2119
+ else if (!$(".search-field").hidden) $("#search").focus();
2120
+ } else if (index > 0) {
2121
+ rows[index - 1].focus();
2122
+ } else if (!$(".search-field").hidden) {
2123
+ $("#search").focus();
2124
+ } else {
2125
+ rows.at(-1).focus();
2126
+ }
2127
+ });
1545
2128
  $("#minus").onclick = () => zoom(view.scale / 1.25);
1546
2129
  $("#plus").onclick = () => zoom(view.scale * 1.25);
1547
2130
  function resizeViewport() {
@@ -1569,10 +2152,35 @@ function relationshipGraph(data, measured) {
1569
2152
  return sourceRelationships([...entries].map(([path,imports])=>({path,imports})));
1570
2153
  }
1571
2154
  function applyTokenManifest(data) {
1572
- const previous = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
2155
+ const previous = tokenManifest ?? catalog ?? manifest;
1573
2156
  const entering = !tokenManifest || tokenManifest.directory !== data.directory;
1574
2157
  tokenManifest = { ...data, tokenGroups: groupTokens(data.tokens ?? []) };
1575
- reviewManifest = null;
2158
+ if (entering) {
2159
+ tokenList = false;
2160
+ tokenSearchWasBoard = false;
2161
+ }
2162
+ if (!data.tokenBoard) {
2163
+ tokenList = true;
2164
+ tokenSearchWasBoard = false;
2165
+ tokenHeight = 0;
2166
+ }
2167
+ canvas.width = canvas.width;
2168
+ boardLayer.update([], [], data);
2169
+ boardLayer.camera(view, false);
2170
+ let firstMeasurement = true;
2171
+ boardLayer.tokens(data.tokenBoard, boardHeight => {
2172
+ tokenHeight=boardHeight;
2173
+ world={x:0,y:0,width:data.tokenBoard.width,height:boardHeight};
2174
+ if (entering && firstMeasurement) {
2175
+ const query = new URLSearchParams(location.search);
2176
+ const section = data.fixture?.section ?? (query.has('pattern') ? 'motion' : query.get('section'));
2177
+ const box = section === 'motion' && boardLayer.tokenSection(section);
2178
+ if (box) commit(fitView({ ...box, height: Math.min(box.height, 650) }, fitArea(width, height, sidebar, false), 24));
2179
+ else frame(world);
2180
+ }
2181
+ firstMeasurement = false;
2182
+ requestDraw();
2183
+ });
1576
2184
  scopeRequest = data.scope;
1577
2185
  catalog = null;
1578
2186
  if (entering) {
@@ -1594,29 +2202,7 @@ function applyTokenManifest(data) {
1594
2202
  if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
1595
2203
  }
1596
2204
  updateChrome();
1597
- annotationUI.render();
1598
- renderNav();
1599
- }
1600
- function applyReviewManifest(data) {
1601
- const previous = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
1602
- reviewManifest = data;
1603
- tokenManifest = null;
1604
- catalog = null;
1605
- scopeRequest = 'review';
1606
- fixtureState = null;
1607
- if (previous?.directory !== data.directory) {
1608
- theme = data.theme;
1609
- sidebar = false;
1610
- applyTheme();
1611
- }
1612
- for (const element of document.querySelectorAll('.directory-name')) element.textContent = data.label;
1613
- $('#app-directory').title = data.directory || '';
1614
- document.title = `${data.label} · Review — Agent Design Gallery`;
1615
- const url = viewURL(location.href, 'review');
1616
- if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
1617
- renderReview($('#review-page'), data.review);
1618
- updateChrome();
1619
- annotationUI.render();
2205
+ commentUI.render();
1620
2206
  renderNav();
1621
2207
  requestDraw();
1622
2208
  }
@@ -1625,7 +2211,7 @@ async function applyManifest(data, force = false) {
1625
2211
  if (force || tokenManifest?.directory !== data.directory || tokenManifest?.revision !== data.revision) applyTokenManifest(data);
1626
2212
  return;
1627
2213
  }
1628
- const leavingOverlayView = !!tokenManifest || !!reviewManifest;
2214
+ const leavingOverlayView = !!tokenManifest;
1629
2215
  const changedRoot = initializedDirectory !== data.directory, changedScope = initializedScope !== data.scope || initializedFrame !== onlyFrame;
1630
2216
  const first = changedRoot || changedScope;
1631
2217
  if (!force && !first && !leavingOverlayView && manifest.revision === data.revision)
@@ -1636,12 +2222,28 @@ async function applyManifest(data, force = false) {
1636
2222
  }
1637
2223
  if (changedRoot) {
1638
2224
  fixtureState=data.fixture ?? null;
1639
- theme = data.theme;
1640
- applyTheme();
2225
+ if (!derivedLanding || catalog?.directory !== data.directory) {
2226
+ theme = data.theme;
2227
+ applyTheme();
2228
+ }
1641
2229
  if (!leavingOverlayView) sidebar = !!fixtureState?.sidebar;
1642
2230
  inspector = !!fixtureState && data.inspector;
1643
2231
  history = [];
1644
2232
  }
2233
+ if (first && !fixtureState && frameFilter !== 'all' && !initializedDirectory && data.directory) {
2234
+ catalog = manifest = data;
2235
+ derivedLanding = true;
2236
+ scopeRequest = data.scope;
2237
+ setMotionProjection(data.motionFrames);
2238
+ for (const element of document.querySelectorAll('.directory-name')) element.textContent = data.label;
2239
+ $('#app-directory').title = data.directory;
2240
+ document.title = `${data.label} — Agent Design Gallery`;
2241
+ updateChrome();
2242
+ renderScopeTabs(data);
2243
+ if (frameFilter !== 'recent' || !openRecentHistory(data)) renderFrameView();
2244
+ requestDraw();
2245
+ return;
2246
+ }
1645
2247
  if (first) {
1646
2248
  if (catalog?.directory !== data.directory || catalog?.scope !== data.scope) {
1647
2249
  expanded.clear();
@@ -1657,7 +2259,6 @@ async function applyManifest(data, force = false) {
1657
2259
  window.__adg.ready = false;
1658
2260
  if (first) {
1659
2261
  cache.clear();
1660
- labelLayer.clear();
1661
2262
  queued = [];
1662
2263
  selected = null;
1663
2264
  selectedId = null;
@@ -1669,21 +2270,65 @@ async function applyManifest(data, force = false) {
1669
2270
  }
1670
2271
  const versionTheme = effectiveTheme;
1671
2272
  const link = initializedDirectory === undefined && !fixtureState ? initialLink : null;
1672
- const entry = !changedRoot && scopeRequest===data.scope ? scopeEntry : null;
2273
+ const entry = (!changedRoot || leavingOverlayView) && scopeRequest===data.scope ? scopeEntry : null;
1673
2274
  const groupTitle = groups[active]?.title;
1674
- restorePacking(data.packing);
2275
+
1675
2276
  const previous=manifest, results=new Array(data.assets.length), signal=refreshController?.signal;
1676
2277
  let next=0,publishFrame=0,streamView=null,streamMoved=false,publishedCount=0,nextPublish=1;
1677
2278
  const streaming=first && !leavingOverlayView;
2279
+ let cachedPlacement;
2280
+ const order = data.assets.map((_, i) => i);
2281
+ if (streaming && data.view && data.metadataTheme === versionTheme &&
2282
+ data.assets.length && data.assets.every(a => a.layout)) {
2283
+ // The cached frame bounds determine placement without loading the much larger hit maps.
2284
+ const outlines = data.assets.map(a => decorateMetadata(a, a.layout));
2285
+ if (data.scope === 'all' && data.tokenBoard && !tokenHeight)
2286
+ boardLayer.tokens(data.tokenBoard, height => { tokenHeight = height; });
2287
+ const panel = layoutData({...data,assets:outlines});
2288
+ cachedPlacement = await arranger.arrange(panel, {signal});
2289
+ const priority = new Map();
2290
+ const camera = entry?.view ?? data.view;
2291
+ const items = arrange(panel, {placed:cachedPlacement}).items;
2292
+ const offset = data.scope === 'all' && data.tokenBoard && tokenHeight ? tokenHeight + 480 : 0;
2293
+ const candidates = [];
2294
+ for (const item of items) {
2295
+ const x = camera.x + item.x * camera.scale, y = camera.y + (item.y + offset) * camera.scale;
2296
+ const w = item.width * camera.scale, h = item.height * camera.scale;
2297
+ const distance = Math.hypot(x + w / 2 - width / 2, y + h / 2 - height / 2);
2298
+ priority.set(item.path, Math.min(priority.get(item.path) ?? Infinity, distance));
2299
+ if (x < width && x+w > 0 && y < height && y+h > 0) candidates.push({item,distance});
2300
+ }
2301
+ // Start the actual cached images while their interaction metadata is in flight.
2302
+ // Reuse the same bounded queue when the corresponding specimens are published.
2303
+ const primed = new Set();
2304
+ for (const {item} of candidates.sort((a,b) => a.distance-b.distance)) {
2305
+ const crop = item.previewCrop ?? item.shown[0];
2306
+ const key = assetURL(item,crop);
2307
+ if (primed.has(key) || !item.previewIds?.[versionTheme]?.includes(crop.id)) continue;
2308
+ ensureImage(item,crop).visiblePriority = true;
2309
+ primed.add(key);
2310
+ if (primed.size === 3) break;
2311
+ }
2312
+ pump();
2313
+ order.sort((a,b) => priority.get(data.assets[a].path) - priority.get(data.assets[b].path));
2314
+ }
2315
+ let lastPublish = -Infinity;
1678
2316
  const publish=()=>{
1679
2317
  publishFrame=0;
1680
2318
  if(signal?.aborted||versionTheme!==effectiveTheme)return;
1681
2319
  const available=results.filter(Boolean);
1682
2320
  if(!available.length)return;
2321
+ lastPublish = performance.now();
1683
2322
  publishedCount=available.length;nextPublish=Math.max(publishedCount+1,publishedCount*2);
1684
2323
  if(streamView&&view!==streamView)streamMoved=true;
1685
2324
  manifest={...data,assets:available,renderTheme:versionTheme,loading:true};
1686
- layout(manifest,false,{provisional:true});
2325
+ let placed;
2326
+ if (cachedPlacement) {
2327
+ const paths = new Set(available.map(a => a.path));
2328
+ placed = cachedPlacement.map(board => ({...board, blocks:board.blocks.filter(b => paths.has(b.asset))}))
2329
+ .filter(board => board.blocks.length);
2330
+ }
2331
+ layout(manifest,false,{provisional:true,placed});
1687
2332
  if(streaming&&!streamMoved){view=entry?.view??data.view??fitWorld(cameraArea(),data);streamView=view;}
1688
2333
  requestDraw();
1689
2334
  };
@@ -1694,19 +2339,32 @@ async function applyManifest(data, force = false) {
1694
2339
  }
1695
2340
  let completed=results.filter(Boolean).length;
1696
2341
  if(streaming&&completed&&completed<data.assets.length)publish();
2342
+ // Let the server build the next sources while the browser measures this batch.
2343
+ const prefetched = new Map();
2344
+ let fetchIndex = 0;
2345
+ function prefetch() {
2346
+ while (fetchIndex < data.assets.length && prefetched.size < 4) {
2347
+ const i = order[fetchIndex++], asset = data.assets[i];
2348
+ if (results[i]) continue;
2349
+ const source = asset.metadataRefs?.[versionTheme]
2350
+ ? readSourceMetadata(asset, versionTheme, signal)
2351
+ : fetchSource(asset, versionTheme, signal);
2352
+ source.catch(() => {}); // A superseded refresh can abandon this lookahead.
2353
+ prefetched.set(i, source);
2354
+ }
2355
+ }
2356
+ prefetch();
1697
2357
  await Promise.all(Array.from({length:4},async()=>{
1698
2358
  while(next<data.assets.length) {
1699
2359
  signal?.throwIfAborted();
1700
- const i=next++,a=data.assets[i];
2360
+ const i=order[next++],a=data.assets[i];
1701
2361
  if(results[i])continue;
1702
- let entry;
1703
- if(a.hash&&a.metadataRefs?.[versionTheme]) {
1704
- const query=new URLSearchParams({theme:versionTheme,context:metadataContext()});
1705
- const response=await dataFetch(`metadata/${a.hash}?${query}`,{signal});
1706
- if(response.ok){const saved=await response.json();entry=decorateMetadata({...a,previewIds:{...a.previewIds,[versionTheme]:saved.previewIds}},saved.metadata);}
1707
- }
2362
+ const source = prefetched.get(i);
2363
+ prefetched.delete(i);
2364
+ prefetch();
2365
+ let entry = a.metadataRefs?.[versionTheme] ? await source : null;
1708
2366
  if(!entry) {
1709
- entry=await prepare(a,versionTheme,{signal});
2367
+ entry=await prepare(a,versionTheme,{signal,source:a.metadataRefs?.[versionTheme] ? undefined : source});
1710
2368
  if (a.onlyFrame && !entry.parts.some(part => part.name === a.onlyFrame)) throw Error(`Frame ${a.onlyFrame} does not exist in ${a.path}.`);
1711
2369
  Object.assign(a,{hash:entry.hash,version:entry.version});
1712
2370
  persistSource(entry,versionTheme);
@@ -1715,16 +2373,14 @@ async function applyManifest(data, force = false) {
1715
2373
  const metadata=measuredMetadata(entry);
1716
2374
  metadataCache.set(sourceKey(entry,versionTheme,data.directory),metadata);
1717
2375
  results[i]=decorateMetadata(a,metadata);completed++;
1718
- if(streaming&&completed>=nextPublish&&!publishFrame)publishFrame=requestAnimationFrame(publish);
2376
+ if(streaming&&completed>=nextPublish&&!publishFrame&&performance.now()-lastPublish>=100)publishFrame=requestAnimationFrame(publish);
1719
2377
  }
1720
2378
  }));
1721
2379
  if(publishFrame)cancelAnimationFrame(publishFrame);
1722
2380
  if(versionTheme!==effectiveTheme){pending=true;return;}
1723
2381
  signal?.throwIfAborted();
1724
2382
  const complete={...data,assets:results};
1725
- const placed=await arranger.arrange(layoutData(complete),{signal,onPending:()=>{
1726
- if(streaming&&completed>publishedCount)publish();
1727
- }});
2383
+ const placed=await arranger.arrange(layoutData(complete),{signal});
1728
2384
  if(versionTheme!==effectiveTheme){pending=true;return;}
1729
2385
  signal?.throwIfAborted();
1730
2386
  if(streamView&&view!==streamView)streamMoved=true;
@@ -1733,11 +2389,11 @@ async function applyManifest(data, force = false) {
1733
2389
  for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
1734
2390
  manifest = { ...data, assets: results, relationships:relationshipGraph(data,results), renderTheme: versionTheme };
1735
2391
  tokenManifest = null;
1736
- reviewManifest = null;
1737
2392
  // Early streamed worlds can use a much larger camera scale. Discard those
1738
2393
  // raster intermediates so the completed world starts at its exact final scale.
1739
2394
  if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
1740
2395
  catalog = null;
2396
+ derivedLanding = false;
1741
2397
  layout(
1742
2398
  manifest,
1743
2399
  !first && !!previous &&
@@ -1747,20 +2403,23 @@ async function applyManifest(data, force = false) {
1747
2403
  for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
1748
2404
  $("#app-directory").title=data.directory||'';
1749
2405
  document.title = `${data.label} — Agent Design Gallery`;
1750
- if (first) {
2406
+ if (first || leavingOverlayView) {
1751
2407
  const target = entry ? entry.target : link ?? data.selection;
1752
- if (!fixtureState) restoreSelection(target);
2408
+ if (!fixtureState && !(streaming && (selected || active !== null))) restoreSelection(target);
1753
2409
  const saved = data.selection;
1754
2410
  const sameSelection = link && saved && (link.path
1755
2411
  ? link.path === saved.path && link.form === saved.form && link.element?.id === saved.element?.id
1756
2412
  : !saved.path && link.group === saved.group);
1757
2413
  const reload = performance.getEntriesByType('navigation')[0]?.type === 'reload';
1758
- if (entry?.view) view=entry.view;
2414
+ if (entry?.view && !streamMoved) view=entry.view;
1759
2415
  else if (entry?.target || (link && (onlyFrame || !(reload && sameSelection && data.view)))) {
1760
2416
  const target = selectedBox() || currentItem() || groups[active] || world;
1761
2417
  frame(target, selected ? 24 : 0);
1762
- } else if (data.view) view = data.view;
1763
- else if (!streamMoved) frame(world);
2418
+ } else if (leavingOverlayView && previous?.directory === data.directory && previous.scope === data.scope && previous.view) view = previous.view;
2419
+ else if (!streamMoved) {
2420
+ if (data.view) view = data.view;
2421
+ else frame(world);
2422
+ }
1764
2423
  } else if (groupTitle) {
1765
2424
  const index = groups.findIndex(group=>group.title===groupTitle);
1766
2425
  active = index < 0 ? null : index;
@@ -1789,13 +2448,21 @@ async function applyManifest(data, force = false) {
1789
2448
  initializedFrame=onlyFrame;
1790
2449
  initialLink=null;
1791
2450
  scopeEntry=null;
1792
- if(data.features?.persistedMetadata && !onlyFrame)cacheWrite(`catalog?context=${encodeURIComponent(metadataContext())}`,{packing:packingSnapshot()});
1793
2451
  selection();
2452
+ if (frameFilter === 'recent') openRecentHistory(data);
1794
2453
  if (pendingNavigation) {
1795
2454
  const action = pendingNavigation;
1796
2455
  pendingNavigation = null;
1797
2456
  action();
1798
2457
  }
2458
+ if (commentNavigation && (data.scope === commentNavigation.scope || !data.loading)) {
2459
+ const found = focusBoardComment(commentNavigation.thread);
2460
+ if (found || !data.loading) {
2461
+ commentNavigation.resolve(found);
2462
+ commentNavigation = null;
2463
+ }
2464
+ }
2465
+ commentUI.render();
1799
2466
  requestDraw();
1800
2467
  }
1801
2468
  function updateChoices() {
@@ -1806,15 +2473,47 @@ function updateChoices() {
1806
2473
  }
1807
2474
  }
1808
2475
  for(const button of $("#backgrounds").children) button.onclick=()=>{backgroundChoice=button.dataset.background;updateChoices();requestDraw()};
2476
+ function menuItems(menu) {
2477
+ return [...menu.querySelectorAll('button:not(:disabled)')].filter(el => !el.hidden && el.offsetParent !== null);
2478
+ }
1809
2479
  for(const [id,trigger] of [['zoom-menu','zoom-options'],['more-menu','more']]) {
1810
- $("#"+id).addEventListener('toggle',event=>{
1811
- $("#"+trigger).setAttribute(id === "more-menu" ? "aria-expanded" : "aria-pressed", String(event.newState === "open"));
2480
+ const menu = $("#"+id), btn = $("#"+trigger);
2481
+ menu.addEventListener('toggle',event=>{
2482
+ btn.setAttribute(id === "more-menu" ? "aria-expanded" : "aria-pressed", String(event.newState === "open"));
1812
2483
  if(event.newState==='open') {
1813
2484
  for(const other of document.querySelectorAll(':popover-open')) if(other.id!==id) other.hidePopover();
1814
2485
  hideTooltip();positionZoomMenu();
1815
2486
  }
1816
2487
  requestDraw();
1817
2488
  });
2489
+ menu.addEventListener('keydown', event => {
2490
+ const items = menuItems(menu);
2491
+ if (!items.length) return;
2492
+ const index = items.indexOf(document.activeElement);
2493
+ const next = event.key === 'ArrowDown' ? items[index < 0 ? 0 : (index + 1) % items.length]
2494
+ : event.key === 'ArrowUp' ? items[index <= 0 ? items.length - 1 : index - 1]
2495
+ : event.key === 'Home' ? items[0]
2496
+ : event.key === 'End' ? items.at(-1)
2497
+ : null;
2498
+ if (!next) return;
2499
+ event.preventDefault();
2500
+ event.stopPropagation();
2501
+ next.focus();
2502
+ });
2503
+ btn.addEventListener('keydown', event => {
2504
+ if (!menu.matches(':popover-open')) return;
2505
+ const items = menuItems(menu);
2506
+ if (!items.length) return;
2507
+ if (event.key === 'ArrowDown' || event.key === 'Home') {
2508
+ event.preventDefault();
2509
+ event.stopPropagation();
2510
+ items[0].focus();
2511
+ } else if (event.key === 'ArrowUp' || event.key === 'End') {
2512
+ event.preventDefault();
2513
+ event.stopPropagation();
2514
+ items.at(-1).focus();
2515
+ }
2516
+ });
1818
2517
  }
1819
2518
  let tooltipTimer;
1820
2519
  function hideTooltip() { clearTimeout(tooltipTimer);if (!$("#tooltip").hidden) { $("#tooltip").hidden=true;requestDraw(); } }
@@ -1833,12 +2532,29 @@ function bindTooltip(button, trailing = false) {
1833
2532
  }
1834
2533
  for(const button of document.querySelectorAll('[data-tooltip]')) bindTooltip(button);
1835
2534
  $("#keys-close").onclick=()=>$("#keys").close();
2535
+ $("#keys").addEventListener('click', event => {
2536
+ if (event.target !== $("#keys")) return;
2537
+ const r = $("#keys").getBoundingClientRect();
2538
+ if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) {
2539
+ $("#keys").close();
2540
+ }
2541
+ });
1836
2542
  for(const dialog of document.querySelectorAll('dialog')) {
1837
2543
  dialog.addEventListener('toggle', () => requestDraw());
1838
2544
  dialog.addEventListener('close',()=>{viewport.focus({preventScroll:true});requestDraw()});
1839
2545
  }
1840
2546
  document.addEventListener('keydown',event=>{
1841
- if(event.key==='?'&&!event.target.matches('input,textarea')&&!document.querySelector('dialog[open]')) {event.preventDefault();hideTooltip();$("#keys").showModal()}
2547
+ if (event.key !== '?' || event.metaKey || event.ctrlKey || event.altKey || event.target.matches('input,textarea,select,[contenteditable]')) return;
2548
+ if ($("#keys").open) {
2549
+ event.preventDefault();
2550
+ $("#keys").close();
2551
+ return;
2552
+ }
2553
+ if (!document.querySelector('dialog[open]')) {
2554
+ event.preventDefault();
2555
+ hideTooltip();
2556
+ $("#keys").showModal();
2557
+ }
1842
2558
  });
1843
2559
  async function applyFixture() {
1844
2560
  const state=fixtureState;if(!state)return;
@@ -1877,19 +2593,12 @@ async function refresh(force = false) {
1877
2593
  fetching = true;refreshController=new AbortController();
1878
2594
  try {
1879
2595
  if (routeError) throw routeError;
1880
- if (scopeRequest === 'review') {
1881
- window.__adg.ready = false;
1882
- const signal = refreshController.signal, data = await api('review', null, false, signal);
1883
- signal.throwIfAborted();
1884
- applyReviewManifest(data);
1885
- error("");
1886
- return;
1887
- }
1888
2596
  const query=new URLSearchParams({context:metadataContext(),theme:effectiveTheme,scope:scopeRequest});
1889
2597
  if (strictRoute) query.set('strict', '1');
1890
2598
  if (onlyFrame) query.set('frame', onlyFrame);
1891
- if(!manifest){query.set('initial','1');query.set('metadata','1');}
1892
- else if(manifest.renderTheme!==effectiveTheme || scopeRequest!==initializedScope)query.set('metadata','1');
2599
+ if (!manifest) query.set('initial', '1');
2600
+ if (!(frameFilter !== 'all' && (!manifest || derivedLanding)) &&
2601
+ (!manifest || manifest.renderTheme !== effectiveTheme || scopeRequest !== initializedScope)) query.set('metadata', !manifest && !onlyFrame ? 'layout' : '1');
1893
2602
  const signal=refreshController.signal, data=await api(`manifest?${query}`,null,false,signal);
1894
2603
  signal.throwIfAborted();
1895
2604
  data.scope ??= 'all';
@@ -1911,14 +2620,37 @@ async function refresh(force = false) {
1911
2620
  }
1912
2621
  await refresh();
1913
2622
  if(fixtureState) { try { await applyFixture(); } catch(e) { error(e.message); } }
1914
- if ((reviewManifest || tokenManifest || manifest) && !isUnauthorized()) {
2623
+ if ((tokenManifest || manifest) && !isUnauthorized()) {
1915
2624
  const events = new EventSource(keyURL('events'));
2625
+ const refreshComments = () => commentUI.refresh().catch(err => error(err.message));
2626
+ events.addEventListener('comments', refreshComments);
2627
+ let connectedOnce=false;
2628
+ events.addEventListener('open',()=>{
2629
+ refreshComments();
2630
+ if(connectedOnce)void refresh();
2631
+ connectedOnce=true;
2632
+ });
1916
2633
  window.addEventListener('adg-unauthorized', () => events.close(), { once: true });
1917
- events.onmessage = (e) => {
2634
+ events.onmessage = async (e) => {
1918
2635
  const data = JSON.parse(e.data);
2636
+ if (data.changed || data.motionSources) recentFilter.invalidate();
2637
+ if(data.motionSources){
2638
+ if (manifest) {
2639
+ manifest.motionFrames = data.motionFrames;
2640
+ manifest.motionEdges = data.motionEdges;
2641
+ manifest.revision = data.revision;
2642
+ }
2643
+ setMotionProjection(data.motionFrames);
2644
+ if (frameFilter === 'playable') renderFrameView();
2645
+ updateFramePlay();
2646
+ requestDraw();
2647
+ return;
2648
+ }
1919
2649
  if (data.error) error(data.error);
1920
- else if (data.annotations) annotationUI.refresh().catch(err => error(err.message));
1921
- else void refresh();
2650
+ else {
2651
+ void refresh();
2652
+ if (data.changed && commentCatalogLoaded) void refreshCommentCatalog();
2653
+ }
1922
2654
  };
1923
2655
  events.onerror = async () => {
1924
2656
  try {
@@ -1927,21 +2659,36 @@ if ((reviewManifest || tokenManifest || manifest) && !isUnauthorized()) {
1927
2659
  error('Local server disconnected. Reconnecting…');
1928
2660
  } catch (e) { error(e.message); }
1929
2661
  };
2662
+ void refreshComments().then(async () => {
2663
+ const number = new URL(location.href).searchParams.get('comment');
2664
+ if (number) {
2665
+ await refreshCommentCatalog();
2666
+ void commentUI.openLink(number);
2667
+ }
2668
+ });
1930
2669
  }
1931
2670
 
1932
2671
  document.addEventListener("keydown", (e) => {
1933
2672
  if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
1934
- if (reviewManifest) return;
1935
2673
  e.preventDefault();
1936
- $("#search").focus();
2674
+ if (frameFilter === 'all') $("#search").focus();
1937
2675
  return;
1938
2676
  }
1939
2677
  if (e.key !== "Escape" || document.querySelector("dialog[open]")) return;
1940
2678
  if (document.querySelector(":popover-open")) return;
1941
- if (annotationUI.cancelMove()) return;
1942
- if (reviewManifest) return;
2679
+ if (e.defaultPrevented) return;
2680
+ if (frameFilter !== 'all') {
2681
+ e.preventDefault();
2682
+ setFrameFilter('all');
2683
+ return;
2684
+ }
1943
2685
  if (tokenManifest) {
1944
- if ($('#search').value) $('#search-clear').click();
2686
+ if ($('#search').value) {
2687
+ e.preventDefault();
2688
+ $('#search-clear').click();
2689
+ } else if (document.activeElement === $('#search')) {
2690
+ viewport.focus({ preventScroll: true });
2691
+ }
1945
2692
  return;
1946
2693
  }
1947
2694
  if (searchReturn) {
@@ -1949,11 +2696,27 @@ document.addEventListener("keydown", (e) => {
1949
2696
  searchReturn = null;
1950
2697
  $("#search").value = "";
1951
2698
  toggleSidebar(old.sidebar);
1952
- ({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
1953
- selection();
1954
- commit(old.view);
1955
- } else clearSelection();
2699
+ if (old.scope === initializedScope) {
2700
+ ({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
2701
+ selection();
2702
+ commit(old.view);
2703
+ } else {
2704
+ renderNav();
2705
+ }
2706
+ } else if ($("#search").value) {
2707
+ $("#search").value = "";
2708
+ $("#search").oninput();
2709
+ } else if (selected) {
2710
+ clearSelection();
2711
+ } else if (!$("#back").disabled) {
2712
+ back();
2713
+ }
1956
2714
  viewport.focus({ preventScroll: true });
1957
2715
  });
1958
2716
 
1959
2717
  initSwitcher();
2718
+
2719
+ $('#token-list-toggle').onclick = () => {
2720
+ $('#more-menu').hidePopover();
2721
+ setTokenList(!tokenList);
2722
+ };