@floless/app 0.113.1 → 0.113.2

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.
@@ -25,6 +25,7 @@
25
25
 
26
26
  const $app = document.getElementById('app');
27
27
  const $switch = document.getElementById('mode-switch');
28
+ const $workflowTab = $switch.querySelector('button[data-mode="workflows"]');
28
29
  const $landing = document.getElementById('ws-landing');
29
30
  const $project = document.getElementById('ws-project');
30
31
  const $spine = document.getElementById('ws-spine');
@@ -265,9 +266,10 @@
265
266
  // "none yet" ONLY when this is null (see the empty state in renderLanding)
266
267
  let archived = []; // archived projects (the "Trash") — listed under a collapsed section on the landing
267
268
  // Installed workspace apps, in descriptor order — `{ appId, templateId, ambiguous }` per entry.
268
- // Populated from /api/apps in loadProjects(): the set = apps flagged workspace===true whose LINEAGE
269
- // ROOT has a WORKSPACE_APPS descriptor (an app whose root we have no descriptor for is skipped with
270
- // a console note — never a broken open).
269
+ // Populated from /api/apps in loadProjects(): the set = installed apps whose LINEAGE ROOT has a
270
+ // WORKSPACE_APPS descriptor. The installed source's `workspace` flag is deliberately not an
271
+ // admission gate: bundled workflows gain it one update at a time, and narrowing on it made each
272
+ // not-yet-updated sibling create card disappear during normal partial adoption (#362).
271
273
  //
272
274
  // Two ids, because a rename separates them and each half is load-bearing: `appId` is the LIVE app a
273
275
  // card creates on (post the descriptor key after a rename and the server rightly 404s "not
@@ -291,6 +293,32 @@
291
293
  // The pre-/api/apps default (and the failure fallback): assume each descriptor's canonical app is
292
294
  // the installed one. Unambiguous by construction — one entry per descriptor, appId === templateId.
293
295
  const wsDefaultAppEntries = () => Object.keys(WORKSPACE_APPS).map((id) => ({ appId: id, templateId: id, ambiguous: false }));
296
+ function installedWorkspaceAppEntries(apps) {
297
+ // Group every installed app whose lineage root the client can render. A known descriptor plus a
298
+ // live installed source is sufficient authority for today's first-party create cards; requiring
299
+ // the lagging source flag as a third vote breaks partial updates (#362). Still call out a FLAGGED
300
+ // unknown root because that means a workspace-capable app exists that this client cannot present.
301
+ const byRoot = new Map();
302
+ for (const a of apps || []) {
303
+ if (!a || typeof a.id !== 'string' || !a.id) continue;
304
+ const root = a.templateId || a.id;
305
+ if (!WORKSPACE_APPS[root]) {
306
+ if (a.workspace === true) {
307
+ console.warn(`[workspaces] app "${a.id}" is flagged workspace but its lineage root "${root}" has no client descriptor — skipping its create card`);
308
+ }
309
+ continue;
310
+ }
311
+ if (!byRoot.has(root)) byRoot.set(root, []);
312
+ byRoot.get(root).push(a.id);
313
+ }
314
+ return Object.keys(WORKSPACE_APPS).filter((root) => byRoot.has(root)).map((root) => {
315
+ // Sorted, so which app a card targets is stable across loads rather than dependent on the
316
+ // order `aware app list` happened to return. The canonical install wins when present: it is
317
+ // the one the user has not deliberately made a variant of.
318
+ const ids = byRoot.get(root).slice().sort();
319
+ return { appId: ids.indexOf(root) >= 0 ? root : ids[0], templateId: root, ambiguous: ids.length > 1 };
320
+ });
321
+ }
294
322
  let wsAppEntries = wsDefaultAppEntries();
295
323
  let current = null; // the open project (null = landing)
296
324
 
@@ -338,9 +366,51 @@
338
366
  if (!ws || !current) { if (bridge.clearWorkspaceGuide) bridge.clearWorkspaceGuide(); }
339
367
  else syncWorkspaceGuide();
340
368
  }
341
- function setMode(m) {
369
+ let modeChangeSequence = 0;
370
+ function showWorkflowOpening(opening) {
371
+ if (!$workflowTab) return;
372
+ $workflowTab.toggleAttribute('aria-busy', opening);
373
+ $workflowTab.toggleAttribute('aria-disabled', opening);
374
+ if (opening) {
375
+ $workflowTab.setAttribute('aria-label', 'Opening Workflows');
376
+ $workflowTab.innerHTML = '<span class="rtn-spinner" aria-hidden="true"></span><span>Opening Workflows…</span>';
377
+ } else {
378
+ $workflowTab.removeAttribute('aria-label');
379
+ $workflowTab.textContent = 'Workflows';
380
+ }
381
+ }
382
+ async function setMode(m) {
342
383
  const next = m === 'workspaces' ? 'workspaces' : 'workflows';
384
+ // The still-selected Workspaces tab remains the cancellation path. Re-activating the pending
385
+ // Workflows tab would only start another read, supersede the useful one, and extend the wait.
386
+ if (next === 'workflows' && $workflowTab?.getAttribute('aria-busy') === 'true') return;
387
+ const sequence = ++modeChangeSequence;
343
388
  const changed = next !== mode;
389
+ if (next !== 'workflows') {
390
+ $switch.removeAttribute('aria-busy');
391
+ showWorkflowOpening(false);
392
+ }
393
+ // Keep the Workspaces surface visible until publication availability has been re-read. This
394
+ // prevents a stale workflow card from briefly advertising a project that was just archived, and
395
+ // the sequence guard prevents a slower response from overriding a newer mode choice.
396
+ if (changed && next === 'workflows' && bridge.refreshCurrentWorkflow) {
397
+ $switch.setAttribute('aria-busy', 'true');
398
+ showWorkflowOpening(true);
399
+ try {
400
+ await bridge.refreshCurrentWorkflow();
401
+ } catch (error) {
402
+ if (sequence === modeChangeSequence) {
403
+ showToast('Couldn’t refresh the workflow: ' + (error && error.message ? error.message : String(error)), 'warn');
404
+ }
405
+ return;
406
+ } finally {
407
+ if (sequence === modeChangeSequence) {
408
+ $switch.removeAttribute('aria-busy');
409
+ showWorkflowOpening(false);
410
+ }
411
+ }
412
+ if (sequence !== modeChangeSequence) return;
413
+ }
344
414
  mode = next;
345
415
  try { localStorage.setItem(LS_MODE, mode); } catch { /* private mode */ }
346
416
  applyMode();
@@ -424,11 +494,11 @@
424
494
  console.warn('[workspaces] archived list failed to load: ' + (err && err.message || err));
425
495
  }
426
496
  if (archivedSig(archived) !== archivedBefore) renderLanding();
427
- // Which workspace apps to offer a create card for: those flagged workspace===true on /api/apps
428
- // whose LINEAGE ROOT we also know how to render (have a WORKSPACE_APPS descriptor). Matching on
429
- // the root, not the raw id, is what keeps the cards alive across a rename — a renamed steel-model
430
- // is still flagged workspace, but under a key no descriptor answers to. /api/apps already carries
431
- // `templateId` per app (the picker's fork/update badges read the same field), so no extra call.
497
+ // Which workspace apps to offer a create card for: installed apps whose LINEAGE ROOT we know how
498
+ // to render (have a WORKSPACE_APPS descriptor). Matching on the root, not the raw id, keeps cards
499
+ // alive across rename/duplicate. Do not narrow on the installed source's `workspace` flag: an
500
+ // update adds it to one bundled workflow at a time, so it is expected to be mixed during adoption.
501
+ // /api/apps already carries `templateId` per app (the picker uses the same field), so no extra call.
432
502
  // Keep descriptor order for a stable card order. A load failure RE-WIDENS the entries to the
433
503
  // descriptor keys (the catch assigns them): still usable, and a card for something uninstalled is
434
504
  // refused by the server on click.
@@ -437,29 +507,10 @@
437
507
  try {
438
508
  const { apps } = await api('/api/apps');
439
509
  if (stale()) return;
440
- // Group the live workspace apps by lineage root, so one descriptor yields one card even when
441
- // several installed apps share a root (an original plus a duplicate, say).
442
- const byRoot = new Map();
443
- for (const a of apps || []) {
444
- if (!a || a.workspace !== true) continue;
445
- const root = a.templateId || a.id;
446
- if (!WORKSPACE_APPS[root]) {
447
- console.warn(`[workspaces] app "${a.id}" is flagged workspace but its lineage root "${root}" has no client descriptor — skipping its create card`);
448
- continue;
449
- }
450
- if (!byRoot.has(root)) byRoot.set(root, []);
451
- byRoot.get(root).push(a.id);
452
- }
453
- wsAppEntries = Object.keys(WORKSPACE_APPS).filter((root) => byRoot.has(root)).map((root) => {
454
- // Sorted, so which app a card targets is stable across loads rather than dependent on the
455
- // order `aware app list` happened to return. The canonical install wins when present: it is
456
- // the one the user has not deliberately made a variant of.
457
- const ids = byRoot.get(root).slice().sort();
458
- return { appId: ids.indexOf(root) >= 0 ? root : ids[0], templateId: root, ambiguous: ids.length > 1 };
459
- });
460
- // Hardening: /api/apps loaded but flagged NONE of our known workspace apps (a transient
461
- // appWorkspace read blip returning false for all). Rather than render zero create cards, fall
462
- // back to the descriptor keys — the same usable default a full /api/apps failure lands on.
510
+ wsAppEntries = installedWorkspaceAppEntries(apps);
511
+ // Hardening: /api/apps loaded but reported NONE of our known installed workspace apps (a
512
+ // transient empty/read blip). Rather than render zero create cards, fall back to the descriptor
513
+ // keys — the same usable default a full /api/apps failure lands on.
463
514
  if (wsAppEntries.length === 0 && Object.keys(WORKSPACE_APPS).length > 0) {
464
515
  wsAppEntries = wsDefaultAppEntries();
465
516
  }
@@ -592,13 +643,10 @@
592
643
  (again || firstCard)?.focus({ focusVisible: true });
593
644
  }
594
645
 
595
- function renderLanding() {
596
- let html = `<div class="ws-head"><div class="ws-head-text"><h2>Workspaces</h2>` +
597
- `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>` +
598
- `<button type="button" class="ws-import-btn" id="ws-import-project" data-tip="Restore a project from an exported .zip file">↓ Import project…</button></div>`;
646
+ function workspaceCreateEntries(entries) {
599
647
  // Create affordances stay docked at the top, separate from existing projects. Drawing-first
600
648
  // entries lead; importing the current Workflows model stays last because it is a different mode.
601
- const createEntries = wsAppEntries
649
+ return entries
602
650
  .flatMap((entry) => {
603
651
  const d = WORKSPACE_APPS[entry.templateId];
604
652
  const actions = d && Array.isArray(d.createActions) ? d.createActions : [];
@@ -609,28 +657,39 @@
609
657
  if (a.action.kind !== 'current' && b.action.kind === 'current') return -1;
610
658
  return 0;
611
659
  });
660
+ }
661
+
662
+ function workspaceCreateCardHtml(entry, action) {
663
+ const isDrawing = action.kind === 'drawing';
664
+ // Name the target workflow ONLY when the root has more than one live app behind it, so the
665
+ // ordinary card stays clean and the extra line means something wherever it does appear. It
666
+ // must also go on the aria-label: the button's own aria-label REPLACES the accessible name
667
+ // computed from its children, so a descendant span alone is silent to a screen reader.
668
+ const target = entry.ambiguous ? entry.appId : '';
669
+ return `<button type="button" class="ws-seed${isDrawing ? ' ws-seed-drop' : ''}" ` +
670
+ `aria-label="${escapeAttr((action.label || action.headline) + (target ? ` (on the ${target} workflow)` : ''))}" ` +
671
+ `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}"` +
672
+ (isDrawing ? ` data-seed-drop="${escapeAttr(entry.appId)}"` : '') +
673
+ `>` +
674
+ `<span class="plus">+</span>` +
675
+ `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
676
+ (action.capability ? `<span class="ws-seed-capability">${escapeHtml(action.capability)}</span>` : '') +
677
+ `<span class="ws-seed-sub">${escapeHtml(action.sub)}</span>` +
678
+ (target
679
+ ? `<span class="ws-seed-target" data-tip="You have more than one of these workflows installed.\nThis card creates on:\n${escapeAttr(target)}">On ${escapeHtml(target)}</span>`
680
+ : '') +
681
+ `</button>`;
682
+ }
683
+
684
+ function renderLanding() {
685
+ let html = `<div class="ws-head"><div class="ws-head-text"><h2>Workspaces</h2>` +
686
+ `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>` +
687
+ `<button type="button" class="ws-import-btn" id="ws-import-project" data-tip="Restore a project from an exported .zip file">↓ Import project…</button></div>`;
688
+ const createEntries = workspaceCreateEntries(wsAppEntries);
612
689
  if (createEntries.length) {
613
690
  html += `<div class="ws-create-grid">`;
614
691
  for (const { entry, action } of createEntries) {
615
- const isDrawing = action.kind === 'drawing';
616
- // Name the target workflow ONLY when the root has more than one live app behind it, so the
617
- // ordinary card stays clean and the extra line means something wherever it does appear. It
618
- // must also go on the aria-label: the button's own aria-label REPLACES the accessible name
619
- // computed from its children, so a descendant span alone is silent to a screen reader.
620
- const target = entry.ambiguous ? entry.appId : '';
621
- html += `<button type="button" class="ws-seed${isDrawing ? ' ws-seed-drop' : ''}" ` +
622
- `aria-label="${escapeAttr((action.label || action.headline) + (target ? ` (on the ${target} workflow)` : ''))}" ` +
623
- `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}"` +
624
- (isDrawing ? ` data-seed-drop="${escapeAttr(entry.appId)}"` : '') +
625
- `>` +
626
- `<span class="plus">+</span>` +
627
- `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
628
- (action.capability ? `<span class="ws-seed-capability">${escapeHtml(action.capability)}</span>` : '') +
629
- `<span class="ws-seed-sub">${escapeHtml(action.sub)}</span>` +
630
- (target
631
- ? `<span class="ws-seed-target" data-tip="You have more than one of these workflows installed.\nThis card creates on:\n${escapeAttr(target)}">On ${escapeHtml(target)}</span>`
632
- : '') +
633
- `</button>`;
692
+ html += workspaceCreateCardHtml(entry, action);
634
693
  }
635
694
  html += `</div>`;
636
695
  }
@@ -781,8 +840,11 @@
781
840
  }
782
841
  // A create card needs BOTH halves of its identity: one workflow can declare several create actions
783
842
  // (steel declares two), so data-seed-app alone would match the wrong card.
784
- const seed = el.getAttribute('data-seed-app');
785
- if (seed != null) return `[data-seed-app="${escapeAttr(seed)}"][data-seed-action="${escapeAttr(el.getAttribute('data-seed-action') || '')}"]`;
843
+ // The lineage root is the stable identity across a workflow rename; data-seed-app is the live
844
+ // action target and can change during an autonomous apps-changed repaint. Keying focus on it
845
+ // would drop a keyboard user to <body> precisely when the workflow moves (#362 review).
846
+ const seed = el.getAttribute('data-seed-template');
847
+ if (seed != null) return `[data-seed-template="${escapeAttr(seed)}"][data-seed-action="${escapeAttr(el.getAttribute('data-seed-action') || '')}"]`;
786
848
  if (el.classList.contains('ws-archived-summary')) return '.ws-archived-summary';
787
849
  return null;
788
850
  }
@@ -4651,20 +4713,51 @@
4651
4713
  };
4652
4714
 
4653
4715
  let versions = []; // last-rendered ledger (newest first)
4654
- // Whether the semantic comparison applies to THIS project — the SERVER's answer, so the rule lives
4655
- // in one place instead of being duplicated here. Today that answer is "is this app steel-model",
4656
- // decided from the live app id; it is NOT contract-type aware (that work is deferred — see
4657
- // `appSupportsDiff`'s header server-side). Set on every versions fetch; the conservative default is
4658
- // false so a failed or never-run fetch shows no toggle rather than a dead one.
4716
+ // Legacy project-level comparison answer for older servers/clients. Current servers additionally
4717
+ // authorize each exact row/base pair; the conservative default is false so a failed or never-run
4718
+ // fetch shows no toggle rather than a dead one.
4659
4719
  let histDiffSupported = false;
4720
+ let histDiffEligibleVersions = null; // one shared whitelist avoids an O(N²) copy on every row
4660
4721
  let expandDiffOnce = null; // { projectId, n }: successful Approve opens only that project's new row
4661
4722
 
4662
- function changeCellHtml(v, canDiff) {
4723
+ const hasOwnField = (obj, key) => !!obj && Object.prototype.hasOwnProperty.call(obj, key);
4724
+ function historyDiffMeta(v) {
4725
+ const n = Number(v.n);
4726
+ const explicit = hasOwnField(v, 'diffSupported');
4727
+ if (explicit) {
4728
+ // Row metadata is an authorization tuple. Every component must be the exact transport type;
4729
+ // coercing "1" or accepting a missing whitelist would turn malformed state into an affordance.
4730
+ const transportedBases = Array.isArray(v.diffBases) ? v.diffBases : histDiffEligibleVersions;
4731
+ if (v.diffSupported !== true || typeof v.diffBase !== 'number' || !Number.isInteger(v.diffBase)
4732
+ || v.diffBase < 1 || v.diffBase >= n || !Array.isArray(transportedBases)
4733
+ || transportedBases.some((base) => typeof base !== 'number' || !Number.isInteger(base) || base < 1)
4734
+ || !transportedBases.includes(v.diffBase)) {
4735
+ return { canDiff: false, base: null, bases: [] };
4736
+ }
4737
+ return {
4738
+ canDiff: n > 1,
4739
+ base: v.diffBase,
4740
+ bases: [...new Set(transportedBases.filter((base) => base < n))],
4741
+ };
4742
+ }
4743
+ // Older server: preserve the former project-level gate and summary-derived default. This branch is
4744
+ // intentionally absent as soon as ANY row-level field is present—even explicit false/null wins.
4745
+ const summaryBase = v.changeSummary && Number.isInteger(Number(v.changeSummary.from))
4746
+ ? Number(v.changeSummary.from)
4747
+ : null;
4748
+ const isApprovalBaseline = v.kind === 'approve' && v.changeSummary && v.changeSummary.from == null;
4749
+ return {
4750
+ canDiff: histDiffSupported && n > 1 && !isApprovalBaseline,
4751
+ base: summaryBase,
4752
+ bases: null,
4753
+ };
4754
+ }
4755
+
4756
+ function changeCellHtml(v, meta) {
4663
4757
  const s = v.changeSummary;
4664
4758
  const n = Number(v.n);
4665
- const summaryBase = s && Number.isInteger(Number(s.from)) ? Number(s.from) : null;
4666
- const baseAttr = summaryBase != null ? ` data-diff-base="${escapeAttr(String(summaryBase))}"` : '';
4667
- const toggle = canDiff
4759
+ const baseAttr = meta.base != null ? ` data-diff-base="${escapeAttr(String(meta.base))}"` : '';
4760
+ const toggle = meta.canDiff
4668
4761
  ? `<button type="button" class="hd-toggle" data-diff="${escapeAttr(String(n))}"${baseAttr} aria-expanded="false" ` +
4669
4762
  `aria-controls="hist-diff-${escapeAttr(String(n))}" aria-label="View detailed changes in version ${escapeAttr(String(n))}" ` +
4670
4763
  'data-tip="Show the complete member-by-member comparison">' +
@@ -4673,7 +4766,7 @@
4673
4766
  if (!s || !Array.isArray(s.bullets)) {
4674
4767
  return `<div class="hist-event">${escapeHtml(v.message)}</div>${toggle}`;
4675
4768
  }
4676
- const visible = s.bullets.slice(0, 4);
4769
+ const visible = meta.canDiff ? s.bullets.slice(0, 4) : s.bullets;
4677
4770
  const more = s.bullets.length - visible.length;
4678
4771
  const bullets = visible.map((x) => `<li>${escapeHtml(String(x))}</li>`).join('') +
4679
4772
  (more > 0 ? `<li class="hist-change-more">${escapeHtml(`${more} more change ${more === 1 ? 'category' : 'categories'} in the detailed view.`)}</li>` : '');
@@ -4693,23 +4786,22 @@
4693
4786
  // predecessor (n>1). v1 is the baseline, and a no-diff app (vectorize) gets NO toggle on ANY row —
4694
4787
  // an ABSENT control, never a disabled one (spec §4.4, mirroring the v1-baseline branch).
4695
4788
  //
4696
- // `histDiffSupported` is the SERVER's answer (`diffSupported` on the versions response) rather
4697
- // than this side's own reading of the app descriptor. Not because the server currently knows
4698
- // more — it applies the same "is this steel-model" rule — but because TWO copies of one rule
4699
- // drift, and when they drift this way the user gets a "View detailed changes" control that then
4700
- // answers 409: an affordance they can never satisfy. One answer, from the side that also owns the
4701
- // refusal. Defaults to the descriptor when the field is absent (an older server).
4702
- const isApprovalBaseline = v.kind === 'approve' && v.changeSummary && v.changeSummary.from == null;
4703
- const canDiff = histDiffSupported && Number(v.n) > 1 && !isApprovalBaseline;
4789
+ // Current row metadata authorizes an exact pair and a filtered base set. Only when it is wholly
4790
+ // absent do we use the server's legacy project-level answer (or the descriptor against an older
4791
+ // server); explicit false/malformed metadata never falls back.
4792
+ const meta = historyDiffMeta(v);
4793
+ const diffStatus = meta.canDiff
4794
+ ? `<div class="sr-only" data-diff-status="${escapeAttr(String(v.n))}" role="status" aria-live="polite"></div>`
4795
+ : '';
4704
4796
  const verRow = `<tr class="${v.current ? 'current' : ''}" data-ver="${escapeAttr(String(v.n))}">` +
4705
4797
  `<td><span class="ver${v.current ? ' cur' : ''}">v${escapeHtml(String(v.n))}</span></td>` +
4706
4798
  `<td class="htime">${escapeHtml(histWhen(v.ts))}</td>` +
4707
4799
  `<td><span class="hby">${avatarFor(v.author)}${escapeHtml(v.author)}</span></td>` +
4708
4800
  `<td>${gateBadge(v.gate, v.kind, v.n)}</td>` +
4709
- `<td class="change">${changeCellHtml(v, canDiff)}</td>` +
4801
+ `<td class="change">${changeCellHtml(v, meta)}${diffStatus}</td>` +
4710
4802
  `<td>${action}</td></tr>`;
4711
4803
  // The disclosure row is always emitted (hidden) so toggling is a pure show/hide + lazy fetch.
4712
- const diffRow = canDiff
4804
+ const diffRow = meta.canDiff
4713
4805
  ? `<tr class="hist-diff-row" data-diff-for="${escapeAttr(String(v.n))}" hidden><td colspan="6">` +
4714
4806
  `<div class="hd-panel" id="hist-diff-${escapeAttr(String(v.n))}" data-panel="${escapeAttr(String(v.n))}" role="region" ` +
4715
4807
  `aria-label="Detailed changes in version ${escapeAttr(String(v.n))}"></div></td></tr>`
@@ -4724,13 +4816,15 @@
4724
4816
  $wsHistory.innerHTML = '<div class="hist-note">Loading history…</div>';
4725
4817
  let rows = [];
4726
4818
  let approvedAt;
4819
+ let nextDiffSupported = false;
4820
+ let nextDiffEligibleVersions = null;
4727
4821
  try {
4728
4822
  const r = await api(`/api/projects/${encodeURIComponent(id)}/versions`);
4729
4823
  rows = Array.isArray(r.versions) ? r.versions : [];
4730
4824
  // Absent on an older server → fall back to the descriptor, which is the pre-change behaviour.
4731
- histDiffSupported = typeof r.diffSupported === 'boolean' ? r.diffSupported : !!(wsApp() && wsApp().diff);
4825
+ nextDiffSupported = typeof r.diffSupported === 'boolean' ? r.diffSupported : !!(wsApp() && wsApp().diff);
4826
+ nextDiffEligibleVersions = hasOwnField(r, 'diffEligibleVersions') ? r.diffEligibleVersions : null;
4732
4827
  approvedAt = r.approvedAt || undefined;
4733
- current.approvedAt = approvedAt; // re-sync — an in-editor autosave clears the sign-off server-side
4734
4828
  } catch (err) {
4735
4829
  showToast('Couldn’t load history: ' + ((err && err.message) || err), 'warn');
4736
4830
  if (current && current.id === id && !$wsHistory.hidden) {
@@ -4739,6 +4833,9 @@
4739
4833
  return;
4740
4834
  }
4741
4835
  if (!current || current.id !== id || $wsHistory.hidden) return; // switched away mid-await
4836
+ histDiffSupported = nextDiffSupported;
4837
+ histDiffEligibleVersions = nextDiffEligibleVersions;
4838
+ current.approvedAt = approvedAt; // re-sync — an in-editor autosave clears the sign-off server-side
4742
4839
  versions = rows;
4743
4840
  if (!rows.length) {
4744
4841
  // Empty = an inline-action banner (never a bare header row that reads as broken/loading).
@@ -4841,6 +4938,21 @@
4841
4938
  ];
4842
4939
  const diffBase = new Map(); // "<projectId>\0<n>" → chosen baseline (undefined = compare to the previous version)
4843
4940
  const baseKeyFor = (n) => (current && current.id ? current.id : '?') + '\0' + n; // project-scoped so a base pick can't bleed across projects sharing a version number
4941
+ function authorizedDiffBase(row, cached) {
4942
+ const meta = historyDiffMeta(row || {});
4943
+ if (Array.isArray(meta.bases)) return meta.bases.includes(cached) ? cached : meta.base;
4944
+ return cached != null ? cached : meta.base;
4945
+ }
4946
+ function selectableDiffBaseVersions(row, to, ledger) {
4947
+ const transported = row && Array.isArray(row.diffBases) ? row.diffBases : histDiffEligibleVersions;
4948
+ const explicit = row && hasOwnField(row, 'diffSupported')
4949
+ ? (Array.isArray(transported) ? new Set(transported.map(Number)) : new Set())
4950
+ : null;
4951
+ return ledger.filter((version) => {
4952
+ const n = Number(version.n);
4953
+ return n < to && (!explicit || explicit.has(n));
4954
+ });
4955
+ }
4844
4956
  const el = (tag, cls, text) => {
4845
4957
  const n = document.createElement(tag);
4846
4958
  if (cls) n.className = cls;
@@ -4934,6 +5046,9 @@
4934
5046
  btn.type = 'button';
4935
5047
  btn.dataset.baseFor = String(diff.to);
4936
5048
  btn.setAttribute('data-tip', 'Compare against an earlier version');
5049
+ btn.setAttribute('aria-haspopup', 'menu');
5050
+ btn.setAttribute('aria-expanded', 'false');
5051
+ btn.setAttribute('aria-controls', `hd-base-menu-${diff.to}`);
4937
5052
  btn.appendChild(el('span', null, `v${diff.from}`));
4938
5053
  btn.appendChild(el('span', 'hd-base-caret', '▾'));
4939
5054
  wrap.appendChild(btn);
@@ -4955,34 +5070,113 @@
4955
5070
  panel.appendChild(el('div', 'hd-tail', `${diff.unchanged} members unchanged`));
4956
5071
  }
4957
5072
  }
4958
- async function loadDiff(n, base) {
5073
+ function renderDiffUnavailable(panel) {
5074
+ panel.textContent = '';
5075
+ const status = el('div', 'hd-empty', 'Comparison unavailable');
5076
+ status.setAttribute('role', 'status');
5077
+ status.setAttribute('aria-live', 'polite');
5078
+ panel.appendChild(status);
5079
+ }
5080
+ function wellFormedDiff(diff) {
5081
+ if (!diff || typeof diff !== 'object' || Array.isArray(diff)
5082
+ || !Number.isInteger(diff.from) || diff.from < 0 || !Number.isInteger(diff.to) || diff.to < 1
5083
+ || diff.from >= diff.to
5084
+ || !diff.tonnage || typeof diff.tonnage !== 'object' || !Number.isFinite(diff.tonnage.netTons)
5085
+ || !Number.isInteger(diff.unchanged) || diff.unchanged < 0
5086
+ || !diff.warnings || typeof diff.warnings !== 'object') return false;
5087
+ const optionalString = (obj, key) => !Object.prototype.hasOwnProperty.call(obj, key)
5088
+ || typeof obj[key] === 'string';
5089
+ const ref = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
5090
+ && typeof value.id === 'string' && !!value.id
5091
+ && ['key', 'sheet', 'mark', 'profile', 'role'].every((key) => optionalString(value, key));
5092
+ const xform = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
5093
+ && ref(value.ref) && typeof value.from === 'string' && typeof value.to === 'string';
5094
+ const moved = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
5095
+ && ref(value.ref) && Number.isFinite(value.feet)
5096
+ && (!Object.prototype.hasOwnProperty.call(value, 'scaleUnknown') || typeof value.scaleUnknown === 'boolean');
5097
+ const connection = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
5098
+ && ref(value.ref) && typeof value.summary === 'string';
5099
+ const validators = { added: ref, removed: ref, resized: xform, moved, material: xform, connections: connection };
5100
+ if (!DIFF_GROUPS.every((group) =>
5101
+ Array.isArray(diff[group.key]) && diff[group.key].every(validators[group.key]))) return false;
5102
+ return ['duplicateKeys', 'ambiguousJoints', 'mergedAmbiguous'].every((key) =>
5103
+ !Object.prototype.hasOwnProperty.call(diff.warnings, key)
5104
+ || (Array.isArray(diff.warnings[key]) && diff.warnings[key].every((value) => typeof value === 'string')));
5105
+ }
5106
+ function decodeDiffResponse(response) {
5107
+ if (!response || typeof response !== 'object') throw new Error('invalid comparison response');
5108
+ const hasStatus = hasOwnField(response, 'status');
5109
+ if (hasStatus && response.status === 'unavailable') return { kind: 'unavailable' };
5110
+ if (hasStatus && response.status !== 'available') throw new Error('invalid comparison response status');
5111
+ if (!wellFormedDiff(response.diff)) throw new Error('invalid comparison response');
5112
+ // Old server compatibility. Its unreadable-v2 response was HTTP 200 with an inert diff, so the
5113
+ // warning—not the zero buckets—is the only honest discriminator.
5114
+ if (!hasStatus && response.diff.warnings.invalidModelV2) return { kind: 'unavailable' };
5115
+ return { kind: 'available', diff: response.diff };
5116
+ }
5117
+ function restoreDiffFocus(panel, n) {
5118
+ const target = panel.querySelector('.hd-base')
5119
+ || panel.querySelector('[data-diff-retry]')
5120
+ || $wsHistory.querySelector(`.hd-toggle[data-diff="${CSS.escape(String(n))}"]`);
5121
+ target?.focus({ focusVisible: true });
5122
+ }
5123
+ function focusDiffLoadingControl(n) {
5124
+ $wsHistory.querySelector(`.hd-toggle[data-diff="${CSS.escape(String(n))}"]`)
5125
+ ?.focus({ focusVisible: true });
5126
+ }
5127
+ async function loadDiff(n, base, opts) {
4959
5128
  const proj = current;
4960
5129
  if (!proj) return;
4961
5130
  const panel = $wsHistory.querySelector(`.hd-panel[data-panel="${CSS.escape(String(n))}"]`);
4962
5131
  if (!panel) return;
5132
+ const progress = $wsHistory.querySelector(`[data-diff-status="${CSS.escape(String(n))}"]`);
4963
5133
  const stamp = `${proj.id}:${n}:${base ?? ''}`; // guard against a stale response painting the wrong project/version/base
4964
5134
  panel.dataset.stamp = stamp;
5135
+ if (opts && opts.restoreBaseFocus) focusDiffLoadingControl(n);
5136
+ panel.setAttribute('aria-busy', 'true');
4965
5137
  panel.textContent = '';
4966
- panel.appendChild(el('div', 'hd-loading', 'Comparing…'));
4967
- let diff;
5138
+ const loading = el('div', 'hd-loading', 'Comparing…');
5139
+ panel.appendChild(loading);
5140
+ if (progress) progress.textContent = 'Comparing…';
5141
+ let decoded;
4968
5142
  try {
4969
5143
  const q = base != null ? `?base=${encodeURIComponent(base)}` : '';
4970
- diff = (await api(`/api/projects/${encodeURIComponent(proj.id)}/versions/${encodeURIComponent(n)}/diff${q}`)).diff;
5144
+ const response = await api(`/api/projects/${encodeURIComponent(proj.id)}/versions/${encodeURIComponent(n)}/diff${q}`);
5145
+ decoded = decodeDiffResponse(response);
5146
+ const expectedFrom = base != null ? base : (n === 1 ? 0 : n - 1);
5147
+ if (decoded.kind === 'available'
5148
+ && (decoded.diff.to !== n || decoded.diff.from !== expectedFrom)) {
5149
+ throw new Error('comparison response does not match the request');
5150
+ }
4971
5151
  } catch (err) {
4972
5152
  if (current && current.id === proj.id && panel.dataset.stamp === stamp) {
5153
+ panel.setAttribute('aria-busy', 'false');
5154
+ if (progress) progress.textContent = '';
5155
+ if (err && err.body && err.body.status === 'unavailable') {
5156
+ renderDiffUnavailable(panel);
5157
+ if (opts && opts.restoreBaseFocus) restoreDiffFocus(panel, n);
5158
+ return;
5159
+ }
4973
5160
  panel.textContent = '';
4974
5161
  const box = el('div', 'hd-err');
5162
+ box.setAttribute('role', 'status');
5163
+ box.setAttribute('aria-live', 'polite');
4975
5164
  box.appendChild(document.createTextNode('Couldn’t load the comparison' + (err && err.message ? ` — ${err.message}` : '') + ' — '));
4976
5165
  const retry = el('button', null, 'try again');
4977
5166
  retry.type = 'button';
4978
5167
  retry.dataset.diffRetry = String(n);
4979
5168
  box.appendChild(retry);
4980
5169
  panel.appendChild(box);
5170
+ if (opts && opts.restoreBaseFocus) restoreDiffFocus(panel, n);
4981
5171
  }
4982
5172
  return;
4983
5173
  }
4984
5174
  if (!current || current.id !== proj.id || panel.dataset.stamp !== stamp) return; // switched away / re-picked mid-await
4985
- renderDiffPanel(panel, diff);
5175
+ panel.setAttribute('aria-busy', 'false');
5176
+ if (progress) progress.textContent = '';
5177
+ if (decoded.kind === 'unavailable') renderDiffUnavailable(panel);
5178
+ else renderDiffPanel(panel, decoded.diff);
5179
+ if (opts && opts.restoreBaseFocus) restoreDiffFocus(panel, n);
4986
5180
  }
4987
5181
  function toggleDiff(btn) {
4988
5182
  const n = Number(btn.dataset.diff);
@@ -4999,17 +5193,21 @@
4999
5193
  const panel = row.querySelector('.hd-panel');
5000
5194
  if (panel && !panel.dataset.stamp) {
5001
5195
  const key = baseKeyFor(n);
5002
- let base = diffBase.get(key);
5003
- if (!diffBase.has(key) && btn.dataset.diffBase) {
5196
+ const version = versions.find((item) => Number(item.n) === n);
5197
+ let base = authorizedDiffBase(version, diffBase.get(key));
5198
+ if (!diffBase.has(key) && base == null && btn.dataset.diffBase) {
5004
5199
  const summaryBase = Number(btn.dataset.diffBase);
5005
5200
  if (Number.isInteger(summaryBase)) {
5006
- diffBase.set(key, summaryBase);
5007
5201
  base = summaryBase;
5008
5202
  }
5009
5203
  }
5204
+ base = authorizedDiffBase(version, base);
5205
+ if (base != null) diffBase.set(key, base);
5206
+ else diffBase.delete(key);
5010
5207
  loadDiff(n, base); // lazy first load; approval rows start at the previous signed version
5011
5208
  }
5012
5209
  } else {
5210
+ closeBaseMenu();
5013
5211
  row.setAttribute('hidden', '');
5014
5212
  btn.setAttribute('aria-expanded', 'false');
5015
5213
  btn.setAttribute('aria-label', `View detailed changes in version ${n}`);
@@ -5019,35 +5217,88 @@
5019
5217
  }
5020
5218
  }
5021
5219
  // Baseline picker popover (mirrors the rollback-confirm popover idiom; never a native <select>).
5220
+ let baseMenuTrigger = null;
5022
5221
  function onDocDownForBase(e) {
5023
5222
  if (!e.target.closest('.hd-base-menu') && !e.target.closest('.hd-base')) closeBaseMenu();
5024
5223
  }
5025
- function closeBaseMenu() {
5224
+ function onKeyDownForBase(e) {
5225
+ const menu = $wsHistory.querySelector('.hd-base-menu');
5226
+ if (!menu) return;
5227
+ const options = [...menu.querySelectorAll('.hd-base-opt')];
5228
+ const at = options.indexOf(document.activeElement);
5229
+ if (e.key === 'Escape') {
5230
+ e.preventDefault();
5231
+ closeBaseMenu(true);
5232
+ return;
5233
+ }
5234
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Home' || e.key === 'End') {
5235
+ e.preventDefault();
5236
+ const next = e.key === 'Home' ? 0
5237
+ : e.key === 'End' ? options.length - 1
5238
+ : e.key === 'ArrowDown' ? (at + 1 + options.length) % options.length
5239
+ : (at - 1 + options.length) % options.length;
5240
+ options[next]?.focus({ focusVisible: true });
5241
+ return;
5242
+ }
5243
+ if (e.key === 'Tab' && baseMenuTrigger) {
5244
+ e.preventDefault();
5245
+ const trigger = baseMenuTrigger;
5246
+ closeBaseMenu();
5247
+ const controls = [...$wsHistory.querySelectorAll('button:not([disabled])')]
5248
+ .filter((button) => button.offsetParent !== null);
5249
+ const triggerAt = controls.indexOf(trigger);
5250
+ const next = e.shiftKey ? triggerAt - 1 : triggerAt + 1;
5251
+ (controls[next] || trigger).focus({ focusVisible: true });
5252
+ }
5253
+ }
5254
+ function closeBaseMenu(restoreFocus = false) {
5026
5255
  const m = $wsHistory.querySelector('.hd-base-menu');
5027
5256
  if (m) m.remove();
5257
+ const trigger = baseMenuTrigger;
5258
+ if (trigger && trigger.isConnected) trigger.setAttribute('aria-expanded', 'false');
5259
+ baseMenuTrigger = null;
5028
5260
  document.removeEventListener('mousedown', onDocDownForBase, true);
5261
+ document.removeEventListener('keydown', onKeyDownForBase, true);
5262
+ if (restoreFocus && trigger && trigger.isConnected) trigger.focus({ focusVisible: true });
5029
5263
  }
5030
5264
  function showBaseMenu(btn) {
5265
+ if (baseMenuTrigger === btn && $wsHistory.querySelector('.hd-base-menu')) {
5266
+ closeBaseMenu(true);
5267
+ return;
5268
+ }
5031
5269
  closeBaseMenu();
5032
5270
  const to = Number(btn.dataset.baseFor);
5033
- const cur = diffBase.get(baseKeyFor(to)) ?? to - 1;
5271
+ const row = versions.find((version) => Number(version.n) === to);
5272
+ const cur = authorizedDiffBase(row, diffBase.get(baseKeyFor(to)))
5273
+ ?? (row && typeof row.diffBase === 'number' ? row.diffBase : to - 1);
5274
+ if (cur != null) diffBase.set(baseKeyFor(to), cur);
5034
5275
  const menu = el('div', 'hd-base-menu');
5035
- for (const v of versions) { // module-level ledger (newest first); only earlier versions are valid bases
5036
- if (Number(v.n) >= to) continue;
5276
+ menu.id = `hd-base-menu-${to}`;
5277
+ menu.setAttribute('role', 'menu');
5278
+ menu.setAttribute('aria-label', `Compare version ${to} against`);
5279
+ for (const v of selectableDiffBaseVersions(row, to, versions)) {
5037
5280
  const opt = el('button', 'hd-base-opt' + (Number(v.n) === cur ? ' sel' : ''));
5038
5281
  opt.type = 'button';
5282
+ opt.tabIndex = -1;
5283
+ opt.setAttribute('role', 'menuitemradio');
5284
+ opt.setAttribute('aria-checked', Number(v.n) === cur ? 'true' : 'false');
5039
5285
  opt.dataset.baseOpt = String(v.n);
5040
5286
  opt.dataset.baseTo = String(to);
5041
5287
  opt.appendChild(el('span', null, `v${v.n}`));
5042
5288
  opt.appendChild(el('span', 'hd-base-meta', histWhen(v.ts)));
5043
5289
  menu.appendChild(opt);
5044
5290
  }
5291
+ if (!menu.children.length) return;
5045
5292
  $wsHistory.appendChild(menu);
5293
+ baseMenuTrigger = btn;
5294
+ btn.setAttribute('aria-expanded', 'true');
5046
5295
  const pr = $wsHistory.getBoundingClientRect();
5047
5296
  const br = btn.getBoundingClientRect();
5048
5297
  menu.style.top = br.bottom - pr.top + $wsHistory.scrollTop + 4 + 'px';
5049
5298
  menu.style.left = Math.max(8, Math.min(br.left - pr.left, $wsHistory.clientWidth - menu.offsetWidth - 8)) + 'px';
5050
5299
  document.addEventListener('mousedown', onDocDownForBase, true);
5300
+ document.addEventListener('keydown', onKeyDownForBase, true);
5301
+ (menu.querySelector('.hd-base-opt.sel') || menu.querySelector('.hd-base-opt'))?.focus({ focusVisible: true });
5051
5302
  }
5052
5303
 
5053
5304
  $wsHistory.addEventListener('click', (e) => {
@@ -5060,7 +5311,13 @@
5060
5311
  const tog = e.target.closest('.hd-toggle');
5061
5312
  if (tog) { toggleDiff(tog); return; }
5062
5313
  const opt = e.target.closest('[data-base-opt]');
5063
- if (opt) { const to = Number(opt.dataset.baseTo), b = Number(opt.dataset.baseOpt); diffBase.set(baseKeyFor(to), b); closeBaseMenu(); loadDiff(to, b); return; }
5314
+ if (opt) {
5315
+ const to = Number(opt.dataset.baseTo), b = Number(opt.dataset.baseOpt);
5316
+ diffBase.set(baseKeyFor(to), b);
5317
+ closeBaseMenu();
5318
+ loadDiff(to, b, { restoreBaseFocus: true });
5319
+ return;
5320
+ }
5064
5321
  const baseBtn = e.target.closest('.hd-base');
5065
5322
  if (baseBtn) { showBaseMenu(baseBtn); return; }
5066
5323
  const dr = e.target.closest('[data-diff-retry]');