@whzxc/agent-design-gallery 0.14.0 → 0.15.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 (64) hide show
  1. package/README.md +26 -16
  2. package/package.json +1 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +708 -483
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +60 -38
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +124 -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 +26 -2
  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 +2 -0
  19. package/public/index.html +13 -9
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/selection.js +1 -1
  23. package/public/style.css +74 -152
  24. package/public/switcher.css +5 -4
  25. package/public/switcher.js +109 -34
  26. package/public/token-catalog.js +8 -3
  27. package/public/tokens.css +14 -1
  28. package/public/view-route.js +0 -1
  29. package/src/boards/board.mjs +30 -0
  30. package/src/boards/token-board.mjs +196 -0
  31. package/src/cli-output.mjs +8 -5
  32. package/src/cli.mjs +49 -29
  33. package/src/comments.mjs +293 -0
  34. package/src/http.mjs +2 -3
  35. package/src/hub/project-link.mjs +41 -0
  36. package/src/hub/registry.mjs +5 -0
  37. package/src/hub.mjs +14 -10
  38. package/src/link.mjs +13 -1
  39. package/src/server.mjs +57 -93
  40. package/src/service.mjs +46 -12
  41. package/src/toolkit/arch.mjs +3 -2
  42. package/src/toolkit/asset-rules.mjs +24 -1
  43. package/src/toolkit/build-worker.mjs +6 -2
  44. package/src/toolkit/build.mjs +4 -2
  45. package/src/toolkit/commands.mjs +12 -7
  46. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  47. package/src/toolkit/diff-inputs.mjs +66 -30
  48. package/src/toolkit/diff.mjs +181 -39
  49. package/src/toolkit/impact-selection.mjs +25 -10
  50. package/src/toolkit/impact.mjs +32 -12
  51. package/src/toolkit/move-pairing.mjs +140 -0
  52. package/src/toolkit/project-index.mjs +2 -2
  53. package/src/toolkit/results.mjs +1 -1
  54. package/src/toolkit/review-document.mjs +435 -0
  55. package/src/toolkit/review-groups.mjs +29 -0
  56. package/src/toolkit/review-observation.mjs +131 -0
  57. package/src/toolkit/review-sheet.mjs +117 -0
  58. package/src/toolkit/review-specimens.mjs +60 -0
  59. package/src/toolkit/review.mjs +140 -0
  60. package/src/toolkit/runtime.mjs +1 -1
  61. package/src/toolkit/theme.mjs +16 -0
  62. package/public/annotations.js +0 -816
  63. package/public/labels.js +0 -122
  64. package/src/annotations.mjs +0 -238
package/public/app.js CHANGED
@@ -1,32 +1,72 @@
1
- import { createAnnotations, createContextMenu, formatElementReference, READABLE_ANNOTATION_SCALE } from './annotations.js';
1
+ import { createContextMenu } from './context-menu.js';
2
+ import { createComments } from './comments.js';
3
+ import { attachComment, commentElement, commentLabel, placeComment } from './comment-anchors.js';
2
4
  import { initSwitcher, updateSwitcherLabels } from './switcher.js';
3
5
  import { dataFetch, keyURL, isUnauthorized } from './auth.js';
4
- import { Labels } from "./labels.js";
5
- import { fitArea, fitView, packingSnapshot, restorePacking } from "./layout.js";
6
+ import { fitArea, fitView } from "./layout.js";
6
7
  import { icon, hydrateIcons } from "./icons.js";
7
8
  hydrateIcons();
8
9
  import { prepare, imageURL, arrange, groupAssets, evictPreviews, metadataContext, measuredMetadata, previewAddress, compactPreparedSource, scopeKind, scopeTarget } from "./assets.js";
9
10
  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';
11
+ import { contains, hitSelection, frameBox, exportFrames } from './selection.js';
12
+ import { groupTokens, renderTokenTable, tokenBoardSection } from './token-catalog.js';
13
13
  import { readViewRoute, viewURL } from './view-route.js';
14
+ import { createBoardLayer } from './boards.js';
14
15
  import { createArranger } from './arrangement.js';
15
16
  const arranger = createArranger();
16
17
  window.addEventListener('pagehide',()=>arranger.close());
17
18
  // ARC's gallery layout and camera model, decoupled from its React runtime.
18
19
  const $ = (selector) => document.querySelector(selector);
20
+ const copyTimers = new WeakMap();
21
+ function flashCopied(button) {
22
+ if (!button) return;
23
+ const holder = button.querySelector('[data-icon]');
24
+ button.dataset.copied = 'true';
25
+ if (holder) holder.innerHTML = icon('check', Number(holder.dataset.size) || 12);
26
+ clearTimeout(copyTimers.get(button));
27
+ copyTimers.set(button, setTimeout(() => {
28
+ delete button.dataset.copied;
29
+ if (holder) holder.innerHTML = icon(holder.dataset.icon || 'copy', Number(holder.dataset.size) || 12);
30
+ }, 1200));
31
+ }
19
32
  const viewport = $(".gallery-viewport"),
20
33
  canvas = $("#drawings"),
21
34
  ctx = canvas.getContext("2d"),
22
35
  background = $("#canvas-background"),
23
36
  backgroundContext = background.getContext("2d", { alpha: false });
37
+ const boardLayer = createBoardLayer(viewport, (path, title, button) => {
38
+ const asset = assets.find(a => a.path === path);
39
+ if (asset) selectSource(asset);
40
+ navigator.clipboard.writeText(title).then(() => {
41
+ flashCopied(button);
42
+ if ($('#error').textContent.startsWith('Cannot copy name:')) error('');
43
+ }, failure => error(`Cannot copy name: ${failure.message}`));
44
+ }, {
45
+ onSelectFrame(source, frameName) {
46
+ const item = assets.find(a => a.path === source && (a.component || a.shown[0]?.name === frameName));
47
+ const part = item?.parts.find(p => p.name === frameName);
48
+ if (item && part) selectFrame(item, part);
49
+ else if (item) selectSource(item);
50
+ },
51
+ onFocusFrame(source, frameName) {
52
+ const item = assets.find(a => a.path === source && (a.component || a.shown[0]?.name === frameName));
53
+ const part = item?.parts.find(p => p.name === frameName);
54
+ if (item && part) inspectForm(item, part);
55
+ },
56
+ onCopyError(failure) {
57
+ if (failure) error(`Cannot copy token name: ${failure.message}`);
58
+ else if ($('#error').textContent.startsWith('Cannot copy token name:')) error('');
59
+ },
60
+ });
24
61
  let manifest,
25
62
  catalog = null,
26
63
  tokenManifest = null,
27
- reviewManifest = null,
28
64
  tokenCategory = null,
65
+ tokenList = false,
66
+ tokenSearchWasBoard = false,
67
+ tokenHeight = 0,
29
68
  pendingNavigation = null,
69
+ commentUI = null,
30
70
  groups = [],
31
71
  assets = [],
32
72
  world = { x: 0, y: 0, width: 1, height: 1 },
@@ -45,16 +85,6 @@ let raf = 0,
45
85
  loading = 0,
46
86
  queued = [],
47
87
  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
88
  let drawingDirty = true, drawingView = null, drawingMargin = 0, drawingReady = 0, drawingCount = 0;
59
89
  const zoomValue = $("#zoom-value"), zoomOutput = $("output");
60
90
  const cache = new Map(),
@@ -139,10 +169,24 @@ let route = {}, routeError;
139
169
  try { route = readViewRoute(new URL(location.href)); }
140
170
  catch (error) { routeError = error; }
141
171
  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;
172
+ let scopeRequest = fixtureName ? 'all' : (route.scope ?? 'default'), onlyFrame = route.onlyFrame ?? null;
143
173
  let initializedScope, initializedFrame, scopeEntry;
144
174
  const currentItem = () => inspection || assets.find((a) => a.id === selectedId);
175
+ function sameView(a, b) {
176
+ return !!a && !!b && a.x === b.x && a.y === b.y && a.scale === b.scale;
177
+ }
145
178
  function remember() {
179
+ const prev = history.at(-1);
180
+ if (prev &&
181
+ prev.scope === initializedScope &&
182
+ (prev.onlyFrame ?? null) === (onlyFrame ?? null) &&
183
+ prev.active === active &&
184
+ prev.selected === selected &&
185
+ prev.selectedForm === selectedForm &&
186
+ (prev.selectedElement?.id ?? null) === (selectedElement?.id ?? null) &&
187
+ sameView(prev.view, view)) {
188
+ return;
189
+ }
146
190
  history.push({
147
191
  view: { ...view },
148
192
  scope: initializedScope,
@@ -159,6 +203,17 @@ function remember() {
159
203
  });
160
204
  if (history.length > 40) history.shift();
161
205
  }
206
+ function exitIsolation(record = true) {
207
+ const data = catalog ?? manifest;
208
+ const asset = data?.assets?.[0];
209
+ const seg = asset?.layer ?? asset?.path?.split('/')[0];
210
+ const next = data?.layers?.length === 1
211
+ ? `layer:${data.layers[0]}`
212
+ : seg && ['components', 'modules', 'surfaces', 'arch'].includes(seg) && (!data?.layers || data.layers.includes(seg))
213
+ ? `layer:${seg}`
214
+ : 'all';
215
+ changeScope(next, null, record);
216
+ }
162
217
  function back() {
163
218
  if (catalog) return;
164
219
  const old = history.pop();
@@ -166,6 +221,10 @@ function back() {
166
221
  changeScope(initializedScope, null, false);
167
222
  return;
168
223
  }
224
+ if (!old && ['group', 'asset'].includes(scopeKind(initializedScope))) {
225
+ exitIsolation(false);
226
+ return;
227
+ }
169
228
  if (old) {
170
229
  if (old.scope && (old.scope !== initializedScope || (old.onlyFrame ?? null) !== onlyFrame)) {
171
230
  changeScope(old.scope, old, false);
@@ -179,22 +238,42 @@ function back() {
179
238
  function changeScope(next, entry = null, record = true) {
180
239
  const nextFrame = entry?.onlyFrame ?? null;
181
240
  if (next === scopeRequest && nextFrame === onlyFrame) return;
182
- if ((initializedScope || tokenManifest || reviewManifest) && !catalog) {
183
- if (record && !tokenManifest && !reviewManifest && next !== 'tokens' && next !== 'review') remember();
241
+ const wasOverlay = scopeRequest === 'tokens' || !!tokenManifest;
242
+ const nextOverlay = next === 'tokens';
243
+ const preserveSearch = !fixtureState && !wasOverlay && !nextOverlay && ['all', 'layer'].includes(scopeKind(next)) && !!$("#search").value.trim();
244
+ if ((initializedScope || tokenManifest) && !catalog) {
245
+ if (next === 'tokens' && manifest && !tokenManifest) manifest.view = { ...view };
246
+ if (record && !tokenManifest && next !== 'tokens') remember();
184
247
  void persistPreferences();
185
248
  }
186
249
  scopeRequest = next;
187
250
  onlyFrame = nextFrame;
188
- queryView = entry?.queryView ?? (next !== 'review' && !['all', 'layer'].includes(scopeKind(next)));
251
+ queryView = entry?.queryView ?? !['all', 'layer'].includes(scopeKind(next));
189
252
  strictRoute = false;
190
253
  scopeEntry = entry;
191
254
  initialLink = null;
192
255
  pendingNavigation = null;
193
- if (searchReturn) sidebar = searchReturn.sidebar;
194
- searchReturn = null;
195
- $("#search").value = '';
256
+ tokenSearchWasBoard = false;
257
+ if (!preserveSearch) {
258
+ if (searchReturn) sidebar = searchReturn.sidebar;
259
+ searchReturn = null;
260
+ $("#search").value = '';
261
+ }
196
262
  void refresh(true);
197
263
  }
264
+ function setTokenList(next) {
265
+ if (next === tokenList) return;
266
+ if (!next && !tokenManifest?.tokenBoard) return;
267
+ tokenList = next;
268
+ tokenSearchWasBoard = false;
269
+ updateChrome();
270
+ renderNav();
271
+ if (!tokenList && tokenHeight && world.height <= 1) {
272
+ world = { x: 0, y: 0, width: tokenManifest.tokenBoard.width, height: tokenHeight };
273
+ frame(world);
274
+ }
275
+ requestDraw();
276
+ }
198
277
  function toggleSidebar(value = !sidebar) {
199
278
  sidebar = value;
200
279
  updateChrome();
@@ -202,30 +281,61 @@ function toggleSidebar(value = !sidebar) {
202
281
  }
203
282
  function updateChrome() {
204
283
  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);
284
+ const data = tokenManifest ?? catalog ?? manifest;
285
+ const opened = !!data?.directory;
286
+ const showTokens = !!tokenManifest && tokenList;
287
+ $('#token-list-toggle').hidden = !tokenManifest;
288
+ $('#token-list-toggle').disabled = !tokenManifest?.tokenBoard;
289
+ $('#token-list-toggle').textContent = tokenList ? 'Board view' : 'List view';
290
+ const tokenToggle = $('#token-view-toggle');
291
+ tokenToggle.hidden = !tokenManifest || !!fixtureState;
292
+ tokenToggle.disabled = !tokenManifest?.tokenBoard;
293
+ const tokenMode = tokenList ? 'board' : 'list';
294
+ if (tokenToggle.dataset.mode !== tokenMode) {
295
+ tokenToggle.dataset.mode = tokenMode;
296
+ tokenToggle.innerHTML = `${icon(tokenList ? 'layout-grid' : 'list', 14)}<span>${tokenList ? 'Board view' : 'List view'}</span>`;
297
+ }
298
+ $('#token-board-button').hidden = !tokenManifest?.tokenBoard || !!fixtureState;
299
+ const isolation = $('#scope-isolation');
300
+ const showIsolation = !fixtureState && !tokenManifest && !!data?.scope && (['group', 'asset'].includes(scopeKind(data.scope)) || !!onlyFrame);
301
+ isolation.hidden = !showIsolation;
302
+ if (showIsolation) {
303
+ const label = onlyFrame ? `${scopeLabel(data.scope)} · ${onlyFrame}` : scopeLabel(data.scope);
304
+ if (isolation.dataset.label !== label) {
305
+ isolation.dataset.label = label;
306
+ isolation.innerHTML = `${icon('square-dashed', 12)}<span></span>${icon('x', 12)}`;
307
+ isolation.querySelector('span').textContent = label;
308
+ isolation.setAttribute('aria-label', `Exit isolated scope: ${label}`);
309
+ isolation.dataset.tooltip = 'Show full layer';
310
+ }
311
+ }
312
+ const canInspect = opened && !showTokens && !!selected;
313
+ $('.gallery').classList.toggle('tokens-mode', showTokens);
210
314
  $('#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;
315
+ viewport.inert = showTokens;
316
+ $('#sidebar').hidden = !opened || !sidebar;
317
+ const allArch = assets.length > 0 && assets.every(a => a.path.endsWith('.mmd'));
318
+ const canComment = opened && !tokenManifest && scopeRequest !== 'layer:arch' && !allArch;
319
+ const unavailableReason = canComment ? ''
320
+ : tokenManifest ? 'Tokens take no comments.'
321
+ : scopeRequest === 'layer:arch' || assets.some(a => a.path.endsWith('.mmd')) ? 'Architecture diagrams take no comments.'
322
+ : '';
323
+ $('#comment-tool').hidden = !!tokenManifest && !!fixtureState;
324
+ $('#comment-tool').disabled = !canComment;
325
+ $('#comment-tool').dataset.tooltip = canComment || !unavailableReason ? 'Comment (C)' : unavailableReason;
326
+ commentUI?.setAvailable?.(canComment, unavailableReason);
219
327
  $('#app-bar').hidden = !opened;
220
328
  if (fixtureState) $('#app-directory .switcher-chevron').hidden = false;
221
329
  $('#tools').hidden = !opened;
222
- $('.zoom').hidden = !opened || showTokens || showReview;
330
+ $('.zoom').hidden = !opened || showTokens;
223
331
  $('#source').hidden = !canInspect || !inspector;
224
332
  $('#inspect').disabled = !canInspect;
225
333
  $('#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));
334
+ $('#arrange').hidden = !!tokenManifest;
335
+ $('#zoom-fit-group').disabled = !!tokenManifest || active === null || !groups[active];
336
+ $('#zoom-fit-selection').disabled = !!tokenManifest || !selected;
337
+ if (!opened) $('#minimap').hidden = true;
338
+ $('#sidebar-toggle').setAttribute('aria-expanded', String(opened && sidebar));
229
339
  positionZoomMenu();
230
340
  }
231
341
  function positionZoomMenu() {
@@ -238,9 +348,8 @@ const media = matchMedia("(prefers-color-scheme: dark)");
238
348
  const modifiedDate = new Intl.DateTimeFormat('en-US', {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
239
349
  window.__adg = {
240
350
  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;},
351
+ get metadataComplete() {return !!tokenManifest || (!!manifest && !manifest.loading);},
352
+ get scope() {return tokenManifest?.scope ?? initializedScope;},
244
353
  get cachePending() {return cacheWrites+loading+queued.length;},
245
354
  get cacheFlush() {return flushCache();},
246
355
  get cacheFailures() {return cacheFailures;},
@@ -248,7 +357,7 @@ window.__adg = {
248
357
  return { ...view };
249
358
  },
250
359
  get assets() {
251
- return reviewManifest || tokenManifest ? 0 : assets.length;
360
+ return tokenManifest ? 0 : assets.length;
252
361
  },
253
362
  get previews() {
254
363
  return {entries: cache.size, decoded: [...cache.values()].filter(e => e.image).length,
@@ -293,7 +402,7 @@ async function api(url, data, keepalive = false, signal) {
293
402
  return result;
294
403
  }
295
404
  function preferences() {
296
- if (reviewManifest || tokenManifest || onlyFrame) return { theme };
405
+ if (tokenManifest || onlyFrame) return { theme };
297
406
  return {
298
407
  view,
299
408
  scope: initializedScope,
@@ -343,91 +452,51 @@ function restoreSelection(target) {
343
452
  }
344
453
  function persistPreferences(keepalive = false) {
345
454
  clearTimeout(saveTimer);
346
- if (fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
455
+ if (fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
347
456
  return api('preferences', preferences(), keepalive).catch(e => error(e.message));
348
457
  }
349
458
  function save() {
350
- if(fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
459
+ if(fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
351
460
  clearTimeout(saveTimer);
352
461
  saveTimer = setTimeout(persistPreferences, 220);
353
462
  }
354
463
  window.addEventListener('pagehide', () => void persistPreferences(true));
355
464
  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;
465
+ 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
466
  function layout(data, preserve = false, options = {}) {
358
467
  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);
468
+ const previousGroups = groups,
469
+ result = arrange(layoutData(data),{...options, previousGroups: preserve ? previousGroups : undefined});
362
470
  groups = result.groups;
363
471
  assets = result.items;
364
472
  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);
473
+ if (data.scope === 'all' && data.tokenBoard && tokenHeight) {
474
+ const offset = tokenHeight + 480;
475
+ for (const group of groups) group.y += offset;
476
+ for (const asset of assets) {
477
+ asset.y += offset;
478
+ if (asset.well) asset.well.y += offset;
419
479
  }
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
- );
427
- }
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));
480
+ world.height += offset;
481
+ world.width = Math.max(world.width, 1680);
430
482
  }
483
+ boardLayer.update(groups, assets, data);
484
+ boardLayer.tokens(data.scope === 'all' ? data.tokenBoard : null, h => {
485
+ if (Math.abs(tokenHeight-h)>1) {
486
+ const firstMeasurement = !tokenHeight;
487
+ const previousSelection = firstMeasurement ? selectedBox() : null;
488
+ tokenHeight=h;
489
+ layout(data, preserve, options);
490
+ const nextSelection = previousSelection ? selectedBox() : null;
491
+ if (nextSelection) {
492
+ commit({ ...view,
493
+ x: view.x - (nextSelection.x - previousSelection.x) * view.scale,
494
+ y: view.y - (nextSelection.y - previousSelection.y) * view.scale,
495
+ });
496
+ } else if (firstMeasurement && !preserve && !data.view) frame(world);
497
+ requestDraw();
498
+ }
499
+ });
431
500
  renderNav();
432
501
  $("#asset-access").replaceChildren(
433
502
  ...assets.map((a) => {
@@ -437,11 +506,21 @@ function layout(data, preserve = false, options = {}) {
437
506
  return b;
438
507
  }),
439
508
  );
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.';
509
+ $("#empty").hidden = !!assets.length || !!data.tokenBoard || !data.directory;
510
+ if (!assets.length) $("#empty").textContent = scopedUI(data) ? 'No assets in this scope.' : 'No design sources in this directory.';
442
511
  endArrangement?.({items:assets.length});
443
512
  if (assets.length) globalThis.__adgTiming?.mark('first-layout');
444
513
  }
514
+ function assetTitle(path = '') {
515
+ const parts = path.split('/');
516
+ const filename = parts.at(-1) ?? '';
517
+ return filename === 'index.tsx' && parts.length > 1
518
+ ? parts.at(-2)
519
+ : filename.replace(/\.(tsx|svg|mmd)$/i, '');
520
+ }
521
+ function displayName(a) {
522
+ return a?.path ? assetTitle(a.path) : a?.name ?? '';
523
+ }
445
524
  function makeRow(name, label, count, className = 'tree-row') {
446
525
  const button = document.createElement('button'); button.className = className;
447
526
  button.innerHTML = icon(name, 14);
@@ -451,8 +530,8 @@ function makeRow(name, label, count, className = 'tree-row') {
451
530
  }
452
531
  function searchResults(query) {
453
532
  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 })));
533
+ const files = entries.filter(a => displayName(a).toLowerCase().includes(query)).map(a => ({ a }));
534
+ const forms = entries.flatMap(a => displayName(a).toLowerCase().includes(query) ? [] : (a.parts ?? []).filter(p => p.name.toLowerCase().includes(query)).map(p => ({ a, p })));
456
535
  return [...files, ...forms];
457
536
  }
458
537
  function navigate(action) {
@@ -462,17 +541,15 @@ function navigate(action) {
462
541
  function scopedUI(data) { return !!data.layers && (!data.fixture || !!data.fixture.scope); }
463
542
  function scopeLabel(scope) {
464
543
  const target = scopeTarget(scope);
465
- if (scope === 'review') return 'Review';
466
544
  if (scope === 'all') return 'All designs';
467
545
  if (scope === 'tokens') return 'Tokens';
468
546
  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,'');
547
+ if (scopeKind(scope) === 'asset') return assetTitle(target);
470
548
  return target;
471
549
  }
472
550
  function renderScopeTabs(data) {
473
551
  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'];
552
+ const choices = [...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
476
553
  const signature = JSON.stringify([data.scope, choices]);
477
554
  $('#sidebar').classList.toggle('scoped', scopedUI(data));
478
555
  if (tabs.dataset.signature === signature) return;
@@ -502,6 +579,7 @@ $('#scope-tabs').addEventListener('keydown', event => {
502
579
  : step ? tabs[(index + step + tabs.length) % tabs.length] : null;
503
580
  if (!target) return;
504
581
  event.preventDefault();
582
+ event.stopPropagation();
505
583
  target.focus();
506
584
  target.click();
507
585
  });
@@ -518,24 +596,21 @@ function scopeAction(kind, key, label) {
518
596
  }
519
597
  function navFile(a, options = {}) {
520
598
  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');
599
+ const label = displayName(a);
600
+ const item=makeRow((a.component ?? a.path.startsWith('components/'))?'component':'app-window',label,undefined,'tree-row file');
522
601
  item.dataset.navkey=`file:${a.path}`;
523
602
  item.setAttribute('aria-current',String(selected===a.path));
524
603
  item.onclick=()=>navigate(()=>focusAsset(assets.find(x=>x.path===a.path)));
525
604
  if (!isolate) return item;
526
605
  const row=document.createElement('div');row.className='scope-row';
527
606
  if (indent) row.classList.add('scope-row-indent');
528
- row.append(item,scopeAction('asset',a.path,a.name));
607
+ row.append(item,scopeAction('asset',a.path,label));
529
608
  return row;
530
609
  }
531
610
  function renderNav() {
532
- const data = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
611
+ const data = tokenManifest ?? catalog ?? manifest;
533
612
  if (!data) return;
534
613
  renderScopeTabs(data);
535
- if (reviewManifest) {
536
- requestDraw();
537
- return;
538
- }
539
614
  const scoped = scopedUI(data), kind = scoped ? scopeKind(data.scope) : null;
540
615
  const focusKey = document.activeElement?.dataset.navkey;
541
616
  const query = $("#search").value.trim().toLowerCase(), nodes = [];
@@ -552,6 +627,16 @@ function renderNav() {
552
627
  button.setAttribute('aria-current', String(tokenCategory === category));
553
628
  button.onclick = () => {
554
629
  tokenCategory = category;
630
+ if (!tokenList) {
631
+ if (!category) {
632
+ frame(world);
633
+ } else {
634
+ const slug = tokenBoardSection(category);
635
+ const box = slug && boardLayer.tokenSection(slug);
636
+ if (box) commit(fitView(box, fitArea(width, height, sidebar, false), 24));
637
+ else setTokenList(true);
638
+ }
639
+ }
555
640
  $('.token-scroll').scrollTop = 0;
556
641
  renderNav();
557
642
  };
@@ -566,16 +651,27 @@ function renderNav() {
566
651
  });
567
652
  } else if (query) {
568
653
  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);
654
+ heading.className = 'search-count';
655
+ heading.textContent = results.length === 0 && data.scope && data.scope !== 'all'
656
+ ? `0 results in ${scopeLabel(data.scope)}`
657
+ : `${results.length} ${results.length === 1 ? 'result' : 'results'}`;
658
+ nodes.push(heading);
659
+ if (results.length === 0 && data.scope && data.scope !== 'all') {
660
+ const expand = makeRow('layout-grid', 'Search All designs', undefined, 'tree-row search-result');
661
+ expand.dataset.navkey = 'search:all';
662
+ expand.onclick = () => changeScope('all');
663
+ nodes.push(expand);
664
+ }
570
665
  for (const { a, p } of results) {
666
+ const name = displayName(a);
571
667
  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');
668
+ 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
669
  button.dataset.navkey=`search:${a.path}:${p?.id ?? ''}`;
574
670
  button.setAttribute('aria-current',String(selected===a.path && (!p || selectedForm===p.id)));
575
671
  button.onclick=()=>navigate(()=>p ? inspectForm(a,p) : focusAsset(assets.find(item=>item.path===a.path)));
576
672
  if (scoped && kind!=='asset' && !p) {
577
673
  const row=document.createElement('div');row.className='scope-row';
578
- row.append(button,scopeAction('asset',a.path,a.name));nodes.push(row);
674
+ row.append(button,scopeAction('asset',a.path,name));nodes.push(row);
579
675
  } else nodes.push(button);
580
676
  }
581
677
  } else if (kind === 'asset') {
@@ -616,7 +712,7 @@ function renderNav() {
616
712
  requestDraw();
617
713
  }
618
714
  function renderRelationships(source) {
619
- const basename = path => path.split('/').at(-1).replace(/\.tsx$/, '');
715
+ const basename = path => assetTitle(path);
620
716
  for (const [id,direction] of [['uses','uses'],['used-by','usedBy']]) {
621
717
  const entries=relatedSources(manifest?.relationships ?? {},source,direction), directories=new Map();
622
718
  for (const entry of entries) {
@@ -629,7 +725,7 @@ function renderRelationships(source) {
629
725
  const group=document.createElement('section'),heading=document.createElement('h5');
630
726
  heading.className='relationship-directory';heading.textContent=directory;group.append(heading);
631
727
  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(' → ');
728
+ const via=entry.via.map(path=>basename(path)===basename(entry.path)?path.replace(/(\/index)?\.(tsx|mmd|svg)$/i,''):basename(path)).join(' → ');
633
729
  const button=makeRow(directory==='surfaces'?'app-window':'component',basename(entry.path)+(via?` · via ${via}`:''),undefined,'tree-row relationship-row'+(entry.direct?'':' indirect'));
634
730
  button.dataset.relatedPath=entry.path;button.dataset.direct=String(entry.direct);
635
731
  button.title=entry.path+(entry.via.length?` via ${entry.via.join(' → ')}`:'');
@@ -652,22 +748,23 @@ function selection() {
652
748
  if (!selected) inspector = false;
653
749
  syncSelectionURL();
654
750
  renderNav(); updateChrome();
655
- $('#back').disabled = !history.length && !onlyFrame;
751
+ $('#back').disabled = !history.length && !onlyFrame && !['group', 'asset'].includes(scopeKind(initializedScope));
656
752
  const host=currentItem(), part=host?.parts.find(p=>p.id===selectedForm);
657
753
  const owner=selectedElement?.owner;
658
754
  const hasExport=!!owner?.export;
659
755
  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
756
  if(a) {
661
- $('#source-name').textContent=hasExport ? owner.export : a.name;$('#source-path').textContent=a.path;
757
+ const isComponent = a.sourceComponent ?? a.component ?? manifest?.assets.find(x => x.path === a.path)?.component ?? a.path?.startsWith('components/');
758
+ $('#source-name').textContent=hasExport ? owner.export : displayName(a);$('#source-path').textContent=a.path;
662
759
  $('#source-path').title=a.path;
663
760
  $('#frame-detail').hidden=!part;
664
761
  $('#frame-name').textContent=part?.name ?? '';
665
762
  const size=selectedElement ?? part;
666
763
  $('#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';
764
+ $('#forms-heading').textContent=hasExport?'Frames using this export':isComponent?'Forms':'Frames';
668
765
  const forms=hasExport?exportFrames(a,owner):a.parts;
669
766
  $('#forms').replaceChildren(...forms.map(p=>{
670
- const button=makeRow(a.component?'component':'app-window',p.name,`${Math.round(p.width)} × ${Math.round(p.height)}`);
767
+ const button=makeRow(isComponent?'component':'app-window',p.name,`${Math.round(p.width)} × ${Math.round(p.height)}`);
671
768
  button.classList.add('frame-row');button.title=p.name;
672
769
  button.dataset.frame=p.name;
673
770
  button.setAttribute('aria-current',String(!hasExport && selectedForm===p.id));
@@ -682,11 +779,19 @@ function selection() {
682
779
  }
683
780
  function selectSource(a) {
684
781
  if (!a) return;
685
- remember();inspection=null;selected=a.path;selectedId=a.id;selectedForm=null;selectedElement=null;active=a.group;expanded.add(active);selection();
782
+ const unchanged = !inspection && selected === a.path && selectedId === a.id && selectedForm === null && selectedElement === null && active === a.group;
783
+ if (!(unchanged && sameView(history.at(-1)?.view, view) && history.at(-1)?.scope === initializedScope)) remember();
784
+ inspection=null;selected=a.path;selectedId=a.id;selectedForm=null;selectedElement=null;active=a.group;expanded.add(active);selection();
686
785
  }
687
786
  function selectFrame(a,p,element=null) {
688
787
  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;
788
+ const nextElement = element ? { ...element, owner: elementOwner(element, a.path) } : null;
789
+ const unchanged = selected === a.path && selectedId === a.id && selectedForm === p.id && active === a.group &&
790
+ (selectedElement?.id ?? null) === (nextElement?.id ?? null) &&
791
+ (selectedElement?.owner?.source ?? null) === (nextElement?.owner?.source ?? null) &&
792
+ (selectedElement?.owner?.export ?? null) === (nextElement?.owner?.export ?? null);
793
+ if (!(unchanged && sameView(history.at(-1)?.view, view) && history.at(-1)?.scope === initializedScope)) remember();
794
+ selected=a.path;selectedId=a.id;selectedForm=p.id;active=a.group;selectedElement=nextElement;
690
795
  expanded.add(active);selection();
691
796
  }
692
797
  function clearSelection() { selected=null;selectedId=null;selectedForm=null;selectedElement=null;inspection=null;selection(); }
@@ -699,88 +804,146 @@ function selectedBox() {
699
804
  function copyToClipboard(text) {
700
805
  navigator.clipboard.writeText(text).catch(e => error(e.message));
701
806
  }
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
807
  const contextMenu = createContextMenu($('#context-menu'), {
743
808
  viewport,
744
809
  onOverlayChange: () => { hideTooltip(); requestDraw(true, false); },
745
810
  });
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) };
811
+ const boardPoint = (x, y) => {
812
+ const rect = viewport.getBoundingClientRect();
813
+ return { x: (x - rect.left - view.x) / view.scale, y: (y - rect.top - view.y) / view.scale };
814
+ };
815
+ function asScreen(box) {
816
+ const rect = viewport.getBoundingClientRect();
817
+ return { x: rect.left + view.x + box.x * view.scale, y: rect.top + view.y + box.y * view.scale,
818
+ width: box.width * view.scale, height: box.height * view.scale };
819
+ }
820
+ const sourcePrefix = () => manifest?.sourcePrefix ?? '';
821
+ const projectSource = source => {
822
+ const prefix = sourcePrefix();
823
+ return !prefix || source.startsWith(prefix + '/') ? source : prefix + '/' + source;
824
+ };
825
+ const designSource = source => sourcePrefix() && source.startsWith(sourcePrefix() + '/') ? source.slice(sourcePrefix().length + 1) : source;
826
+ const commentable = source => !source?.endsWith('.mmd');
827
+ const sectionBox = (board, block) => ({ x: board.x + block.x, y: board.y + block.y, width: block.w, height: block.h });
828
+ const boardGroup = (thread, board) => board.layer === thread.anchor.layer && board.title === thread.anchor.chapter;
829
+ let commentBoards = [];
830
+ let commentCatalogRun, commentCatalogLoaded;
831
+ function refreshCommentCatalog() {
832
+ if (commentCatalogRun) return commentCatalogRun;
833
+ const catalog = manifest?.scope === 'all' ? Promise.resolve(manifest) : api('manifest');
834
+ commentCatalogRun = catalog.then(data => {
835
+ commentBoards = groupAssets(data);
836
+ commentCatalogLoaded = true;
837
+ commentUI.render();
838
+ }).catch(() => {}).finally(() => { commentCatalogRun = null; });
839
+ return commentCatalogRun;
840
+ }
841
+ const commentOwner = (element, fallback) => {
842
+ if (!element) return null;
843
+ const owner = elementOwner(element, fallback);
844
+ return owner.export ? projectSource(owner.source) + '#' + owner.export : null;
845
+ };
846
+ function targetOnBoard(x, y, deepest, point = boardPoint(x, y)) {
847
+ if (tokenManifest || !manifest || manifest.renderTheme !== effectiveTheme) return null;
848
+ const { x: wx, y: wy } = point;
849
+ const hit = hitSelection(inspection ? [inspection] : assets, wx, wy, false);
850
+ const group = hit ? groups[hit.asset.group] : groups.find(board => contains(board, wx, wy));
851
+ if (!group || group.layer?.toLowerCase() === 'arch') return null;
852
+ const block = group.blocks?.find(block => contains(sectionBox(group, block), wx, wy));
853
+ const path = hit?.asset.path ?? block?.asset;
854
+ if (!commentable(path) || (!path && group.assets?.every(asset => !commentable(asset.path)))) return null;
855
+ const part = hit?.part;
856
+ const frameBounds = part ? frameBox(hit.asset, part) : null;
857
+ const elementHit = part?.elements?.findLast(element => contains(element, wx - frameBounds.x, wy - frameBounds.y));
858
+ const element = commentElement(part?.elements, elementHit, deepest);
859
+ const box = element ? { ...element, x: frameBounds.x + element.x, y: frameBounds.y + element.y }
860
+ : frameBounds ?? (block ? sectionBox(group, block) : group);
861
+ return { ...placeComment({ source: path ? projectSource(path) : null, frame: part?.name, layer: group.layer,
862
+ chapter: group.title, box, frameBox: frameBounds, element, owner: commentOwner(element, path),
863
+ label: path ? commentLabel(path, part?.name) : `${group.layer} / ${group.title}` }, point),
864
+ x, y, box: asScreen(box) };
865
+ }
866
+ function boardAttachment(thread) {
867
+ const { source, frame: frameName } = thread.anchor;
868
+ const path = source && designSource(source);
869
+ const board = groups.find(group => path ? group.blocks?.some(block => block.asset === path) : boardGroup(thread, group));
870
+ if (!board) return null;
871
+ const block = board.blocks?.find(block => block.asset === path);
872
+ const item = (inspection ? [inspection] : assets).find(asset => asset.path === path && asset.shown[0]?.name === frameName);
873
+ const part = item?.parts.find(part => part.name === frameName);
874
+ const attached = attachComment(thread, { chapter: board, source: block && sectionBox(board, block),
875
+ frame: part && frameBox(item, part), elements: part?.elements });
876
+ return attached && { ...attached, chapter: board.title, layer: board.layer };
877
+ }
878
+
879
+ function locateComment(thread) {
880
+ if (tokenManifest) return null;
881
+ const point = boardAttachment(thread);
882
+ return point && { ...point, ...asScreen({ x: point.x, y: point.y, width: 0, height: 0 }) };
883
+ }
884
+ function focusBoardComment(thread) {
885
+ const point = boardAttachment(thread);
886
+ if (!point) return false;
887
+ const target = point.box;
888
+ if (!contains(target, point.x, point.y)) return false;
889
+ if (thread.anchor.kind === 'element' && !point.changed) {
890
+ const scale = view.scale;
891
+ commit({ scale, x: cameraArea().x + cameraArea().width / 2 - point.x * scale, y: cameraArea().y + cameraArea().height / 2 - point.y * scale });
892
+ } else frame(target, 48);
893
+ return true;
894
+ }
895
+ let commentNavigation;
896
+ async function navigateComment(thread) {
897
+ if (!tokenManifest && focusBoardComment(thread)) return true;
898
+ const { layer } = commentBoardPlace(thread);
899
+ const next = layer ? `layer:${layer}` : 'all';
900
+ if (scopeRequest === next && !manifest?.loading) return false;
901
+ if (scopeRequest !== next) changeScope(next);
902
+ commentNavigation?.resolve(false);
903
+ return new Promise(resolve => { commentNavigation = { thread, scope: next, resolve }; });
904
+ }
905
+ function commentBoardOrder(thread) {
906
+ const { source, frame: frameName } = thread.anchor;
907
+ const path = source && designSource(source);
908
+ const boards = commentBoards.length ? commentBoards : groups;
909
+ const board = boards.findIndex(group => path ? group.assets?.some(asset => asset.path === path) : boardGroup(thread, group));
910
+ if (board < 0) return Number.MAX_SAFE_INTEGER;
911
+ const block = boards[board].assets?.findIndex(asset => asset.path === path) ?? -1;
912
+ const frameIndex = manifest?.assets.find(asset => asset.path === path)?.parts?.findIndex(part => part.name === frameName) ?? -1;
913
+ return board * 1_000_000 + (block + 1) * 1_000 + frameIndex + 1;
914
+ }
915
+ function commentBoardPlace(thread) {
916
+ const path = thread.anchor.source && designSource(thread.anchor.source);
917
+ const board = commentBoards.find(group => path ? group.assets.some(asset => asset.path === path) : boardGroup(thread, group));
918
+ return board ? { layer: board.layer, chapter: board.title } : { changed: commentBoards.length > 0 };
919
+ }
920
+ commentUI = createComments({
921
+ toolButton: $('#comment-tool'), panelButton: $('#comments-toggle'), panel: $('#comments-panel'), layer: $('#comment-layer'),
922
+ hitTest: targetOnBoard,
923
+ locate: locateComment, navigate: navigateComment, boardOrder: commentBoardOrder, boardPlace: commentBoardPlace, request: api,
924
+ onPanelToggle: open => {
925
+ if (open && inspector) {
926
+ inspector = false;
927
+ updateChrome();
928
+ requestDraw(true, false);
929
+ }
771
930
  },
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)),
931
+ });
932
+ document.addEventListener('keydown', event => commentUI.key(event));
933
+ $('#comments-toggle').addEventListener('click', () => {
934
+ if (!commentCatalogLoaded) void refreshCommentCatalog();
935
+ if (!$('#comments-panel').hidden && inspector) {
936
+ inspector = false;
937
+ updateChrome();
938
+ requestDraw(true, false);
939
+ }
778
940
  });
779
941
  function updateOutlines() {
780
- annotationUI.render();
942
+ viewport.dataset.hoverHit = String(!!hoveredElement && !commentUI.active());
943
+ commentUI.reposition();
781
944
  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]]) {
945
+ const hoverBox=hover?.element?{...hover.element,x:origin.x+hover.element.x,y:origin.y+hover.element.y}:origin;
946
+ for (const [id,box] of [['selection-outline',selectedBox() ?? (selected ? currentItem() : null)],['hover-outline',hoverBox]]) {
784
947
  const el=$('#'+id);el.hidden=!box || moving;
785
948
  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
949
  }
@@ -800,6 +963,10 @@ function frame(box, padding = 0) {
800
963
  commit(box===world ? fitWorld(cameraArea(),manifest) : fitView(box, cameraArea(), padding));
801
964
  }
802
965
  function fit() {
966
+ if (tokenManifest) {
967
+ frame(world);
968
+ return;
969
+ }
803
970
  remember();
804
971
  inspection = null;
805
972
  selected = null;
@@ -815,7 +982,7 @@ function focusAsset(a) {
815
982
  }
816
983
  function inspectForm(a,p,minScale=0) {
817
984
  if (!a || !p) return;
818
- const item=assets.find(item=>item.path===a.path && (a.component || item.shown[0].id===p.id));
985
+ const item=assets.find(item=>item.path===a.path && (item.component || item.shown[0].id===p.id));
819
986
  if (!item) {
820
987
  if (initializedScope !== 'all') {
821
988
  changeScope(`asset:${a.path}`, { target: { path: a.path, form: p.name } });
@@ -836,7 +1003,6 @@ function zoom(scale, x = cameraArea().x + cameraArea().width / 2, y = cameraArea
836
1003
  }
837
1004
  function commit(next) {
838
1005
  window.__adg.ready = false;
839
- labelsDirty ||= view.scale !== next.scale;
840
1006
  view = next;
841
1007
  moving = true;
842
1008
  requestDraw(false, false);
@@ -847,9 +1013,8 @@ function commit(next) {
847
1013
  requestDraw();
848
1014
  }, 150);
849
1015
  }
850
- function requestDraw(labelsChanged = true, drawingChanged = true) {
1016
+ function requestDraw(_labelsChanged = true, drawingChanged = true) {
851
1017
  drawingDirty ||= drawingChanged;
852
- if (labelsChanged) { labelsDirty = true; labelObstacles = null; }
853
1018
  if (!raf) raf = requestAnimationFrame(draw);
854
1019
  }
855
1020
  function visible(a, margin = 0) {
@@ -960,9 +1125,7 @@ function thumbnail(e, upgrade = false) {
960
1125
  const c = document.createElement('canvas');
961
1126
  c.width = Math.max(1, Math.ceil(e.part.width * limit));
962
1127
  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);
1128
+ const preview = c.getContext('2d');
966
1129
  preview.drawImage(e.image, 0, 0, c.width, c.height);
967
1130
  e.bitmap = c;
968
1131
  e.bitmapScale = limit;
@@ -993,13 +1156,22 @@ function draw() {
993
1156
  const endDrawing = globalThis.__adgTiming?.span('drawing');
994
1157
  raf = 0;
995
1158
  drawBackground();
996
- if (tokenManifest || reviewManifest) {
1159
+ if (tokenManifest && tokenList) {
997
1160
  window.__adg.ready = true;
998
- window.__adg.revision = (reviewManifest ?? tokenManifest)?.revision;
1161
+ window.__adg.revision = tokenManifest.revision;
999
1162
  if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
1000
1163
  endDrawing?.(); return;
1001
1164
  }
1002
- if (!labelObstacles) readChromeBounds();
1165
+ if (tokenManifest) {
1166
+ boardLayer.camera(view, false);
1167
+ const percentage = `${Math.round(view.scale * 100)}%`;
1168
+ zoomValue.textContent = percentage; zoomOutput.value = percentage;
1169
+ window.__adg.ready = tokenHeight > 0;
1170
+ window.__adg.revision = tokenManifest.revision;
1171
+ if (fixtureState && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
1172
+ drawMap();
1173
+ endDrawing?.(); return;
1174
+ }
1003
1175
  const displayed = manifest?.renderTheme === effectiveTheme ? inspection ? [inspection] : assets : [];
1004
1176
  // Keep a margin around a settled drawing. Pans can move that
1005
1177
  // retained Canvas layer without replaying or resampling the entire scene.
@@ -1017,22 +1189,25 @@ function draw() {
1017
1189
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1018
1190
  ctx.clearRect(0, 0, width + drawingMargin * 2, height + drawingMargin * 2);
1019
1191
  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) {
1192
+ const boardPalette = boardLayer.palette();
1193
+ if (!inspection) for (const g of groups) {
1021
1194
  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();
1195
+ rounded(g.x, g.y, g.width, g.height, 0, boardPalette.surface || palette.surface);
1196
+ for (const section of g.blocks) for (const specimen of section.frames) {
1197
+ const well = specimen.well;
1198
+ 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);
1199
+ }
1024
1200
  }
1025
1201
  let ready = 0, count = 0;
1026
1202
  for (const a of displayed) {
1027
1203
  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();
1204
+
1205
+ const parts = placements(a).map(pos => ({ ...pos, image: ensureImage(a, a.previewCrop ?? pos.part) }));
1206
+ ctx.save();
1207
+ const well = a.well ?? a;
1208
+ ctx.beginPath();
1209
+ ctx.roundRect(well.x, well.y, well.width, well.height, parseFloat(boardPalette['radius-card']) || 12);
1210
+ ctx.clip();
1036
1211
  const inViewport = visible(a);
1037
1212
  for (const pos of parts) {
1038
1213
  if (inViewport) count++;
@@ -1040,20 +1215,19 @@ function draw() {
1040
1215
  if (e.state !== 'ready') continue;
1041
1216
  if (inViewport) ready++;
1042
1217
  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);
1218
+ const crop = a.previewCrop ?? pos.part;
1219
+ const paint = a.paintCrop ?? pos.part;
1220
+ const sx = source.width / crop.width, sy = source.height / crop.height;
1221
+ ctx.drawImage(source, (paint.x-crop.x)*sx, (paint.y-crop.y)*sy, paint.width*sx, paint.height*sy,
1222
+ pos.x+paint.x-pos.part.x, pos.y+paint.y-pos.part.y, paint.width, paint.height);
1051
1223
  if (inViewport) globalThis.__adgTiming?.paint('first-content', {source:a.path,crop:pos.part.id});
1052
1224
  }
1053
1225
  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();
1226
+ if (a.layer?.toLowerCase() === 'surfaces' || a.path.startsWith('surfaces/')) {
1227
+ ctx.strokeStyle = boardPalette.border || palette.border;
1228
+ ctx.lineWidth = 1;
1229
+ ctx.strokeRect(a.x, a.y, a.width, a.height);
1230
+ }
1057
1231
  }
1058
1232
  ctx.restore();
1059
1233
  drawingReady = ready; drawingCount = count;
@@ -1061,7 +1235,7 @@ function draw() {
1061
1235
  }
1062
1236
  canvas.style.transform = `translate(${view.x - drawingView.x - drawingMargin}px,${view.y - drawingView.y - drawingMargin}px)`;
1063
1237
  updateOutlines();
1064
- drawLabels(displayed);
1238
+ boardLayer.camera(view, !!inspection || !!tokenManifest);
1065
1239
  const percentage = `${Math.round(view.scale * 100)}%`;
1066
1240
  if (zoomValue.textContent !== percentage) zoomValue.textContent = percentage;
1067
1241
  if (zoomOutput.value !== percentage) zoomOutput.value = percentage;
@@ -1074,78 +1248,13 @@ function draw() {
1074
1248
  if(!moving&&queued.length)pump();
1075
1249
  if (cache.size > 100) {
1076
1250
  const activeKeys = new Set(displayed.filter(a => visible(a, drawingMargin))
1077
- .flatMap(a => placements(a).map(({part}) => assetURL(a, part))));
1251
+ .flatMap(a => placements(a).map(({part}) => assetURL(a, a.previewCrop ?? part))));
1078
1252
  evictPreviews(cache, activeKeys);
1079
1253
  }
1080
1254
  endDrawing?.();
1081
1255
  }
1082
1256
  function backgroundColor() { return backgroundChoice === 'theme' ? palette.canvas : backgroundColors[backgroundChoice]; }
1083
1257
 
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
1258
  function mapGeometry() {
1150
1259
  const scale=Math.min(168/world.width,100/world.height);
1151
1260
  return {scale,x:(200-world.width*scale)/2,y:(132-world.height*scale)/2};
@@ -1154,10 +1263,15 @@ function drawMap() {
1154
1263
  const map=$("#minimap");if(map.hidden)return;
1155
1264
  if(map.width!==200*dpr||map.height!==132*dpr){map.width=200*dpr;map.height=132*dpr}
1156
1265
  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()}
1266
+ const boxes = tokenManifest
1267
+ ? [{ x: 0, y: 0, width: world.width, height: world.height }]
1268
+ : manifest?.scope === 'all' && manifest.tokenBoard && tokenHeight
1269
+ ? [{ x: 0, y: 0, width: manifest.tokenBoard.width, height: tokenHeight }, ...groups]
1270
+ : groups;
1271
+ 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
1272
  c.strokeStyle=palette.accent;c.lineWidth=1;
1159
1273
  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);
1274
+ 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
1275
  }
1162
1276
 
1163
1277
  function applyTheme() {
@@ -1173,9 +1287,17 @@ function applyTheme() {
1173
1287
  );
1174
1288
  palette.raised = css.getPropertyValue("--surface-sunken").trim();
1175
1289
  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();
1290
+ for (const sheet of document.styleSheets) {
1291
+ let rules;
1292
+ try { rules = sheet.cssRules; } catch { continue; }
1293
+ for (const rule of rules ?? []) {
1294
+ if (rule.selectorText === ':root' && rule.style.getPropertyValue('--canvas')) {
1295
+ backgroundColors.light = rule.style.getPropertyValue('--canvas').trim();
1296
+ }
1297
+ if (rule.selectorText === ':root[data-theme="dark"]' && rule.style.getPropertyValue('--canvas')) {
1298
+ backgroundColors.dark = rule.style.getPropertyValue('--canvas').trim();
1299
+ }
1300
+ }
1179
1301
  }
1180
1302
  backgroundColors.neutral=`color-mix(in srgb, ${backgroundColors.light} 50%, ${backgroundColors.dark})`;
1181
1303
  updateChoices();
@@ -1184,13 +1306,14 @@ function applyTheme() {
1184
1306
  for (const b of $("#themes").children)
1185
1307
  b.onclick = () => {
1186
1308
  theme = b.dataset.theme;
1309
+ localStorage.setItem('adg-theme', theme);
1187
1310
  applyTheme();
1188
- if (!reviewManifest) void refresh(true);
1311
+ void refresh(true);
1189
1312
  save();
1190
1313
  };
1191
1314
  media.addEventListener("change", () => {
1192
1315
  applyTheme();
1193
- if (!reviewManifest) void refresh(true);
1316
+ void refresh(true);
1194
1317
  });
1195
1318
  viewport.addEventListener(
1196
1319
  "wheel",
@@ -1216,23 +1339,28 @@ viewport.addEventListener(
1216
1339
  );
1217
1340
  viewport.addEventListener("pointerdown", (e) => {
1218
1341
  if (e.button !== 0 && e.button !== 1) return;
1219
- if(e.target.closest('.annotation-layer'))return;
1220
1342
  e.preventDefault();
1221
1343
  viewport.focus({ preventScroll: true });
1222
1344
  pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
1223
1345
  if (pointers.size === 1)
1224
- gesture = { x: e.clientX, y: e.clientY, moved: false };
1346
+ gesture = { x: e.clientX, y: e.clientY, button: e.button, moved: false };
1225
1347
  else gesture.moved = true;
1226
1348
  viewport.setPointerCapture(e.pointerId);
1227
1349
  });
1228
1350
  viewport.addEventListener("pointermove", (e) => {
1229
1351
  const old = pointers.get(e.pointerId);
1230
1352
  if (!old) {
1353
+ if (commentUI.active()) {
1354
+ hoveredElement = null;
1355
+ commentUI.hover(e.clientX, e.clientY, e.altKey);
1356
+ updateOutlines();
1357
+ return;
1358
+ }
1231
1359
  const rect=viewport.getBoundingClientRect();
1232
1360
  hoveredElement=hitSelection(inspection?[inspection]:assets,(e.clientX-rect.left-view.x)/view.scale,(e.clientY-rect.top-view.y)/view.scale);
1233
1361
  updateOutlines();return;
1234
1362
  }
1235
- hoveredElement=null;updateOutlines();
1363
+ hoveredElement=null;commentUI.hover();updateOutlines();
1236
1364
  const before = [...pointers.values()];
1237
1365
  pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
1238
1366
  if (Math.hypot(e.clientX - gesture.x, e.clientY - gesture.y) > 4)
@@ -1261,18 +1389,21 @@ viewport.addEventListener("pointermove", (e) => {
1261
1389
  });
1262
1390
  }
1263
1391
  });
1264
- viewport.addEventListener('pointerleave',()=>{hoveredElement=null;updateOutlines()});
1392
+ viewport.addEventListener('pointerleave',()=>{hoveredElement=null;commentUI.hover();updateOutlines()});
1265
1393
  function up(e) {
1266
1394
  if (!pointers.delete(e.pointerId)) return;
1267
- if (e.type === "pointerup" && !gesture.moved) {
1395
+ if (e.type === "pointerup" && !gesture.moved && gesture.button === 0) {
1268
1396
  const rect = viewport.getBoundingClientRect(),
1269
1397
  x = (e.clientX - rect.left - view.x) / view.scale,
1270
1398
  y = (e.clientY - rect.top - view.y) / view.scale;
1271
1399
  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();
1400
+ if (commentUI.active()) commentUI.click(e.clientX, e.clientY, e.altKey);
1401
+ else {
1402
+ commentUI?.dismiss?.();
1403
+ if(hit?.part) selectFrame(hit.asset,hit.part,hit.element);
1404
+ else if(hit) selectSource(hit.asset);
1405
+ else clearSelection();
1406
+ }
1276
1407
  }
1277
1408
  if (viewport.hasPointerCapture(e.pointerId))
1278
1409
  viewport.releasePointerCapture(e.pointerId);
@@ -1280,41 +1411,23 @@ function up(e) {
1280
1411
  }
1281
1412
  for (const event of ["pointerup", "pointercancel", "lostpointercapture"])
1282
1413
  viewport.addEventListener(event, up);
1283
- function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnFocus = viewport }) {
1414
+ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, deepest, returnFocus = viewport }) {
1284
1415
  const a = currentItem(), p = a?.parts.find(part => part.id === selectedForm), el = selectedElement;
1416
+ const placement = targetOnBoard(screenX, screenY, deepest, worldPoint ?? undefined);
1417
+ const comment = placement && placement.anchor.kind !== 'chapter' ? [{ label: 'Comment', action: () => commentUI.place(placement) }] : [];
1285
1418
  if (a && p && el) {
1286
- const fb = frameBox(a, p);
1287
1419
  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
1420
  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
- },
1421
+ ...comment,
1304
1422
  {
1305
1423
  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
- })),
1424
+ 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
1425
  },
1314
1426
  {
1315
1427
  label: 'Show in Inspector',
1316
1428
  action: () => {
1317
1429
  inspector = true;
1430
+ commentUI?.closePanel?.();
1318
1431
  selection();
1319
1432
  $('#copy-path')?.focus({ preventScroll: true });
1320
1433
  },
@@ -1324,6 +1437,7 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1324
1437
  disabled: !owner?.export,
1325
1438
  action: async () => {
1326
1439
  inspector = true;
1440
+ commentUI?.closePanel?.();
1327
1441
  if (owner?.source && !manifest?.assets.some(item => item.path === owner.source) && !manifest?.extraAssets?.some(item => item.path === owner.source)) {
1328
1442
  try {
1329
1443
  const loaded = await sourceFor({ path: owner.source, version: manifest?.revision ?? 0 }, effectiveTheme);
@@ -1339,6 +1453,7 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1339
1453
  label: 'Show usages',
1340
1454
  action: () => {
1341
1455
  inspector = true;
1456
+ commentUI?.closePanel?.();
1342
1457
  selection();
1343
1458
  $('#used-by-heading')?.scrollIntoView({ block: 'nearest' });
1344
1459
  ($('#used-by button') ?? $('#copy-path'))?.focus({ preventScroll: true });
@@ -1348,41 +1463,31 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1348
1463
  return;
1349
1464
  }
1350
1465
  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
1466
  contextMenu.open([
1355
- {
1356
- label: 'Annotate frame',
1357
- action: () => annotationUI.annotateAt({ source: a.path, frame: p.name, fx, fy, element: null, returnFocus }),
1358
- },
1467
+ ...comment,
1359
1468
  { label: 'Copy frame name', action: () => copyToClipboard(p.name) },
1360
1469
  { label: 'Copy source path', action: () => copyToClipboard(a.path) },
1361
1470
  {
1362
1471
  label: 'Show in Inspector',
1363
1472
  action: () => {
1364
1473
  inspector = true;
1474
+ commentUI?.closePanel?.();
1365
1475
  selection();
1366
1476
  $('#copy-frame')?.focus({ preventScroll: true });
1367
1477
  },
1368
1478
  },
1369
1479
  { 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
1480
  ], { x: screenX, y: screenY, returnFocus });
1376
1481
  return;
1377
1482
  }
1378
1483
  contextMenu.open([
1484
+ ...comment,
1379
1485
  { label: 'Fit all', action: () => fit() },
1380
1486
  { label: 'Arrange current group', action: () => $('#arrange').click() },
1381
1487
  ], { x: screenX, y: screenY, returnFocus });
1382
1488
  }
1383
1489
  viewport.addEventListener('contextmenu', e => {
1384
- if (reviewManifest || tokenManifest || !manifest?.directory) return;
1385
- if (e.target.closest('.annotation-point, .annotation-card')) return;
1490
+ if (tokenManifest || !manifest?.directory) return;
1386
1491
  e.preventDefault();
1387
1492
  viewport.focus({ preventScroll: true });
1388
1493
  const rect = viewport.getBoundingClientRect();
@@ -1392,22 +1497,13 @@ viewport.addEventListener('contextmenu', e => {
1392
1497
  if (hit?.part) selectFrame(hit.asset, hit.part, hit.element);
1393
1498
  else if (hit) selectSource(hit.asset);
1394
1499
  else clearSelection();
1395
- openSelectionContextMenu({ worldPoint: { x: wx, y: wy }, screenX: e.clientX, screenY: e.clientY, returnFocus: viewport });
1500
+ openSelectionContextMenu({ worldPoint: { x: wx, y: wy }, screenX: e.clientX, screenY: e.clientY, deepest: e.altKey, returnFocus: viewport });
1396
1501
  });
1397
1502
  document.addEventListener('keydown', e => {
1398
1503
  if (!(e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) return;
1399
- if (reviewManifest || tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1504
+ if (tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1400
1505
  e.preventDefault();
1401
1506
  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
1507
  const box = selectedBox();
1412
1508
  const vr = viewport.getBoundingClientRect();
1413
1509
  const sx = box ? vr.left + view.x + (box.x + box.width / 2) * view.scale : vr.left + width / 2;
@@ -1415,16 +1511,21 @@ document.addEventListener('keydown', e => {
1415
1511
  openSelectionContextMenu({ worldPoint: null, screenX: sx, screenY: sy, returnFocus: activeEl instanceof HTMLElement ? activeEl : viewport });
1416
1512
  });
1417
1513
  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;
1514
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey ||
1515
+ (tokenManifest && tokenList) ||
1516
+ e.target.matches("input,textarea,select,[contenteditable]") ||
1517
+ document.querySelector("dialog[open], :popover-open")) return;
1518
+ const inPanel = !!e.target.closest('#sidebar, #source, #comments-panel, #scope-tabs, #token-catalog');
1419
1519
  const v = view;
1420
- if (e.key === "+" || e.key === "=") zoom(v.scale * 1.25);
1520
+ if (e.key === "Enter") {
1521
+ if (tokenManifest || inPanel || e.target.closest('button,a,[role="button"]')) return;
1522
+ const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);if(p) inspectForm(a,p);else focusAsset(a);
1523
+ }
1524
+ else if (inPanel) return;
1525
+ else if (e.key === "+" || e.key === "=") zoom(v.scale * 1.25);
1421
1526
  else if (e.key === "-") zoom(v.scale / 1.25);
1422
1527
  else if (e.key === "0") fit();
1423
1528
  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
1529
  else if (e.key === "1") zoom(1);
1429
1530
  else if (e.key.startsWith("Arrow"))
1430
1531
  commit({
@@ -1435,10 +1536,14 @@ document.addEventListener("keydown", (e) => {
1435
1536
  else return;
1436
1537
  e.preventDefault();
1437
1538
  });
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);
1539
+ viewport.addEventListener("dblclick", event => {
1540
+ if (commentUI.active()) return;
1541
+ const rect = viewport.getBoundingClientRect();
1542
+ const x = (event.clientX - rect.left - view.x) / view.scale;
1543
+ const y = (event.clientY - rect.top - view.y) / view.scale;
1544
+ const hit = hitSelection(inspection ? [inspection] : assets, x, y);
1545
+ if (hit?.part) inspectForm(hit.asset, hit.part);
1546
+ else if (hit) focusAsset(hit.asset);
1442
1547
  });
1443
1548
  for (const [id, action] of Object.entries({
1444
1549
  "zoom-fit-all": fit,
@@ -1452,14 +1557,18 @@ for (const [id, action] of Object.entries({
1452
1557
  action();
1453
1558
  };
1454
1559
  $("#back").onclick = back;
1560
+ $("#scope-isolation").onclick = () => exitIsolation(true);
1561
+ $("#token-view-toggle").onclick = () => setTokenList(!tokenList);
1562
+ $("#token-board-button").onclick = () => setTokenList(false);
1455
1563
  $('#sidebar-toggle').onclick = () => toggleSidebar();
1456
1564
  $('#inspect').onclick = () => {
1457
1565
  inspector = !inspector;
1566
+ if (inspector) commentUI?.closePanel?.();
1458
1567
  updateChrome();
1459
1568
  requestDraw(true, false);
1460
1569
  };
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));
1570
+ $('#copy-path').onclick=()=>navigator.clipboard.writeText($('#source-path').textContent).then(()=>flashCopied($('#copy-path')),e=>error(e.message));
1571
+ $('#copy-frame').onclick=()=>navigator.clipboard.writeText($('#frame-name').textContent).then(()=>flashCopied($('#copy-frame')),e=>error(e.message));
1463
1572
  $("#fullscreen").onclick = () => {
1464
1573
  $("#more-menu").hidePopover();
1465
1574
  const p = document.fullscreenElement
@@ -1477,59 +1586,69 @@ $("#map-toggle").onclick = () => {
1477
1586
  $("#map-toggle").setAttribute("aria-pressed", String(!$("#minimap").hidden));
1478
1587
  requestDraw();
1479
1588
  };
1480
- $("#minimap").onclick = e => {
1481
- const {scale:s,x,y}=mapGeometry(),r=e.target.getBoundingClientRect(),area=cameraArea();
1482
- remember();inspection=null;selection();
1589
+ let minimapDragging = false;
1590
+ function scrubMinimap(e) {
1591
+ const map = $("#minimap");
1592
+ const {scale:s,x,y}=mapGeometry(),r=map.getBoundingClientRect(),area=cameraArea();
1483
1593
  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
- };
1594
+ }
1595
+ $("#minimap").addEventListener("pointerdown", e => {
1596
+ if (e.button !== 0) return;
1597
+ e.preventDefault();
1598
+ minimapDragging = true;
1599
+ $("#minimap").setPointerCapture(e.pointerId);
1600
+ if (!tokenManifest) {
1601
+ remember();
1602
+ inspection = null;
1603
+ selection();
1604
+ }
1605
+ scrubMinimap(e);
1606
+ });
1607
+ $("#minimap").addEventListener("pointermove", e => {
1608
+ if (!minimapDragging) return;
1609
+ scrubMinimap(e);
1610
+ });
1611
+ for (const event of ["pointerup", "pointercancel", "lostpointercapture"]) {
1612
+ $("#minimap").addEventListener(event, e => {
1613
+ if (!minimapDragging) return;
1614
+ minimapDragging = false;
1615
+ if ($("#minimap").hasPointerCapture(e.pointerId)) $("#minimap").releasePointerCapture(e.pointerId);
1616
+ requestDraw();
1617
+ });
1618
+ }
1485
1619
  $("#shortcuts").onclick = () => {
1486
1620
  $("#more-menu").hidePopover();
1487
1621
  $("#keys").showModal();
1488
1622
  };
1489
1623
  $("#arrange").onclick = async () => {
1490
1624
  const data=manifest,previousCatalog=catalog;
1625
+ if (!data) return;
1491
1626
  window.__adg.ready=false;
1492
1627
  let placed;
1493
1628
  try {if(!data.loading)placed=await arranger.arrange(layoutData(data));}
1494
1629
  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;
1630
+ if(manifest!==data || catalog!==previousCatalog || tokenManifest){requestDraw();return;}
1498
1631
  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
1632
  $("#more-menu").hidePopover();
1526
1633
  selection();
1527
1634
  };
1528
1635
  $("#search").oninput = () => {
1636
+ const hasQuery = !!$("#search").value.trim();
1529
1637
  if (tokenManifest) {
1638
+ if (hasQuery && !tokenList) {
1639
+ tokenSearchWasBoard = true;
1640
+ tokenList = true;
1641
+ updateChrome();
1642
+ requestDraw();
1643
+ } else if (!hasQuery && tokenSearchWasBoard) {
1644
+ tokenList = false;
1645
+ tokenSearchWasBoard = false;
1646
+ updateChrome();
1647
+ requestDraw();
1648
+ }
1530
1649
  $('.token-scroll').scrollTop = 0;
1531
- } else if ($("#search").value.trim()) {
1532
- searchReturn ??= { view: { ...view }, sidebar, active, selected, selectedId, selectedForm, selectedElement, inspection };
1650
+ } else if (hasQuery) {
1651
+ searchReturn ??= { scope: initializedScope, view: { ...view }, sidebar, active, selected, selectedId, selectedForm, selectedElement, inspection };
1533
1652
  toggleSidebar(true);
1534
1653
  } else if (searchReturn) {
1535
1654
  toggleSidebar(searchReturn.sidebar);
@@ -1538,10 +1657,43 @@ $("#search").oninput = () => {
1538
1657
  renderNav();
1539
1658
  };
1540
1659
  $("#search-clear").onclick=()=>{$("#search").value="";$("#search").oninput();$("#search").focus()};
1660
+ function moduleRows() {
1661
+ if ($("#sidebar").hidden) return [];
1662
+ return [...$("#modules").querySelectorAll("button:is(.tree-row, .group-name):not(:disabled)")].filter(el => el.offsetParent !== null);
1663
+ }
1541
1664
  $("#search").onkeydown = (e) => {
1542
- if (e.key === "Enter")
1665
+ if (e.key === "Enter") {
1543
1666
  $("#modules .search-result")?.click();
1667
+ return;
1668
+ }
1669
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1670
+ const rows = moduleRows();
1671
+ if (!rows.length) return;
1672
+ e.preventDefault();
1673
+ e.stopPropagation();
1674
+ (e.key === "ArrowDown" ? rows[0] : rows.at(-1)).focus();
1675
+ }
1544
1676
  };
1677
+ $("#modules").addEventListener("keydown", (e) => {
1678
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
1679
+ const rows = moduleRows();
1680
+ if (!rows.length) return;
1681
+ const current = e.target.closest(".scope-row, .group-row")?.querySelector("button:is(.tree-row, .group-name)") ?? e.target;
1682
+ const index = rows.indexOf(current);
1683
+ if (index < 0) return;
1684
+ e.preventDefault();
1685
+ e.stopPropagation();
1686
+ if (e.key === "ArrowDown") {
1687
+ if (index + 1 < rows.length) rows[index + 1].focus();
1688
+ else if (!$(".search-field").hidden) $("#search").focus();
1689
+ } else if (index > 0) {
1690
+ rows[index - 1].focus();
1691
+ } else if (!$(".search-field").hidden) {
1692
+ $("#search").focus();
1693
+ } else {
1694
+ rows.at(-1).focus();
1695
+ }
1696
+ });
1545
1697
  $("#minus").onclick = () => zoom(view.scale / 1.25);
1546
1698
  $("#plus").onclick = () => zoom(view.scale * 1.25);
1547
1699
  function resizeViewport() {
@@ -1569,10 +1721,27 @@ function relationshipGraph(data, measured) {
1569
1721
  return sourceRelationships([...entries].map(([path,imports])=>({path,imports})));
1570
1722
  }
1571
1723
  function applyTokenManifest(data) {
1572
- const previous = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
1724
+ const previous = tokenManifest ?? catalog ?? manifest;
1573
1725
  const entering = !tokenManifest || tokenManifest.directory !== data.directory;
1574
1726
  tokenManifest = { ...data, tokenGroups: groupTokens(data.tokens ?? []) };
1575
- reviewManifest = null;
1727
+ if (entering) {
1728
+ tokenList = false;
1729
+ tokenSearchWasBoard = false;
1730
+ }
1731
+ if (!data.tokenBoard) {
1732
+ tokenList = true;
1733
+ tokenSearchWasBoard = false;
1734
+ tokenHeight = 0;
1735
+ }
1736
+ canvas.width = canvas.width;
1737
+ boardLayer.update([], [], data);
1738
+ boardLayer.camera(view, false);
1739
+ boardLayer.tokens(data.tokenBoard, height => {
1740
+ tokenHeight=height;
1741
+ world={x:0,y:0,width:data.tokenBoard.width,height};
1742
+ if (entering) frame(world);
1743
+ requestDraw();
1744
+ });
1576
1745
  scopeRequest = data.scope;
1577
1746
  catalog = null;
1578
1747
  if (entering) {
@@ -1594,29 +1763,7 @@ function applyTokenManifest(data) {
1594
1763
  if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
1595
1764
  }
1596
1765
  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();
1766
+ commentUI.render();
1620
1767
  renderNav();
1621
1768
  requestDraw();
1622
1769
  }
@@ -1625,7 +1772,7 @@ async function applyManifest(data, force = false) {
1625
1772
  if (force || tokenManifest?.directory !== data.directory || tokenManifest?.revision !== data.revision) applyTokenManifest(data);
1626
1773
  return;
1627
1774
  }
1628
- const leavingOverlayView = !!tokenManifest || !!reviewManifest;
1775
+ const leavingOverlayView = !!tokenManifest;
1629
1776
  const changedRoot = initializedDirectory !== data.directory, changedScope = initializedScope !== data.scope || initializedFrame !== onlyFrame;
1630
1777
  const first = changedRoot || changedScope;
1631
1778
  if (!force && !first && !leavingOverlayView && manifest.revision === data.revision)
@@ -1657,7 +1804,6 @@ async function applyManifest(data, force = false) {
1657
1804
  window.__adg.ready = false;
1658
1805
  if (first) {
1659
1806
  cache.clear();
1660
- labelLayer.clear();
1661
1807
  queued = [];
1662
1808
  selected = null;
1663
1809
  selectedId = null;
@@ -1669,9 +1815,9 @@ async function applyManifest(data, force = false) {
1669
1815
  }
1670
1816
  const versionTheme = effectiveTheme;
1671
1817
  const link = initializedDirectory === undefined && !fixtureState ? initialLink : null;
1672
- const entry = !changedRoot && scopeRequest===data.scope ? scopeEntry : null;
1818
+ const entry = (!changedRoot || leavingOverlayView) && scopeRequest===data.scope ? scopeEntry : null;
1673
1819
  const groupTitle = groups[active]?.title;
1674
- restorePacking(data.packing);
1820
+
1675
1821
  const previous=manifest, results=new Array(data.assets.length), signal=refreshController?.signal;
1676
1822
  let next=0,publishFrame=0,streamView=null,streamMoved=false,publishedCount=0,nextPublish=1;
1677
1823
  const streaming=first && !leavingOverlayView;
@@ -1733,7 +1879,6 @@ async function applyManifest(data, force = false) {
1733
1879
  for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
1734
1880
  manifest = { ...data, assets: results, relationships:relationshipGraph(data,results), renderTheme: versionTheme };
1735
1881
  tokenManifest = null;
1736
- reviewManifest = null;
1737
1882
  // Early streamed worlds can use a much larger camera scale. Discard those
1738
1883
  // raster intermediates so the completed world starts at its exact final scale.
1739
1884
  if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
@@ -1747,7 +1892,7 @@ async function applyManifest(data, force = false) {
1747
1892
  for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
1748
1893
  $("#app-directory").title=data.directory||'';
1749
1894
  document.title = `${data.label} — Agent Design Gallery`;
1750
- if (first) {
1895
+ if (first || leavingOverlayView) {
1751
1896
  const target = entry ? entry.target : link ?? data.selection;
1752
1897
  if (!fixtureState) restoreSelection(target);
1753
1898
  const saved = data.selection;
@@ -1759,7 +1904,8 @@ async function applyManifest(data, force = false) {
1759
1904
  else if (entry?.target || (link && (onlyFrame || !(reload && sameSelection && data.view)))) {
1760
1905
  const target = selectedBox() || currentItem() || groups[active] || world;
1761
1906
  frame(target, selected ? 24 : 0);
1762
- } else if (data.view) view = data.view;
1907
+ } else if (leavingOverlayView && previous?.directory === data.directory && previous.scope === data.scope && previous.view) view = previous.view;
1908
+ else if (data.view) view = data.view;
1763
1909
  else if (!streamMoved) frame(world);
1764
1910
  } else if (groupTitle) {
1765
1911
  const index = groups.findIndex(group=>group.title===groupTitle);
@@ -1789,13 +1935,20 @@ async function applyManifest(data, force = false) {
1789
1935
  initializedFrame=onlyFrame;
1790
1936
  initialLink=null;
1791
1937
  scopeEntry=null;
1792
- if(data.features?.persistedMetadata && !onlyFrame)cacheWrite(`catalog?context=${encodeURIComponent(metadataContext())}`,{packing:packingSnapshot()});
1793
1938
  selection();
1794
1939
  if (pendingNavigation) {
1795
1940
  const action = pendingNavigation;
1796
1941
  pendingNavigation = null;
1797
1942
  action();
1798
1943
  }
1944
+ if (commentNavigation && (data.scope === commentNavigation.scope || !data.loading)) {
1945
+ const found = focusBoardComment(commentNavigation.thread);
1946
+ if (found || !data.loading) {
1947
+ commentNavigation.resolve(found);
1948
+ commentNavigation = null;
1949
+ }
1950
+ }
1951
+ commentUI.render();
1799
1952
  requestDraw();
1800
1953
  }
1801
1954
  function updateChoices() {
@@ -1806,15 +1959,47 @@ function updateChoices() {
1806
1959
  }
1807
1960
  }
1808
1961
  for(const button of $("#backgrounds").children) button.onclick=()=>{backgroundChoice=button.dataset.background;updateChoices();requestDraw()};
1962
+ function menuItems(menu) {
1963
+ return [...menu.querySelectorAll('button:not(:disabled)')].filter(el => !el.hidden && el.offsetParent !== null);
1964
+ }
1809
1965
  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"));
1966
+ const menu = $("#"+id), btn = $("#"+trigger);
1967
+ menu.addEventListener('toggle',event=>{
1968
+ btn.setAttribute(id === "more-menu" ? "aria-expanded" : "aria-pressed", String(event.newState === "open"));
1812
1969
  if(event.newState==='open') {
1813
1970
  for(const other of document.querySelectorAll(':popover-open')) if(other.id!==id) other.hidePopover();
1814
1971
  hideTooltip();positionZoomMenu();
1815
1972
  }
1816
1973
  requestDraw();
1817
1974
  });
1975
+ menu.addEventListener('keydown', event => {
1976
+ const items = menuItems(menu);
1977
+ if (!items.length) return;
1978
+ const index = items.indexOf(document.activeElement);
1979
+ const next = event.key === 'ArrowDown' ? items[index < 0 ? 0 : (index + 1) % items.length]
1980
+ : event.key === 'ArrowUp' ? items[index <= 0 ? items.length - 1 : index - 1]
1981
+ : event.key === 'Home' ? items[0]
1982
+ : event.key === 'End' ? items.at(-1)
1983
+ : null;
1984
+ if (!next) return;
1985
+ event.preventDefault();
1986
+ event.stopPropagation();
1987
+ next.focus();
1988
+ });
1989
+ btn.addEventListener('keydown', event => {
1990
+ if (!menu.matches(':popover-open')) return;
1991
+ const items = menuItems(menu);
1992
+ if (!items.length) return;
1993
+ if (event.key === 'ArrowDown' || event.key === 'Home') {
1994
+ event.preventDefault();
1995
+ event.stopPropagation();
1996
+ items[0].focus();
1997
+ } else if (event.key === 'ArrowUp' || event.key === 'End') {
1998
+ event.preventDefault();
1999
+ event.stopPropagation();
2000
+ items.at(-1).focus();
2001
+ }
2002
+ });
1818
2003
  }
1819
2004
  let tooltipTimer;
1820
2005
  function hideTooltip() { clearTimeout(tooltipTimer);if (!$("#tooltip").hidden) { $("#tooltip").hidden=true;requestDraw(); } }
@@ -1833,12 +2018,29 @@ function bindTooltip(button, trailing = false) {
1833
2018
  }
1834
2019
  for(const button of document.querySelectorAll('[data-tooltip]')) bindTooltip(button);
1835
2020
  $("#keys-close").onclick=()=>$("#keys").close();
2021
+ $("#keys").addEventListener('click', event => {
2022
+ if (event.target !== $("#keys")) return;
2023
+ const r = $("#keys").getBoundingClientRect();
2024
+ if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) {
2025
+ $("#keys").close();
2026
+ }
2027
+ });
1836
2028
  for(const dialog of document.querySelectorAll('dialog')) {
1837
2029
  dialog.addEventListener('toggle', () => requestDraw());
1838
2030
  dialog.addEventListener('close',()=>{viewport.focus({preventScroll:true});requestDraw()});
1839
2031
  }
1840
2032
  document.addEventListener('keydown',event=>{
1841
- if(event.key==='?'&&!event.target.matches('input,textarea')&&!document.querySelector('dialog[open]')) {event.preventDefault();hideTooltip();$("#keys").showModal()}
2033
+ if (event.key !== '?' || event.metaKey || event.ctrlKey || event.altKey || event.target.matches('input,textarea,select,[contenteditable]')) return;
2034
+ if ($("#keys").open) {
2035
+ event.preventDefault();
2036
+ $("#keys").close();
2037
+ return;
2038
+ }
2039
+ if (!document.querySelector('dialog[open]')) {
2040
+ event.preventDefault();
2041
+ hideTooltip();
2042
+ $("#keys").showModal();
2043
+ }
1842
2044
  });
1843
2045
  async function applyFixture() {
1844
2046
  const state=fixtureState;if(!state)return;
@@ -1877,14 +2079,6 @@ async function refresh(force = false) {
1877
2079
  fetching = true;refreshController=new AbortController();
1878
2080
  try {
1879
2081
  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
2082
  const query=new URLSearchParams({context:metadataContext(),theme:effectiveTheme,scope:scopeRequest});
1889
2083
  if (strictRoute) query.set('strict', '1');
1890
2084
  if (onlyFrame) query.set('frame', onlyFrame);
@@ -1911,14 +2105,19 @@ async function refresh(force = false) {
1911
2105
  }
1912
2106
  await refresh();
1913
2107
  if(fixtureState) { try { await applyFixture(); } catch(e) { error(e.message); } }
1914
- if ((reviewManifest || tokenManifest || manifest) && !isUnauthorized()) {
2108
+ if ((tokenManifest || manifest) && !isUnauthorized()) {
1915
2109
  const events = new EventSource(keyURL('events'));
2110
+ const refreshComments = () => commentUI.refresh().catch(err => error(err.message));
2111
+ events.addEventListener('comments', refreshComments);
2112
+ events.addEventListener('open', refreshComments);
1916
2113
  window.addEventListener('adg-unauthorized', () => events.close(), { once: true });
1917
2114
  events.onmessage = (e) => {
1918
2115
  const data = JSON.parse(e.data);
1919
2116
  if (data.error) error(data.error);
1920
- else if (data.annotations) annotationUI.refresh().catch(err => error(err.message));
1921
- else void refresh();
2117
+ else {
2118
+ void refresh();
2119
+ if (data.changed && commentCatalogLoaded) void refreshCommentCatalog();
2120
+ }
1922
2121
  };
1923
2122
  events.onerror = async () => {
1924
2123
  try {
@@ -1927,21 +2126,31 @@ if ((reviewManifest || tokenManifest || manifest) && !isUnauthorized()) {
1927
2126
  error('Local server disconnected. Reconnecting…');
1928
2127
  } catch (e) { error(e.message); }
1929
2128
  };
2129
+ void refreshComments().then(async () => {
2130
+ const number = new URL(location.href).searchParams.get('comment');
2131
+ if (number) {
2132
+ await refreshCommentCatalog();
2133
+ void commentUI.openLink(number);
2134
+ }
2135
+ });
1930
2136
  }
1931
2137
 
1932
2138
  document.addEventListener("keydown", (e) => {
1933
2139
  if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
1934
- if (reviewManifest) return;
1935
2140
  e.preventDefault();
1936
2141
  $("#search").focus();
1937
2142
  return;
1938
2143
  }
1939
2144
  if (e.key !== "Escape" || document.querySelector("dialog[open]")) return;
1940
2145
  if (document.querySelector(":popover-open")) return;
1941
- if (annotationUI.cancelMove()) return;
1942
- if (reviewManifest) return;
2146
+ if (e.defaultPrevented) return;
1943
2147
  if (tokenManifest) {
1944
- if ($('#search').value) $('#search-clear').click();
2148
+ if ($('#search').value) {
2149
+ e.preventDefault();
2150
+ $('#search-clear').click();
2151
+ } else if (document.activeElement === $('#search')) {
2152
+ viewport.focus({ preventScroll: true });
2153
+ }
1945
2154
  return;
1946
2155
  }
1947
2156
  if (searchReturn) {
@@ -1949,11 +2158,27 @@ document.addEventListener("keydown", (e) => {
1949
2158
  searchReturn = null;
1950
2159
  $("#search").value = "";
1951
2160
  toggleSidebar(old.sidebar);
1952
- ({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
1953
- selection();
1954
- commit(old.view);
1955
- } else clearSelection();
2161
+ if (old.scope === initializedScope) {
2162
+ ({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
2163
+ selection();
2164
+ commit(old.view);
2165
+ } else {
2166
+ renderNav();
2167
+ }
2168
+ } else if ($("#search").value) {
2169
+ $("#search").value = "";
2170
+ $("#search").oninput();
2171
+ } else if (selected) {
2172
+ clearSelection();
2173
+ } else if (!$("#back").disabled) {
2174
+ back();
2175
+ }
1956
2176
  viewport.focus({ preventScroll: true });
1957
2177
  });
1958
2178
 
1959
2179
  initSwitcher();
2180
+
2181
+ $('#token-list-toggle').onclick = () => {
2182
+ $('#more-menu').hidePopover();
2183
+ setTokenList(!tokenList);
2184
+ };