rig-review 4.0.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/compare.html CHANGED
@@ -3,5 +3,5 @@
3
3
  <template data-workspace-header></template>
4
4
  <div class="layout"><main><div class="toolbar"><template data-workspace-comment></template><span id="toolbar-mode-hint">Inspect A and B at the reference video time</span><template data-workspace-view-tools></template><template data-workspace-camera></template></div><!-- shared:stage-bars -->
5
5
  <div id="stage-layout" class="stages"><section id="reference-pane" class="pane"><div class="pane-head"><strong>REFERENCE</strong><span id="reference-name"></span></div><div id="reference-viewport" class="reference-viewport"><video id="reference-video" preload="auto" playsinline muted></video><p id="reference-empty" class="empty">Loading reference video…</p></div><div class="pane-foot"><span id="reference-time">— s</span><label><input id="reference-audio" type="checkbox">Video audio</label></div></section><section id="a-pane" class="pane"><div class="pane-head"><strong class="side-label">A</strong><span id="a-title"></span></div><div id="a-viewport" class="rig-viewport"><div id="a-root" class="rig-root"></div><canvas id="a-overlay" class="rig-overlay" aria-label="A actual rig mesh and bone overlay"></canvas><!-- shared:stage-handles --><p id="a-empty" class="empty">Loading rig…</p></div><div class="pane-foot"><span id="a-time">— s</span><span id="a-frame">rate unknown</span><span id="a-renderer" aria-label="A last draw backend" title="DOM images for rigid parts; WebGL meshes when available, Canvas2D fallback.">Not rendered</span></div></section><section id="b-pane" class="pane"><div class="pane-head"><strong class="side-label">B</strong><span id="b-title"></span></div><div id="b-viewport" class="rig-viewport"><div id="b-root" class="rig-root"></div><canvas id="b-overlay" class="rig-overlay" aria-label="B actual rig mesh and bone overlay"></canvas><p id="b-empty" class="empty">Loading rig…</p></div><div class="pane-foot"><span id="b-time">— s</span><span id="b-frame">rate unknown</span><span id="b-renderer" aria-label="B last draw backend" title="DOM images for rigid parts; WebGL meshes when available, Canvas2D fallback.">Not rendered</span></div></section></div>
6
- <section class="inspector" aria-label="Inspection controls"><div class="inspector-heading"><strong>INSPECTOR</strong><div role="tablist" aria-label="Inspector sections"><button role="tab" id="tab-view" data-inspector="view" aria-controls="inspector-view" aria-selected="true" tabindex="0">View</button><button role="tab" id="tab-rig" data-inspector="rig" aria-controls="inspector-rig" aria-selected="false" tabindex="-1">Rig</button><button role="tab" id="tab-playback" data-inspector="playback" aria-controls="inspector-playback" aria-selected="false" tabindex="-1">Playback</button><button role="tab" id="tab-feedback" data-inspector="feedback" aria-controls="inspector-feedback" aria-selected="false" tabindex="-1">Feedback</button></div><span class="hint">Local view controls · source files stay unchanged</span></div><div class="draft-notice"><span id="draft-state" role="status" aria-live="polite"></span><div id="draft-recovery"></div></div><div class="inspector-body"><!-- shared:applied-records --><section id="inspector-view" role="tabpanel" aria-labelledby="tab-view" data-inspector-panel="view"><div class="view-link-controls"><button id="copy-view" type="button">Copy view link</button><span class="hint">Numeric source region · opening this link restores a paused inspection</span></div><pre id="view-coordinates" class="numeric-view" aria-label="Current numeric inspection region"></pre><div class="inspection-controls" aria-label="Inspection display controls"><label>Appearance <select id="appearance"><option value="system">System</option><option value="dark">Dark</option><option value="light">Light</option></select></label><label><input id="idle-repeat" type="checkbox" checked>Repeat idle</label><span id="idle-state" class="hint" role="status">Idle preview unavailable</span><span id="control-state" class="hint" role="status"></span></div><p class="hint">Sync cameras links fit-relative zoom and viewport-relative pan across visible panes. Turn it off for independent Reference, A and B views. Toolbar zoom and Fit use the last active pane.</p></section><section id="inspector-rig" role="tabpanel" aria-labelledby="tab-rig" data-inspector-panel="rig" hidden><!-- shared:setup-block-row --><section id="selected-part" role="tabpanel" aria-labelledby="block-tab-selected-part" aria-label="Selected part" aria-live="polite"></section><div class="rig-layer-controls"><template data-workspace-layers></template><span id="layer-state" class="hint">No rig supplied</span></div><p id="rig-inspector-hint" class="hint">These controls show actual images, last-drawn mesh edges and named bone points. Both builds use the fixed animation named above. This inspector does not author geometry or motion.</p><!-- shared:setup-panels --></section><section id="inspector-playback" role="tabpanel" aria-labelledby="tab-playback" data-inspector-panel="playback" hidden><div id="animation-dock" class="animation-dock-panel" role="region" aria-label="Animation timeline"><section id="transport" class="transport"><button id="play" aria-label="Play reference video and both rigs" disabled>▶</button><input id="scrub" type="range" min="0" max="1" step="0.0001" value="0" aria-label="Shared comparison time" disabled><output id="time">— / — s</output><label for="time-input" class="sr-only">Reference video time to inspect</label><input id="time-input" type="number" min="0" step="0.0001" placeholder="Seconds" disabled><button id="seek" disabled>Go to time</button><!-- shared:transport-strips --></section><section id="animation-inspection" aria-label="Read-only animation inspection"></section></div><div id="animate-blocks" class="animate-blocks-panel" data-inspector-scroll><!-- shared:animate-block-row --><section id="compare-transport-context"><div class="compare-info"><output id="sync-status">Presentation pending</output><span id="sync-warning"></span></div><div class="compare-info"><label for="frame-basis">Review frame</label><select id="frame-basis"><option value="a">A explicit samples</option><option value="b">B explicit samples</option></select><input id="frame-input" type="number" min="0" step="1" aria-label="Explicit producer frame" disabled><button id="frame-seek" type="button" disabled>Inspect frame</button><span id="frame-index-status">Loading reference timestamp index…</span></div><div class="compare-info"><span id="domain">Checking shared playback range…</span><span id="clock-source">Waiting for video time</span></div><details class="trace"><summary>Synchronization trace</summary><pre id="trace">No frame presented yet.</pre></details><p id="playback-inspector-hint" class="boundary">Motion is read only. The reference video FPS is not used to infer the pose frame clock.</p></section><!-- shared:animate-panels --></div></section><section id="inspector-feedback" role="tabpanel" aria-labelledby="tab-feedback" data-inspector-panel="feedback" hidden><div class="review-summary"><div class="eyebrow">COMPARE REVIEW</div><label for="status">Review status</label><select id="status"><option value="pending">Pending</option><option value="approved">Approved</option><option value="changes-requested">Changes requested</option></select><section class="provenance"><h2>Source provenance</h2><div id="provenance-brief"></div><details><summary>Both builds, versions and reference video hash</summary><pre id="provenance-full"></pre></details></section></div><section class="feedback-form"><h2>Frame-range feedback</h2><label for="side">Target build</label><select id="side"><option value="">Select A or B</option><option value="a">A</option><option value="b">B</option></select><div class="frame-range"><label>Start frame<input id="frame-start" type="number" min="0" step="1" inputmode="numeric"></label><label>End frame<input id="frame-end" type="number" min="0" step="1" inputmode="numeric"></label></div><p id="feedback-range-hint" class="hint">Select A or B to check frame bounds.</p><label for="target-kind">Target type</label><select id="target-kind"><option value="">Select</option><option value="bone">Bone</option><option value="slot">Slot</option><option value="rig">Entire rig</option></select><label for="target-name">Actual target name</label><input id="target-name" type="text" list="target-names" autocomplete="off"><datalist id="target-names"></datalist><p id="target-hint" class="hint">Select a target build and type.</p><label for="category">Category</label><select id="category"><option value="">Select</option><option value="defect">Defect</option><option value="quality">Quality</option></select><label for="summary">One-line summary</label><input id="summary" type="text" maxlength="1000" placeholder="What looks wrong, and over which frames?"><button id="add-feedback" class="block" disabled>Add feedback</button><p id="feedback-warnings" class="hint" role="status" hidden></p><div id="feedback-list"></div></section><details id="strip-panel" class="trace"><summary>Export frame strip</summary><p class="hint">Uses the feedback form start and end frames, inclusive. Exports Reference / A / B rows without changing inspection time.</p><label for="strip-scope">Export range</label><select id="strip-scope"><option value="interval">Entered start–end frames</option><option value="feedback">All feedback ranges</option></select><label for="strip-basis">Report defining the range frames</label><select id="strip-basis"><option value="">Select A or B as frame basis</option><option value="a">A report frameTimes</option><option value="b">B report frameTimes</option></select><label for="strip-format">Format</label><select id="strip-format"><option value="png">PNG strip</option><option value="json">JSON frames and provenance</option></select><p class="hint">The same frame number in A and B is not assumed to mean the same time. Batch export uses each feedback side as its frame basis. Without frameTimes, PNG is refused and JSON preserves time: null.</p><button id="strip-export" type="button" disabled>Download strip</button><p id="strip-status" class="hint" role="status" aria-live="polite">Loading comparison provenance…</p></details></section></div></section></main><aside id="parts-explorer" class="parts-explorer" aria-label="Parts explorer"><div class="parts-tools"><h2>PARTS</h2><button type="button" data-part-whole aria-pressed="true">Whole rig</button><label for="part-search">Find slot</label><input id="part-search" data-part-search type="search" autocomplete="off" placeholder="Exact slot name or text"><label class="part-solo"><input id="part-solo" data-part-solo type="checkbox" disabled>Solo selected slot</label><p data-part-status class="hint" role="status">Loading actual slots…</p></div><ul data-part-list aria-label="Actual rig slots"></ul><p class="hint">Select in context or enable Solo. Thumbnails are each slot's declared page region; a type icon stands in where the model declares none. Atlas pages are not part thumbnails.</p></aside>
6
+ <section class="inspector" aria-label="Inspection controls"><div class="inspector-heading"><strong>INSPECTOR</strong><div role="tablist" aria-label="Inspector sections"><button role="tab" id="tab-view" data-inspector="view" aria-controls="inspector-view" aria-selected="true" tabindex="0">View</button><button role="tab" id="tab-rig" data-inspector="rig" aria-controls="inspector-rig" aria-selected="false" tabindex="-1">Rig</button><button role="tab" id="tab-playback" data-inspector="playback" aria-controls="inspector-playback" aria-selected="false" tabindex="-1">Playback</button><button role="tab" id="tab-feedback" data-inspector="feedback" aria-controls="inspector-feedback" aria-selected="false" tabindex="-1">Feedback</button></div><span class="hint">Local view controls · source files stay unchanged</span></div><div class="draft-notice"><span id="draft-state" role="status" aria-live="polite"></span><div id="draft-recovery"></div></div><div class="inspector-body"><!-- shared:applied-records --><section id="inspector-view" role="tabpanel" aria-labelledby="tab-view" data-inspector-panel="view"><div class="view-link-controls"><button id="copy-view" type="button">Copy view link</button><span class="hint">Numeric source region · opening this link restores a paused inspection</span></div><pre id="view-coordinates" class="numeric-view" aria-label="Current numeric inspection region"></pre><div class="inspection-controls" aria-label="Inspection display controls"><label>Appearance <select id="appearance"><option value="system">System</option><option value="dark">Dark</option><option value="light">Light</option></select></label><label><input id="idle-repeat" type="checkbox" checked>Repeat idle</label><span id="idle-state" class="hint" role="status">Idle preview unavailable</span><span id="control-state" class="hint" role="status"></span></div><p class="hint">Sync cameras links fit-relative zoom and viewport-relative pan across visible panes. Turn it off for independent Reference, A and B views. Toolbar zoom and Fit use the last active pane.</p></section><section id="inspector-rig" role="tabpanel" aria-labelledby="tab-rig" data-inspector-panel="rig" hidden><!-- shared:setup-block-row --><section id="selected-part" role="tabpanel" aria-labelledby="block-tab-selected-part" aria-label="Selected part" aria-live="polite"></section><div class="rig-layer-controls"><template data-workspace-layers></template><span id="layer-state" class="hint">No rig supplied</span></div><p id="rig-inspector-hint" class="hint">These controls show actual images, last-drawn mesh edges and named bone points. Both builds use the fixed animation named above. This inspector does not author geometry or motion.</p><!-- shared:setup-panels --></section><section id="inspector-playback" role="tabpanel" aria-labelledby="tab-playback" data-inspector-panel="playback" hidden><!-- shared:animate-block-row --><div id="animation-dock" class="animation-dock-panel" role="tabpanel" aria-labelledby="block-tab-animation-dock" aria-label="Animation timeline"><section id="transport" class="transport"><button id="play" aria-label="Play reference video and both rigs" disabled>▶</button><input id="scrub" type="range" min="0" max="1" step="0.0001" value="0" aria-label="Shared comparison time" disabled><output id="time">— / — s</output><label for="time-input" class="sr-only">Reference video time to inspect</label><input id="time-input" type="number" min="0" step="0.0001" placeholder="Seconds" disabled><button id="seek" disabled>Go to time</button><!-- shared:transport-strips --></section><section id="animation-inspection" aria-label="Read-only animation inspection"></section></div><section id="compare-transport-context"><div class="compare-info"><output id="sync-status">Presentation pending</output><span id="sync-warning"></span></div><div class="compare-info"><label for="frame-basis">Review frame</label><select id="frame-basis"><option value="a">A explicit samples</option><option value="b">B explicit samples</option></select><input id="frame-input" type="number" min="0" step="1" aria-label="Explicit producer frame" disabled><button id="frame-seek" type="button" disabled>Inspect frame</button><span id="frame-index-status">Loading reference timestamp index…</span></div><div class="compare-info"><span id="domain">Checking shared playback range…</span><span id="clock-source">Waiting for video time</span></div><details class="trace"><summary>Synchronization trace</summary><pre id="trace">No frame presented yet.</pre></details><p id="playback-inspector-hint" class="boundary">Motion is read only. The reference video FPS is not used to infer the pose frame clock.</p></section><!-- shared:animate-panels --></section><section id="inspector-feedback" role="tabpanel" aria-labelledby="tab-feedback" data-inspector-panel="feedback" hidden><div class="review-summary"><div class="eyebrow">COMPARE REVIEW</div><label for="status">Review status</label><select id="status"><option value="pending">Pending</option><option value="approved">Approved</option><option value="changes-requested">Changes requested</option></select><section class="provenance"><h2>Source provenance</h2><div id="provenance-brief"></div><details><summary>Both builds, versions and reference video hash</summary><pre id="provenance-full"></pre></details></section></div><section class="feedback-form"><h2>Frame-range feedback</h2><label for="side">Target build</label><select id="side"><option value="">Select A or B</option><option value="a">A</option><option value="b">B</option></select><div class="frame-range"><label>Start frame<input id="frame-start" type="number" min="0" step="1" inputmode="numeric"></label><label>End frame<input id="frame-end" type="number" min="0" step="1" inputmode="numeric"></label></div><p id="feedback-range-hint" class="hint">Select A or B to check frame bounds.</p><label for="target-kind">Target type</label><select id="target-kind"><option value="">Select</option><option value="bone">Bone</option><option value="slot">Slot</option><option value="rig">Entire rig</option></select><label for="target-name">Actual target name</label><input id="target-name" type="text" list="target-names" autocomplete="off"><datalist id="target-names"></datalist><p id="target-hint" class="hint">Select a target build and type.</p><label for="category">Category</label><select id="category"><option value="">Select</option><option value="defect">Defect</option><option value="quality">Quality</option></select><label for="summary">One-line summary</label><input id="summary" type="text" maxlength="1000" placeholder="What looks wrong, and over which frames?"><button id="add-feedback" class="block" disabled>Add feedback</button><p id="feedback-warnings" class="hint" role="status" hidden></p><div id="feedback-list"></div></section><details id="strip-panel" class="trace"><summary>Export frame strip</summary><p class="hint">Uses the feedback form start and end frames, inclusive. Exports Reference / A / B rows without changing inspection time.</p><label for="strip-scope">Export range</label><select id="strip-scope"><option value="interval">Entered start–end frames</option><option value="feedback">All feedback ranges</option></select><label for="strip-basis">Report defining the range frames</label><select id="strip-basis"><option value="">Select A or B as frame basis</option><option value="a">A report frameTimes</option><option value="b">B report frameTimes</option></select><label for="strip-format">Format</label><select id="strip-format"><option value="png">PNG strip</option><option value="json">JSON frames and provenance</option></select><p class="hint">The same frame number in A and B is not assumed to mean the same time. Batch export uses each feedback side as its frame basis. Without frameTimes, PNG is refused and JSON preserves time: null.</p><button id="strip-export" type="button" disabled>Download strip</button><p id="strip-status" class="hint" role="status" aria-live="polite">Loading comparison provenance…</p></details></section></div></section></main><aside id="parts-explorer" class="parts-explorer" aria-label="Parts explorer"><div class="parts-tools"><h2>PARTS</h2><button type="button" data-part-whole aria-pressed="true">Whole rig</button><label for="part-search">Find slot</label><input id="part-search" data-part-search type="search" autocomplete="off" placeholder="Exact slot name or text"><label class="part-solo"><input id="part-solo" data-part-solo type="checkbox" disabled>Solo selected slot</label><p data-part-status class="hint" role="status">Loading actual slots…</p></div><ul data-part-list aria-label="Actual rig slots"></ul><p class="hint">Select in context or enable Solo. Thumbnails are each slot's declared page region; a type icon stands in where the model declares none. Atlas pages are not part thumbnails.</p></aside>
7
7
  </div><footer><span id="message" role="status" aria-live="polite">Loading comparison provenance from the server…</span><span>Source files remain unchanged.</span></footer><script type="module" src="main.js"></script></body></html>
package/web/compare.ts CHANGED
@@ -48,6 +48,7 @@ function mountComparisonChrome(){
48
48
  }
49
49
  const controls=createViewControls({layout:'legacyCompareStep3'});
50
50
  document.querySelector('[data-workspace-camera]')!.replaceWith(controls.zoomGroup!);
51
+ const play=document.getElementById('play')!;play.hidden=true;controls.zoomGroup!.before(play);
51
52
  return shell;
52
53
  }
53
54
  const shell=mountComparisonChrome();
@@ -442,7 +443,7 @@ function bind(): void {
442
443
  input('idle-repeat').onchange=()=>{renderIdle();if(canRepeatIdle())void playComparison().catch(error=>message(describe(error),true));};
443
444
  el('inspector-feedback').addEventListener('focusin',()=>{idleHeld=true;const current=lastPresented?.time;stop();if(current!==undefined&&!seeking)void seekTo(current);});
444
445
  bindInspector();
445
- const transportBlock=document.querySelector<HTMLElement>('#animate-blocks [data-block-target="motion-tools"]');if(transportBlock)transportBlock.dataset.blockIncludes=[transportBlock.dataset.blockIncludes,'compare-transport-context'].filter(Boolean).join(' ');
446
+ const transportBlock=document.querySelector<HTMLElement>('#inspector-playback [data-block-target="animation-dock"]');if(transportBlock)transportBlock.dataset.blockIncludes=[transportBlock.dataset.blockIncludes,'compare-transport-context'].filter(Boolean).join(' ');
446
447
  pickedTools=mountComparePickedTools({data:()=>data,readOnly:()=>readOnly,players,assets,rigScales,layers,parts:()=>parts,time:()=>trace?.reference??presentation.snapshot().lastDrawn?.reference??0,duration:()=>domain?.end??0,playing:()=>!video.paused,pause:()=>{idleHeld=true;stop();},seekTo:seconds=>seekTo(seconds),api,route:access.route,swapSideRig,redrawOverlays,fit,syncLayout:()=>{renderPairLayout();const mode=pickedTools?.mode()??'compare',picked=pickedTools?.pickedSide()??'a';if(mode!=='compare'&&activeCamera!=='reference'&&activeCamera!==picked)activeCamera=picked;fit();},saveDraft:()=>{persistence?.save();},message,download,turnAdjustFor:side=>turnAdjusts[side]??null,syncFeedbackSide:side=>{if(select('side').value!==side&&!input('summary').value.trim()){select('side').value=side;renderFeedbackSelection();}}});
447
448
  document.addEventListener('visibilitychange',()=>{if(document.hidden){suspendedPreview=!video.paused;stop();}else if(suspendedPreview&&!idleHeld){suspendedPreview=false;void playComparison().catch(error=>message(describe(error),true));}});
448
449
  const observer = new ResizeObserver(fit); observer.observe(el('a-viewport')); observer.observe(el('b-viewport'));observer.observe(el('reference-viewport'));
@@ -483,7 +484,7 @@ function createCompareViewport(){
483
484
  cameraRestoring:{get:()=>cameraRestoring,set:(value:boolean)=>{cameraRestoring=value;}},
484
485
  cameraLayout:{get:()=>cameraLayout,set:(value:string)=>{cameraLayout=value;}}
485
486
  });
486
- const provider=createRigViewportProvider({el,player:()=>null,assets:()=>null,
487
+ const provider=createRigViewportProvider({fitLabel:'Fit',el,player:()=>null,assets:()=>null,
487
488
  panes:(['a','b'] as const).map(target=>({target,viewport:el(target+'-viewport'),pane:el(target+'-pane'),
488
489
  root:el(target+'-root'),fallback:target==='a'?'b' as const:'a' as const,box:sharedBox,
489
490
  player:()=>players[target]??null,scale:(value:number)=>{rigScales[target]=value;}})),
@@ -498,7 +499,7 @@ function createCompareViewport(){
498
499
  return selected?`Selected slot fitted${suffix}.`:`View fitted${suffix}.`;
499
500
  },
500
501
  cameraControls:{zoomId:'zoom-label',targetLabel:target=>target==='reference'?'Reference':target?.toUpperCase()??'A',
501
- fitLabel:sync=>sync?'Fit synchronized views':'Fit active view',coordinatesId:null}
502
+ coordinatesId:null}
502
503
  },state);
503
504
  return createViewportController(provider,state);
504
505
  }
@@ -155,14 +155,20 @@ export function recoverSession<T extends {id:string;revision:string;sourceHash:s
155
155
  export const maximumDrafts=32,protectedDraftMs=24*60*60*1000;
156
156
  const draftPrefix='rig-review-draft/1:',draftIndex='rig-review-draft-index/1';
157
157
  const cropDatabase='rig-review-inspection-drafts',cropStore='crops',cropReference='draft-crop:';
158
- /** Only existing stage-comment crops in inspection sessions belong to this private transport. */
159
- function draftCrops(session:unknown):{row:{id:string};crop:Record<string,unknown>}[] {
160
- if(!session||typeof session!=='object'||!Array.isArray((session as PersistenceSession).feedback))return [];
161
- return (session as PersistenceSession).feedback.flatMap(item=>{
162
- const comment=(item as {context?:{comment?:unknown}}|null)?.context?.comment;
163
- if(!hasStageComment(comment))return [];
164
- const row=record(item,'draft');if(typeof row.id!=='string')throw new Error('Draft review state invalid');
165
- return [{row:row as {id:string},crop:record((comment as {crop:unknown}).crop,'crop')}];
158
+ /** Existing rig feedback and native parts issues share the private crop transport. */
159
+ function draftCrops(session:unknown):{row:{id:string};crop:Record<string,unknown>;parts:boolean}[] {
160
+ if(!session||typeof session!=='object')return [];
161
+ const value=session as {feedback?:unknown[];subject?:unknown;issues?:unknown[]};
162
+ const rows=[...(Array.isArray(value.feedback)?value.feedback:[]),...(value.subject==='parts'&&Array.isArray(value.issues)?value.issues:[])];
163
+ return rows.flatMap(item=>{
164
+ const row=record(item,'draft'),parts=value.subject==='parts'&&(row.schema==='rig-review-parts-comment/1'||row.schema==='rig-review-parts-comment/2');
165
+ const comment=parts?row:(item as {context?:{comment?:unknown}}|null)?.context?.comment;
166
+ if(!parts&&!hasStageComment(comment))return [];
167
+ const crop=record((comment as {crop:unknown}).crop,'crop');
168
+ // Finalized parts rows may retain only their server-backed path/hash, without inline pixels.
169
+ if(parts&&!Object.hasOwn(crop,'png'))return [];
170
+ if(typeof row.id!=='string')throw new Error('Draft review state invalid');
171
+ return [{row:row as {id:string},crop,parts}];
166
172
  });
167
173
  }
168
174
  /** Browser counterpart of comment-crops.ts's signature/dimension/digest boundary (no Node imports). */
@@ -239,7 +245,8 @@ export class InspectionDraftStore {
239
245
  if(packed.schema!=='rig-review-local-draft/2')return this.parseDraft(raw,expected);
240
246
  // Check the bounded envelope/binding before touching IDB; validate the full session only after hydration.
241
247
  const draft=this.parseDraft(JSON.stringify({...packed,schema:'rig-review-local-draft/1'}),expected);
242
- const crops=draftCrops(draft.session),blobs=new Map<{id:string},Blob>();
248
+ // Earlier /2 parts drafts stored inline PNGs; migrate them only on their next save.
249
+ const crops=draftCrops(draft.session).filter(({parts,crop})=>!(parts&&typeof crop.png==='string'&&/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png))),blobs=new Map<{id:string},Blob>();
243
250
  if(crops.length)await this.crops('readonly',store=>{
244
251
  for(const {row,crop}of crops){
245
252
  if(crop.png!==cropReference+crop.sha256)throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');
@@ -249,7 +256,7 @@ export class InspectionDraftStore {
249
256
  // A completed read with missing/corrupt bytes loses only that image comment; transport failures still throw.
250
257
  const unavailable=new Set<unknown>();
251
258
  for(const {row,crop}of crops){const png=await draftPng(blobs.get(row)!,crop);if(png===null)unavailable.add(row);else crop.png=png;}
252
- if(unavailable.size){const session=record(draft.session,'draft');session.feedback=(session.feedback as unknown[]).filter(row=>!unavailable.has(row));}
259
+ if(unavailable.size){const session=record(draft.session,'draft');for(const key of ['feedback','issues'])if(Array.isArray(session[key]))session[key]=(session[key] as unknown[]).filter(row=>!unavailable.has(row));}
253
260
  return draft;
254
261
  }
255
262
  read(canRecover?:(session:unknown)=>boolean):Promise<LocalInspectionDraft|null> {
@@ -277,7 +284,7 @@ export class InspectionDraftStore {
277
284
  try{
278
285
  const packed=JSON.parse(snapshot) as LocalInspectionDraft;
279
286
  // Clean sessions are already durable on the server and are never restored as unsent feedback.
280
- if(!packed.reviewDirty&&packed.session&&typeof packed.session==='object'){
287
+ if(!packed.reviewDirty&&packed.session&&typeof packed.session==='object'&&'feedback'in packed.session){
281
288
  packed.session={...packed.session,feedback:[]};
282
289
  }
283
290
  const crops=draftCrops(packed.session),blobs:{key:IDBValidKey;blob:Blob}[]=[];
@@ -311,24 +318,26 @@ export class InspectionDraftStore {
311
318
  }
312
319
 
313
320
  interface PersistenceSession {id:string;revision:string;sourceHash:string;status:string;feedback:unknown[]}
314
- interface PersistenceAdapter<T extends PersistenceSession> {
321
+ interface PersistenceAdapter<T> {
322
+ recover?:(value:unknown,baseline:T)=>T|null;
315
323
  scope:string;binding:InspectionBinding;baseline:T;session:()=>T;reviewDirty:()=>boolean;
316
324
  restoreSession:(value:T,dirty:boolean)=>void;bookmark:()=>InspectionBookmark;
317
325
  restoreBookmark:(bookmark:InspectionBookmark,signal:AbortSignal)=>Promise<void>;
318
326
  ui:()=>Record<string,string|number|null>;restoreUI:(ui:Record<string,string|number|null>)=>void;
319
327
  afterInputs:()=>void;onConflict:(conflict:boolean)=>void;onStatus:(message:string)=>void;
320
328
  }
321
- export interface PersistenceConnection {restored:boolean;restoring:()=>boolean;save:()=>void;submitted:(session:unknown)=>Promise<void>;dispose:()=>void}
329
+ export interface PersistenceConnection {restored:boolean;restoring:()=>boolean;save:()=>Promise<void>;submitted:(session:unknown)=>Promise<void>;dispose:()=>void}
322
330
  const viewInputIds=new Set(['part-search','part-solo','camera-sync','appearance','layer-images','layer-mesh','layer-bones','animation-select','reference-select','person-select','axis-select','axis-value','scrub','frame-number','frame-scrub','time-input','frame-input','part-set']);
323
331
  /** Restore once after normal startup; snapshots never perform a server mutation. */
324
- export async function connectInspectionPersistence<T extends PersistenceSession>(adapter:PersistenceAdapter<T>):Promise<PersistenceConnection> {
332
+ export async function connectInspectionPersistence<T>(adapter:PersistenceAdapter<T>):Promise<PersistenceConnection> {
325
333
  let restoring=true,closed=false,conflict=false,timer:ReturnType<typeof setTimeout>|undefined;
326
334
  let navigationGeneration=0,navigationAbort:AbortController|null=null,navigationQueue=Promise.resolve(),lastNavigationHash=location.hash;
327
335
  let previousInert:boolean|null=null;
328
336
  const holdRestore=(value:boolean)=>{restoring=value;const body=document.body;if(value){if(body&&previousInert===null){previousInert=body.inert;body.inert=true;}}else if(body&&previousInert!==null){body.inert=previousInert;previousInert=null;}};
329
337
  let baseline=await sessionFingerprint(adapter.baseline);const status=adapter.onStatus,initialInputs=captureInputs();
330
338
  const store=new InspectionDraftStore(adapter.scope,adapter.binding,status);
331
- let draft=await store.read(session=>recoverSession(session,adapter.baseline)!==null);
339
+ const recover=adapter.recover??((value:unknown,baseline:T)=>recoverSession(value,baseline as T & PersistenceSession) as T|null);
340
+ let draft=await store.read(session=>recover(session,adapter.baseline)!==null);
332
341
  const notices=[document.getElementById('draft-recovery'),document.getElementById('review-draft-recovery')].filter((node):node is HTMLElement=>node!==null);
333
342
  const clearNotices=()=>{for(const node of notices)node.replaceChildren();};
334
343
  const appendAction=(label:string,onclick:()=>void)=>{for(const node of notices){const button=actionButton(label,onclick);node.append(button);}};
@@ -338,12 +347,14 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
338
347
  try{explicit=decodeBookmark(location.hash,adapter.binding);}catch(error){status(error instanceof Error?error.message:String(error));}
339
348
  let recovered:T|null=null,sameBaseline=false;
340
349
  if(draft){
341
- recovered=recoverSession(draft.session,adapter.baseline);
342
- const prior=recovered?recoverSession(adapter.baseline,draft.session as T):null;
350
+ recovered=recover(draft.session,adapter.baseline);
351
+ const prior=recovered?recover(adapter.baseline,draft.session as T):null;
343
352
  sameBaseline=draft.baseline===baseline||(prior!==null&&draft.baseline===await sessionFingerprint(prior));
344
353
  if(!draft.reviewDirty&&(!sameBaseline||!recovered||draft.baseline!==baseline)){await store.clear();draft=null;recovered=null;}
345
354
  }
346
355
  const raw=store.recovery();
356
+ const restoreFailed=!!raw&&!draft;
357
+ if(restoreFailed){conflict=true;adapter.onConflict(true);status('Saved draft could not be restored. Your draft has not been deleted. Download or discard it before submitting.');}
347
358
  if(draft){
348
359
  conflict=!sameBaseline||!recovered;
349
360
  if(!conflict&&recovered&&draft.reviewDirty){try{adapter.restoreSession(recovered,true);status('Restored local draft · not submitted');}catch(error){conflict=true;adapter.onConflict(true);status(`Local draft needs explicit recovery: ${error instanceof Error?error.message:String(error)}`);}}
@@ -353,9 +364,9 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
353
364
  }
354
365
  try{adapter.restoreUI(draft.ui);}catch(error){status(`Saved panel selection unavailable: ${error instanceof Error?error.message:String(error)}`);}
355
366
  }
356
- if(raw&&(conflict||!draft))appendAction('Download saved local draft',()=>download(raw));
367
+ if(raw&&(conflict||!draft))appendAction('Download saved local draft',()=>{download(raw);if(restoreFailed){conflict=false;adapter.onConflict(false);clearNotices();status('Saved draft downloaded · not submitted');}});
357
368
  if(conflict&&recovered)appendAction('Recover local draft as pending',()=>{try{adapter.restoreSession({...recovered,status:'pending'},true);conflict=false;adapter.onConflict(false);clearNotices();status('Recovered local draft as pending · not submitted');save();}catch(error){status(`Local draft recovery refused: ${error instanceof Error?error.message:String(error)}`);}});
358
- if(conflict)appendAction('Discard conflicting local draft',async()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();await store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
369
+ if(conflict&&!restoreFailed)appendAction('Discard conflicting local draft',async()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();await store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
359
370
  const selected=location.hash.startsWith('#review=')?explicit:draft?.bookmark;
360
371
  let restored=location.hash.startsWith('#review=')||!!draft;
361
372
  if(selected){try{await adapter.restoreBookmark(selected,new AbortController().signal);restored=true;}catch(error){status(`Inspection was not restored: ${error instanceof Error?error.message:String(error)}`);}}
@@ -363,7 +374,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
363
374
  const excluded=new Set(viewInputIds);if(conflict||!draft.reviewDirty){excluded.add('review-status');excluded.add('status');excluded.add('checkpoint-note');for(const key of Object.keys(draft.inputs))if(key.startsWith('radio:outcome:'))excluded.add(key);}
364
375
  restoreInputs(draft.inputs,excluded);adapter.afterInputs();
365
376
  }
366
- if(raw&&!draft)appendAction('Discard unusable local draft',async()=>{await store.clear();clearNotices();status('Unusable local draft discarded for this review only.');save();});
377
+ if(raw&&!draft)appendAction('Discard unusable local draft',async()=>{await store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Unusable local draft discarded for this review only.');save();});
367
378
  let writes=Promise.resolve();
368
379
  restoring=false;
369
380
  if(draft&&!conflict&&draft.baseline!==baseline)save();
@@ -374,10 +385,11 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
374
385
  value.baseline=baseline;
375
386
  if(await store.write(value)&&!closed&&!restoring&&navigation===navigationGeneration){const url=new URL(location.href);url.hash=encodeBookmark(value.bookmark);history.replaceState(null,'',url);lastNavigationHash=url.hash;}
376
387
  }
377
- function save():void {
378
- if(closed||restoring||conflict)return;
388
+ function save():Promise<void> {
389
+ if(closed||restoring||conflict)return Promise.resolve();
379
390
  try{const value=snapshot(),navigation=navigationGeneration;writes=writes.then(()=>persist(value,navigation)).catch(error=>{status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);});
380
391
  }catch(error){status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);}
392
+ return writes;
381
393
  }
382
394
  function navigateView():void {
383
395
  if(closed||location.hash===lastNavigationHash)return;
@@ -32,17 +32,29 @@ export interface InspectorBlocksOptions {
32
32
  available?:readonly string[];
33
33
  /** Called when a click or a key changes a section's active tab. */
34
34
  changed?:()=>void;
35
- /** The rig reuses its block rows in the heading, with one shared Comments tab. */
35
+ /** The rig reuses its block rows in the heading, with one programmatic Comments selection. */
36
36
  bottom?:{strip:HTMLElement;comment:HTMLButtonElement;panel:HTMLElement};
37
37
  }
38
- export interface InspectorBlocks {state():ActiveBlocks;restore(state:ActiveBlocks):void;select(section:string,id:string):void;activate(section:string):void;dispose():void}
38
+ export interface InspectorBlocks {state():ActiveBlocks;restore(state:ActiveBlocks):void;select(section:string,id:string):void;activate(section:string):void;register(tab:{id:string;panel:HTMLElement;label:string;position?:'first'|'last'}):()=>void;dispose():void}
39
39
 
40
40
  interface Tab {button:HTMLButtonElement;id:string;panel:HTMLElement;included:HTMLElement[]}
41
41
  const isRow=(node:Element)=>node.classList.contains('block-row');
42
+ function bindPopupMenu(id:string,items:()=>HTMLButtonElement[],cleanups:(()=>void)[],place?:(menu:HTMLElement)=>void):{button:HTMLButtonElement;menu:HTMLElement;close:(focus?:boolean)=>void} {
43
+ const button=actionButton('⋯',null),menu=panelMake('div',{id,hidden:true}),listen=(node:HTMLElement,type:string,fn:(event:Event)=>void)=>{node.addEventListener(type,fn);cleanups.push(()=>node.removeEventListener(type,fn));};
44
+ button.setAttribute('aria-haspopup','menu');button.setAttribute('aria-controls',id);button.setAttribute('aria-expanded','false');menu.setAttribute('role','menu');
45
+ const close=(focus=true)=>{menu.hidden=true;button.setAttribute('aria-expanded','false');if(focus)button.focus();};
46
+ const open=(last=false)=>{const visible=items();if(!visible.length)return;const list=visible.filter(item=>!item.disabled);menu.hidden=false;place?.(menu);button.setAttribute('aria-expanded','true');if(list.length)list[last?list.length-1:0]!.focus();else{menu.tabIndex=-1;menu.focus();}};
47
+ listen(button,'click',()=>menu.hidden?open():close());
48
+ listen(button,'keydown',event=>{const key=(event as KeyboardEvent).key;if(['ArrowDown','ArrowUp','Enter',' '].includes(key)){event.preventDefault();open(key==='ArrowUp');}else if(key==='Escape'){event.preventDefault();close();}});
49
+ listen(menu,'keydown',event=>{const key=(event as KeyboardEvent).key,list=items().filter(item=>!item.disabled);if(key==='Escape'){event.preventDefault();close();}else if(['ArrowDown','ArrowUp','Home','End'].includes(key)&&list.length){event.preventDefault();const index=list.indexOf(event.target as HTMLButtonElement);list[key==='Home'?0:key==='End'?list.length-1:(index+(key==='ArrowDown'?1:list.length-1))%list.length]!.focus();}});
50
+ listen(menu,'focusout',event=>{const target=(event as FocusEvent).relatedTarget;if(target!==button&&!menu.contains(target as Node|null))close(false);});
51
+ return {button,menu,close};
52
+ }
42
53
 
43
54
  export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlocks {
44
- const rows=new Map<string,InspectorTabs>(),ids=new Map<string,Set<string>>();
45
- const definitions=new Map<string,{section:HTMLElement;row:HTMLElement;scrollRoot:HTMLElement;tabs:Tab[]}>(),saved:ActiveBlocks={};
55
+ const rows=new Map<string,InspectorTabs>(),ids=new Map<string,Set<string>>(),cleanups:(()=>void)[]=[];
56
+ const definitions=new Map<string,{section:HTMLElement;row:HTMLElement;scrollRoot:HTMLElement;tabs:Tab[];syncOverflow:()=>void}>(),saved:ActiveBlocks={};
57
+ const external=new Set<string>();
46
58
  let active:string|undefined;
47
59
  let disposedState:ActiveBlocks|undefined;
48
60
  const state=()=>disposedState??Object.fromEntries([...rows].map(([name,row])=>[name,row.state()!]));
@@ -50,7 +62,7 @@ export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlo
50
62
  const resolve=(name:string,id:string)=>id==='transport'&&!ids.get(name)?.has(id)?'motion-tools':id;
51
63
  for(const section of options.sections){
52
64
  const name=section.dataset.inspectorPanel??'';if(!name)continue;
53
- // In Animate the row heads the blocks panel beside the timeline; that panel is what scrolls.
65
+ // In Animate the row heads the section directly and switches the whole panel body.
54
66
  const children=[...section.children],directRow=children.find(isRow) as HTMLElement|undefined;
55
67
  const scrollRoot=directRow?section:children.find(node=>[...node.children].some(isRow)) as HTMLElement|undefined;if(!scrollRoot)continue;
56
68
  const row=directRow??[...scrollRoot.children].find(isRow) as HTMLElement;
@@ -64,7 +76,43 @@ export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlo
64
76
  }
65
77
  if(!tabs.length&&!options.bottom)continue;
66
78
  if(options.bottom){
67
- definitions.set(name,{section,row,scrollRoot,tabs});saved[name]=tabs.find(tab=>tab.button.getAttribute('aria-selected')==='true')?.id??tabs[0]?.id??'feedback';
79
+ let syncOverflow=()=>{};
80
+ if(typeof (doc as Document).createElement==='function'&&tabs.length){
81
+ const placeOverflow=(menu:HTMLElement)=>{
82
+ if(typeof row.getBoundingClientRect!=='function')return;
83
+ const rect=row.getBoundingClientRect(),inspector=row.closest('.inspector'),main=section.closest('main')?.getBoundingClientRect(),bounds=inspector?.getBoundingClientRect();
84
+ // A collapsed inspector retains its heading, not a clipping body.
85
+ const clip=inspector?.getAttribute('data-collapsed')==='true'||!bounds?.height?main:bounds,above=Math.max(0,rect.top-Math.max(clip?.top??0,main?.top??0)-8),below=Math.max(0,Math.min(innerHeight,clip?.bottom??innerHeight,main?.bottom??innerHeight)-rect.bottom-8);
86
+ const up=below<Math.min(menu.scrollHeight,220)&&above>below,height=Math.min(220,up?above:below);menu.dataset.side=up?'above':'below';menu.style.maxHeight=height+'px';
87
+ // Keep the popup in viewport coordinates when native focus scrolls its items.
88
+ menu.style.position='fixed';menu.style.right=Math.max(0,innerWidth-rect.right)+'px';menu.style.top=(up?rect.top-4-Math.min(menu.scrollHeight,height):rect.bottom+4)+'px';menu.style.bottom='auto';
89
+ };
90
+ const items:HTMLButtonElement[]=[],more=bindPopupMenu('workspace-tabs-more-'+name,()=>{syncOverflow();return items.filter(item=>!item.hidden);},cleanups,placeOverflow);
91
+ more.button.className='workspace-tabs-more';more.button.hidden=true;more.menu.className='workspace-tabs-menu';
92
+ const updateItems=()=>{
93
+ for(const item of items.splice(0))item.remove();
94
+ for(const tab of tabs){
95
+ const item=actionButton(tab.button.textContent??'',()=>{more.close(false);rows.get(name)?.select(tab.id);syncOverflow();tab.button.focus();});
96
+ item.setAttribute('role','menuitem');item.dataset.blockMoreTarget=tab.id;item.tabIndex=-1;item.hidden=true;items.push(item);more.menu.append(item);
97
+ }
98
+ };updateItems();
99
+ row.append(more.button,more.menu);
100
+ syncOverflow=()=>{
101
+ if(items.length!==tabs.length)updateItems();
102
+ const label=tr('More tabs');more.button.setAttribute('aria-label',label);more.button.setAttribute('title',label);
103
+ for(const tab of tabs)tab.button.removeAttribute('data-tab-overflow');
104
+ if(row.hidden||!(row.clientWidth>0)){more.button.hidden=true;more.close(false);return;}
105
+ more.button.hidden=false;
106
+ const availableWidth=row.getBoundingClientRect?.().width??row.clientWidth,gap=4,moreWidth=(more.button.getBoundingClientRect?.().width??more.button.offsetWidth??28)+gap,widths=tabs.map(tab=>tab.button.getBoundingClientRect?.().width??tab.button.offsetWidth);
107
+ if(widths.reduce((sum,w,i)=>sum+w+(i>0?gap:0),0)<=availableWidth){more.button.hidden=true;more.close(false);return;}
108
+ const selectedIndex=tabs.findIndex(tab=>tab.button.getAttribute('aria-selected')==='true'),visible=new Set<number>();
109
+ let used=moreWidth+(selectedIndex>=0?widths[selectedIndex]!+gap:0);if(selectedIndex>=0)visible.add(selectedIndex);
110
+ for(let i=0;i<tabs.length;i++)if(i!==selectedIndex){if(used+widths[i]!+gap<=availableWidth){visible.add(i);used+=widths[i]!+gap;}}
111
+ for(const [i,tab]of tabs.entries()){const over=!visible.has(i);if(over)tab.button.setAttribute('data-tab-overflow','true');items[i]!.hidden=!over;items[i]!.disabled=tab.button.disabled;items[i]!.textContent=tab.button.textContent;const title=tab.button.getAttribute('title');if(title)items[i]!.setAttribute('title',title);else items[i]!.removeAttribute('title');}
112
+ if(!more.menu.hidden)placeOverflow(more.menu);
113
+ };
114
+ }
115
+ definitions.set(name,{section,row,scrollRoot,tabs,syncOverflow});saved[name]=tabs.find(tab=>tab.button.getAttribute('aria-selected')==='true')?.id??tabs[0]?.id??'feedback';
68
116
  row.hidden=true;options.bottom.strip.append(row);continue;
69
117
  }
70
118
  ids.set(name,new Set(tabs.map(tab=>tab.id)));
@@ -73,46 +121,84 @@ export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlo
73
121
  panels:tabs.map(tab=>tab.panel),root:row,scrollRoot,initialize:true,
74
122
  }));
75
123
  }
124
+ const syncActiveOverflow=()=>{if(active)definitions.get(active)?.syncOverflow();};
125
+ if(options.bottom&& [...definitions.values()].some(d=>typeof (d.section.ownerDocument as Document).createElement==='function')){
126
+ cleanups.push(onLanguageChange(syncActiveOverflow));
127
+ if(typeof ResizeObserver==='function'){const ro=new ResizeObserver(syncActiveOverflow);ro.observe(options.bottom.strip);cleanups.push(()=>ro.disconnect());}
128
+ }
76
129
  // Rebind the existing tab controller when the header mode changes. The shared Comments
77
130
  // button/panel retain identity; each mode retains its own last selected block.
78
- const activate=(name:string)=>{
131
+ const activate=(name:string,force=false)=>{
79
132
  if(!options.bottom||!definitions.has(name))return;
80
- if(active===name)return;
133
+ if(active===name&&!force)return;
81
134
  if(active){saved[active]=rows.get(active)?.state()??saved[active]!;rows.get(active)?.dispose();rows.delete(active);definitions.get(active)!.row.hidden=true;}
82
- active=name;const {section,row,scrollRoot,tabs}=definitions.get(name)!,bottom=options.bottom;
83
- bottom.comment.dataset.blockTarget='feedback';row.append(bottom.comment);row.hidden=false;
135
+ active=name;const {section,row,scrollRoot,tabs,syncOverflow}=definitions.get(name)!,bottom=options.bottom;
136
+ bottom.comment.dataset.blockTarget='feedback';bottom.comment.hidden=true;bottom.comment.remove();row.hidden=false;
84
137
  const all=[...tabs,{button:bottom.comment,id:'feedback',panel:bottom.panel,included:[]}];
85
138
  ids.set(name,new Set(all.map(tab=>tab.id)));
86
- const sync=()=>{section.dataset.comments=String(rows.get(name)?.state()==='feedback');options.changed?.();};
139
+ const sync=()=>{section.dataset.comments=String(rows.get(name)?.state()==='feedback'||external.has(rows.get(name)?.state()??''));syncOverflow();options.changed?.();};
87
140
  for(const tab of all)tab.button.setAttribute('aria-selected',String(tab.id===saved[name]));
88
141
  rows.set(name,bindInspectorTabs(sync,()=>{},{tabs:all.map(tab=>({id:tab.id,button:tab.button,panels:[tab.panel],included:tab.included,attribute:'aria-selected'})),panels:all.map(tab=>tab.panel),root:row,scrollRoot,initialize:true}));
89
- section.dataset.comments=String(saved[name]==='feedback');
142
+ section.dataset.comments=String(saved[name]==='feedback'||external.has(saved[name]!));
143
+ for(const tab of tabs)if(external.has(tab.id))tab.panel.setAttribute('aria-labelledby',tab.button.id);syncOverflow();
90
144
  };
91
145
  if(options.bottom)activate(options.sections[0]?.dataset.inspectorPanel??'');
92
146
  return {
93
147
  state:()=>({...saved,...state()}),activate,
94
- select:(name,id)=>{rows.get(name)?.select(resolve(name,id));},
148
+ register(tab){
149
+ if(!options.bottom||external.has(tab.id))return ()=>{};
150
+ external.add(tab.id);tab.panel.hidden=true;tab.panel.setAttribute('role','tabpanel');
151
+ const buttons:HTMLButtonElement[]=[];
152
+ for(const [name,definition]of definitions){
153
+ const button=actionButton(tr(tab.label),null);button.id='inspector-tab-'+name+'-'+tab.id;
154
+ button.dataset.blockTarget=tab.id;button.setAttribute('role','tab');button.setAttribute('aria-controls',tab.panel.id);button.setAttribute('aria-selected','false');button.tabIndex=-1;
155
+ definition.row.insertBefore(button,tab.position==='first'?definition.tabs[0]?.button??null:definition.row.querySelector('.workspace-tabs-more'));buttons.push(button);
156
+ const entry={button,id:tab.id,panel:tab.panel,included:[]};
157
+ if(tab.position==='first')definition.tabs.unshift(entry);else definition.tabs.push(entry);
158
+ }
159
+ const localize=onLanguageChange(()=>{for(const button of buttons)setSourceText(button,tab.label);syncActiveOverflow();});
160
+ if(active)activate(active,true);
161
+ let removed=false;
162
+ const remove=()=>{if(removed)return;removed=true;localize();external.delete(tab.id);
163
+ for(const [name,definition]of definitions){definition.tabs.splice(definition.tabs.findIndex(item=>item.id===tab.id),1);if(rows.get(name)?.state()===tab.id)rows.get(name)?.select(definition.tabs[0]?.id??'feedback');if(saved[name]===tab.id)saved[name]=definition.tabs[0]?.id??'feedback';}
164
+ for(const button of buttons)button.remove();tab.panel.hidden=true;if(active)activate(active,true);
165
+ };
166
+ cleanups.push(remove);return remove;
167
+ },
168
+ select:(name,id)=>{rows.get(name)?.select(resolve(name,id));definitions.get(name)?.syncOverflow();},
95
169
  /** Restore saved tabs without touching the workspace's section scroll offset. */
96
- restore(value){for(const [name,id]of Object.entries(value)){if(options.bottom){const definition=definitions.get(name);if(id==='feedback'||definition?.tabs.some(tab=>tab.id===resolve(name,id)))saved[name]=resolve(name,id);}rows.get(name)?.restore(resolve(name,id));}},
97
- dispose(){disposedState=state();for(const row of rows.values())row.dispose();rows.clear();ids.clear();},
170
+ restore(value){for(const [name,id]of Object.entries(value)){if(options.bottom){const definition=definitions.get(name);if(id==='feedback'||definition?.tabs.some(tab=>tab.id===resolve(name,id)))saved[name]=resolve(name,id);}rows.get(name)?.restore(resolve(name,id));definitions.get(name)?.syncOverflow();}},
171
+ dispose(){disposedState=state();for(const cleanup of cleanups)cleanup();for(const row of rows.values())row.dispose();rows.clear();ids.clear();},
98
172
  };
99
173
  }
100
174
 
101
175
  /** Compose the real rig acts into C6; all fields, submit nodes and their listeners retain identity. */
102
- export function mountRigInspector(root:Document=document):BottomPanel&{actBar:ActBar;comments:{button:HTMLButtonElement;panel:HTMLElement}} {
176
+ export function mountRigInspector(root:Document=document,actHome?:HTMLElement):BottomPanel&{actBar:ActBar;answersRendered:boolean;syncActRow:()=>void;comments:{button:HTMLButtonElement;panel:HTMLElement}} {
103
177
  const inspector=root.querySelector<HTMLElement>('.inspector')!,body=inspector.querySelector<HTMLElement>('.inspector-body')!,heading=inspector.querySelector<HTMLElement>('.inspector-heading')!;
104
178
  const feedback=root.getElementById('inspector-feedback')!,dialog=root.getElementById('review-dialog')!;
105
179
  const [label,status,actions]=[feedback.querySelector<HTMLLabelElement>('label[for="review-status"]')!,root.getElementById('review-status')!,dialog.querySelector<HTMLElement>('.review-dialog-actions')!];
106
- const actBar=mountActBar({id:'workspace-review-act',decision:[label,status],actions,submit:root.getElementById('save') as HTMLButtonElement,saveState:root.getElementById('review-draft-state')!,saveStateCopies:[root.getElementById('draft-state')].flatMap(node=>node?[{node,title:true}]:[])}),act=actBar.element;
180
+ const actBar=mountActBar({id:'workspace-review-act',decision:[label,status],actions,submit:root.getElementById('save') as HTMLButtonElement,saveState:root.getElementById('review-draft-state')!,saveStateCopies:[root.getElementById(actHome?'dirty':'draft-state')].flatMap(node=>node?[{node,title:true}]:[])}),act=actBar.element;
181
+ if(actHome)for(const id of ['draft-state','draft-recovery'])root.getElementById(id)!.hidden=true;
107
182
  const title=dialog.querySelector<HTMLElement>('.review-dialog-header')!;title.querySelector('#review-dialog-close')?.remove();
108
183
  feedback.className='workspace-review-panel';feedback.hidden=true;feedback.prepend(title);body.append(feedback);dialog.remove();
109
184
  feedback.removeAttribute('data-inspector-panel');
110
- const bottom=mountBottomPanel({kind:'rig',heading,act,actHome:heading,tabs:[{id:'feedback',label:'Comments (0)',panel:feedback}]}),comment=bottom.row.tabs[0]!.button;
185
+ root.getElementById('proposal-panel')!.prepend(root.getElementById('comments-list-host')!);
186
+ const bottom=mountBottomPanel({kind:'rig',heading,act,actHome:actHome??heading,tabs:[]}),comment=actionButton(tr('Comments'),null);
187
+ comment.hidden=true;feedback.setAttribute('role','region');feedback.setAttribute('aria-labelledby','stage-comment');
111
188
  delete comment.dataset.inspector;bottom.strip.removeAttribute('role');
112
189
  for(const button of root.querySelectorAll<HTMLButtonElement>('[data-mode][data-inspector]')){button.id||='mode-'+button.dataset.mode;const panel=root.getElementById('inspector-'+button.dataset.mode)!;panel.setAttribute('role','region');panel.setAttribute('aria-labelledby',button.id);}
113
190
  bottom.row={tabs:[...root.querySelectorAll<HTMLButtonElement>('[data-mode][data-inspector]')].map(button=>({id:button.dataset.mode!,button,attribute:'aria-pressed',panels:[root.getElementById('inspector-'+button.dataset.mode)!]})),panels:[root.getElementById('inspector-rig')!,root.getElementById('inspector-playback')!],initialize:true};
114
- heading.append(act);
115
- return {...bottom,actBar,comments:{button:comment,panel:feedback}};
191
+ bottom.actHome.append(act);
192
+ const syncActRow=()=>{
193
+ if(!actHome)return;
194
+ const headline=root.getElementById('workspace-ask-headline'),error=root.getElementById('review-message');
195
+ const question=!!headline&&!headline.hidden&&!!headline.textContent?.trim();
196
+ const refusal=!!error&&!error.hidden&&error.classList.contains('error')&&!!error.textContent?.trim()&&['save','request-changes','workspace-pending-ask'].every(id=>root.getElementById(id)?.hidden!==false);
197
+ // Loading may render answers before the question; an early read refusal can
198
+ // still use this row once its caller has hidden every answer control.
199
+ actHome.hidden=act.hidden||(!question&&!refusal);root.getElementById('dirty')!.hidden=!actHome.hidden;
200
+ };
201
+ return {...bottom,actBar,answersRendered:false,syncActRow,comments:{button:comment,panel:feedback}};
116
202
  }
117
203
 
118
204
  export interface BottomPanel {
@@ -134,7 +220,7 @@ export function mountBottomPanel(options:BottomPanelOptions):BottomPanel {
134
220
  panel.setAttribute('role','tabpanel');panel.setAttribute('aria-labelledby',button.id);
135
221
  strip.append(button);return {id,button,panels:[panel],attribute:'aria-selected' as const};
136
222
  });
137
- const collapse=actionButton(tr('Collapse bottom panel'),null);collapse.id='workspace-bottom-collapse';collapse.setAttribute('aria-expanded','true');collapse.setAttribute('aria-controls','workspace-inspector');
223
+ const collapseLabel=tr('Collapse bottom panel'),collapse=actionButton('⌄',null);collapse.id='workspace-bottom-collapse';collapse.setAttribute('aria-expanded','true');collapse.setAttribute('aria-controls','workspace-inspector');collapse.setAttribute('aria-label',collapseLabel);collapse.setAttribute('title',collapseLabel);
138
224
  options.heading.replaceChildren(strip,collapse);
139
225
  return {row:{tabs,panels:tabs.flatMap(tab=>tab.panels),initialize:true},strip,act:options.act,actHome:options.actHome,collapse,kind:options.kind};
140
226
  }
@@ -164,25 +250,13 @@ export function mountActBar(options:ActBarOptions):ActBar {
164
250
  const cleanups:(()=>void)[]=[],labels:{button:HTMLButtonElement;label:string}[]=[];
165
251
  const listen=(node:HTMLElement,type:string,fn:(event:Event)=>void)=>{node.addEventListener(type,fn);cleanups.push(()=>node.removeEventListener(type,fn));};
166
252
  if(options.overflow?.length){
167
- const button=actionButton('⋯',null),menu=panelMake('div',{id:options.id+'-menu',hidden:true});
168
- button.setAttribute('aria-haspopup','menu');button.setAttribute('aria-controls',menu.id);button.setAttribute('aria-expanded','false');
169
- menu.setAttribute('role','menu');
170
- const close=(focus=true)=>{menu.hidden=true;button.setAttribute('aria-expanded','false');if(focus)button.focus();};
171
- const items=options.overflow.map(action=>{
253
+ const items:HTMLButtonElement[]=[],more=bindPopupMenu(options.id+'-menu',()=>items,cleanups);
254
+ for(const action of options.overflow){
172
255
  const item=actionButton(tr(action.label),null);item.setAttribute('role','menuitem');item.tabIndex=-1;
173
- listen(item,'click',()=>{close();action.handler();});labels.push({button:item,label:action.label});menu.append(item);return item;
174
- });
175
- const open=(last=false)=>{menu.hidden=false;button.setAttribute('aria-expanded','true');items[last?items.length-1:0]!.focus();};
176
- listen(button,'click',()=>menu.hidden?open():close());
177
- listen(button,'keydown',event=>{const key=(event as KeyboardEvent).key;if(['ArrowDown','ArrowUp','Enter',' '].includes(key)){event.preventDefault();open(key==='ArrowUp');}else if(key==='Escape'){event.preventDefault();close();}});
178
- listen(menu,'keydown',event=>{
179
- const key=(event as KeyboardEvent).key;
180
- if(key==='Escape'){event.preventDefault();close();return;}
181
- if(['ArrowDown','ArrowUp','Home','End'].includes(key)){event.preventDefault();const index=items.indexOf(event.target as HTMLButtonElement);items[key==='Home'?0:key==='End'?items.length-1:(index+(key==='ArrowDown'?1:items.length-1))%items.length]!.focus();}
182
- });
183
- listen(menu,'focusout',event=>{const target=(event as FocusEvent).relatedTarget;if(target!==button&&!menu.contains(target as Node|null))close(false);});
256
+ listen(item,'click',()=>{more.close();action.handler();});labels.push({button:item,label:action.label});more.menu.append(item);items.push(item);
257
+ }
184
258
  // Item listeners own activation; events from the sibling popup never trigger submit.
185
- actions.append(button,menu);labels.push({button,label:'More act actions'});
259
+ actions.append(more.button,more.menu);labels.push({button:more.button,label:'More act actions'});
186
260
  }
187
261
  const refresh=()=>{
188
262
  if(options.submitLabel!==undefined)options.submit.textContent=tr(typeof options.submitLabel==='function'?options.submitLabel():options.submitLabel);
@@ -6,6 +6,11 @@ import { createViewControls } from './view-controls.ts';
6
6
  import {WorkspacePreferenceStore,panelBounds} from './workspace-preferences.ts';
7
7
  import { createPartsViewport } from './parts-viewport-provider.ts';
8
8
 
9
+ /** The active image-question form is mounted only while it owns the main reference pane. */
10
+ export function hasTransientQuestionImage(root:{querySelector(selector:string):Element|null}=document):boolean {
11
+ return root.querySelector('#workspace-interview-answer[data-question-image-active=true] [data-interview-main]')!==null;
12
+ }
13
+
9
14
  type Ask = InterviewQuestion['set']['asks'][number];
10
15
  type Pick = Picks['picks'][number];
11
16
  /** Element factory: the stage interview translates with `t`; the job page tags `data-job-text` for its own relocalize. */
@@ -28,6 +33,14 @@ function element<K extends keyof HTMLElementTagNameMap>(tag: K, content?: string
28
33
  return el;
29
34
  }
30
35
  const translated: InterviewText = (tag, key) => element(tag, key === undefined ? undefined : t(key));
36
+ function preserveScrollAndFocus(anchor: HTMLElement, mutate: () => void): void {
37
+ const active = typeof HTMLElement !== 'undefined' && document.activeElement instanceof HTMLElement ? document.activeElement : null;
38
+ const scrolls: [HTMLElement, number, number][] = [];
39
+ for (let node: HTMLElement | null = anchor; node; node = node.parentElement) scrolls.push([node, node.scrollTop, node.scrollLeft]);
40
+ mutate();
41
+ for (const [node, top, left] of scrolls) {if (node.scrollTop !== top) node.scrollTop = top; if (node.scrollLeft !== left) node.scrollLeft = left;}
42
+ if (active?.isConnected && document.activeElement !== active) active.focus({preventScroll:true});
43
+ }
31
44
  /** The `rig-review/interview-picks@1` record exactly as the stage interview has always posted it (key order is the file's bytes). */
32
45
  export function interviewPicksRecord(ref: Picks['set'], picks: readonly Pick[], note: string | undefined, at: string): Picks {
33
46
  return {schema:'rig-review/interview-picks@1', set:ref, picks:picks as Pick[], ...(note !== undefined ? {note} : {}), by:'user', at};
@@ -66,7 +79,7 @@ export function interviewAskGroup(ask: Ask, options: {text?: InterviewText; name
66
79
  const label = make('label'); label.className = 'interview-option';
67
80
  const radio = make('input'); radio.type = 'radio'; radio.name = options.name ?? ask.id; radio.value = option.id;
68
81
  radio.required = true; radio.checked = option.id === pick?.option_id;
69
- radio.onchange = () => {
82
+ radio.onchange = () => preserveScrollAndFocus(group, () => {
70
83
  if (!radio.checked) return;
71
84
  other.hidden = option.kind !== 'other';
72
85
  other.required = option.kind === 'other';
@@ -76,7 +89,7 @@ export function interviewAskGroup(ask: Ask, options: {text?: InterviewText; name
76
89
  pending.textContent = t(key);
77
90
  const next = {ask:ask.id, option_id:option.id};
78
91
  options.onPick?.(option.kind === 'other' ? {...next, other_text:other.value} : next);
79
- };
92
+ });
80
93
  label.append(radio, make('strong', option.label), make('span', option.effect));
81
94
  if(option.kind==='auto'){const badge=text('b','interview.delegate');badge.className='interview-delegate';label.append(badge);}
82
95
  if (option.recommended) {
@@ -202,7 +215,7 @@ export function interviewRecords(diagnostics:readonly InterviewDiagnostic[]=[],h
202
215
 
203
216
  /** B's list | image | survey builder. Hosts supply genuine source data and their own submit transport. */
204
217
  export function createInterviewForm(options:{question:InterviewDisplayQuestion;id:string;node?:InterviewText;form?:HTMLFormElement;fieldset?:HTMLFieldSetElement;source?:HTMLElement;
205
- images:readonly {name:string;src:string}[];questions?:readonly {label:string;answered:boolean}[]|(()=>readonly {label:string;answered:boolean}[]);selected?:number;onSelect?:(index:number)=>void;answered?:boolean;
218
+ mainView?:boolean;images:readonly {name:string;src:string}[];questions?:readonly {label:string;answered:boolean}[]|(()=>readonly {label:string;answered:boolean}[]);selected?:number;onSelect?:(index:number)=>void;answered?:boolean;
206
219
  diagnostics?:readonly InterviewDiagnostic[];historical?:readonly HistoricalInterview[]}) {
207
220
  const question=options.question,copy=new Map<HTMLElement,string>();
208
221
  const make=<K extends keyof HTMLElementTagNameMap>(tag:K,content?:string)=>element(tag,content,options.node);
@@ -231,22 +244,25 @@ export function createInterviewForm(options:{question:InterviewDisplayQuestion;i
231
244
  if(question.partsUnavailable)context.append(node('p','interview.partsUnavailable'));
232
245
  const provenance=make('p'),binding=make('code',question.ref.path+' · '+question.ref.sha256);context.append(provenance,binding);
233
246
  if(question.answer)context.append(make('pre',[question.answer.by,question.answer.at,question.answer.source].filter(value=>typeof value==='string').join(' · ')),make('pre',typeof question.answer.verbatim==='string'?question.answer.verbatim:''));
247
+ if(options.mainView&&options.images.length){form.dataset.interviewMain='';Object.assign(form,{interviewImages:options.images});}
234
248
  const art=make('aside');art.className='interview-art';form.prepend(art);
235
249
  let view:ReturnType<typeof interviewImageView>|undefined,list:HTMLElement|undefined,records:HTMLElement|undefined;
236
250
  const showImage=(index:number)=>{view?.dispose();view?.element.remove();view=interviewImageView(options.images,index,showImage,context);art.append(view.element);};
237
- const refresh=()=>{
251
+ const refresh=()=>preserveScrollAndFocus(fields,()=>{
252
+ submit.hidden=!question.editable||form.dataset.interviewAnswered==='true';
238
253
  provenance.textContent=t('interview.provenance',[question.set.drafted_by,question.set.drafted_at]);
239
254
  const questions=typeof options.questions==='function'?options.questions():options.questions;
240
255
  const items=questions?.map((item,index)=>({...item,answered:index===(options.selected??0)?form.dataset.interviewAnswered==='true':item.answered}))??[{label:question.set.question+' · '+question.set.id,answered:form.dataset.interviewAnswered==='true'}];
241
- const next=interviewQuestionList(items,options.selected??0,options.onSelect??(()=>{}),false,options.node);list?.remove();form.prepend(next);list=next;
256
+ const listTop=list?.scrollTop??0,listLeft=list?.scrollLeft??0;
257
+ const next=interviewQuestionList(items,options.selected??0,options.onSelect??(()=>{}),false,options.node);list?.remove();form.prepend(next);next.scrollTop=listTop;next.scrollLeft=listLeft;list=next;
242
258
  records?.remove();records=interviewRecords(options.diagnostics,options.historical,options.node);context.append(records);
243
- };
244
- const submit=node('button','interview.save');submit.type='submit';submit.hidden=!question.editable;fields.append(submit);
259
+ });
260
+ const submit=node('button','interview.save');submit.type='submit';submit.hidden=!question.editable;
245
261
  const status=node('p',!question.editable?'interview.history':question.saved?'interview.saved':'interview.choose');status.setAttribute('role','status');form.append(status);
246
262
  const localize=()=>{for(const [item,key]of copy)item.textContent=t(item.dataset.jobText??key);refresh();};
247
263
  const dispose=()=>{view?.dispose();form.removeEventListener('input',refresh);form.removeEventListener('change',refresh);form.removeEventListener('job-form-language',localize);};
248
264
  form.addEventListener('input',refresh);form.addEventListener('change',refresh);form.addEventListener('job-form-language',localize);
249
- try{if(options.images.length)showImage(0);else art.append(context);refresh();}catch(error){dispose();throw error;}
265
+ try{if(!options.mainView&&options.images.length)showImage(0);else{art.hidden=true;fields.append(context);}fields.append(submit);refresh();}catch(error){dispose();throw error;}
250
266
  return {form,fieldset:fields,submit,status,retainedNote,
251
267
  read:()=>jobInterviewValue(question.set.question,question.set.asks,item=>answers.find(answer=>answer.item===item)!.answer.value(),retainedNote??''),
252
268
  localize,dispose};