rig-review 1.4.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/main.ts CHANGED
@@ -16,7 +16,7 @@ import {bindDensityStrip,type DensityStripPanel,type DensityStripViewLike} from
16
16
  import {densityField,densityPath} from '../src/density-strip.ts';
17
17
  import {assertMeshPatch,countsText,meshApplyOutcome,meshPatchOps,setEntryValue,triangleAgreement,type MeshEntry} from '../src/mesh-entry.ts';
18
18
  import {worstLine} from '../src/readings.ts';
19
- import {chestOverlayCircles,chestOverlayPolygons,chestRegionRows,chestRowId,evaluateChestForm} from './chest-regions-tool.ts';
19
+ import {chestOverlayPolygons,chestRegionRows,chestRowId,evaluateChestForm} from './chest-regions-tool.ts';
20
20
  import {bindChestEditor,canvasToCrop,bustLabel,bustSides,chestPoseOffset,LANDMARKS,landmarkInputId,posedChestMapping,rowShape,type ChestEditor,type LandmarkKey} from './chest-editor.ts';
21
21
  import {bindMeshEditor,meshEditSource,sha256Hex,type MeshEditor} from './mesh-editor.ts';
22
22
  import {bindWeightsView,setupPoseMesh,type WeightsView} from './weights-view.ts';
@@ -62,6 +62,7 @@ import {appliedBuildOwner,appliedPanelOps,dropNoticeForPanel,reconcilePanelStatu
62
62
  import {bindPhysicsPanel,type PhysicsPanel} from './physics-panel.ts';
63
63
  import {bindIdlePanel,type BoneSetup,type IdlePanel} from './idle-panel.ts';
64
64
  import {composeAdjust,PhysicsPreview} from './preview.ts';
65
+ import {advancePlayback,cueDue} from './playback-clock.ts';
65
66
  import {bindRigFieldsPanel,type RigFieldsPanel} from './rig-fields-panel.ts';
66
67
  import {assertRigFieldOps,RIG_FIELDS_READOUT_BARS,TURN_BONE} from '../src/rig-fields.ts';
67
68
  import {IDLE_READOUT_BARS,type LocalChannel} from '../src/idle-tracks.ts';
@@ -103,6 +104,8 @@ let time = 0;
103
104
  let stageClock: StageClock | null = null;
104
105
  let duration = 0;
105
106
  let lastFrame = 0;
107
+ /** #346: wall-clock seconds accumulated toward the next fixed playback step. */
108
+ let playbackCarry = 0;
106
109
  type CameraTarget='rig'|'reference';
107
110
  let cameraSync=true,activeCamera:CameraTarget='rig',cameraRestoring=false,cameraLayout='';
108
111
  const cameraFrames:Partial<Record<CameraTarget,CameraFrame>>={};
@@ -505,7 +508,7 @@ function chooseAnimation(name: string, move: ClipMove = { kind: 'choose' }): voi
505
508
  select('animation-select').value = name;
506
509
  // #191: the wind restarts before the clip's first frame is drawn, so the paused stage shows the schedule's t=0 world.
507
510
  time = 0; clipMoved(move);
508
- if (player && runtimeAnimation) { drawRig(()=>{player!.play(name,{loop:false});player!.pause();refreshAnimationInspection();player!.draw();}); }
511
+ if (player && runtimeAnimation) { drawRig(()=>{player!.play(name,{loop:canRepeatIdle()});player!.pause();refreshAnimationInspection();player!.draw();}); }
509
512
  else if (player && name){text('renderer-state',rendererStatus(null,'failed').label);message(`Animation "${name}" is not present in the rig.`, true);}
510
513
  renderTransport(); renderCues();renderIdle();
511
514
  }
@@ -519,7 +522,7 @@ function seek(value: number, move?: ClipMove): void {
519
522
  }
520
523
 
521
524
  function stopAudio(): void { for (const audio of audioPlaying) audio.pause(); audioPlaying.clear(); }
522
- function pause(): void { ++playbackIntent;desiredPlay=false;suspendedPreview=false;idleHeld=true; playing = false; lastFrame = 0; player?.pause(); video?.pause(); stopAudio(); button('play').textContent = '▶'; button('play').setAttribute('aria-label', 'Play'); }
525
+ function pause(): void { ++playbackIntent;desiredPlay=false;suspendedPreview=false;idleHeld=true; playing = false; lastFrame = 0; playbackCarry = 0; player?.pause(); video?.pause(); stopAudio(); button('play').textContent = '▶'; button('play').setAttribute('aria-label', 'Play'); }
523
526
 
524
527
  async function audition(clipId: string): Promise<void> {
525
528
  const clip = data.manifest.audio.clips.find(item => item.id === clipId); if (!clip) return;
@@ -646,11 +649,16 @@ function seekReading(clip: string, frame: number, exact: number | null, label: s
646
649
  function tick(now: number): void {
647
650
  if (playing) {
648
651
  const dt = lastFrame ? Math.min((now - lastFrame) / 1000, .1) : 0;
649
- const previous = time; time = Math.min(duration, time + dt);
650
- if (player && player.current) { try { stepEnvironment(dt); drawRig(()=>player!.frame(dt)); } catch (error) { pause(); message(errorText(error), true); } }
652
+ // #346: fixed PLAYBACK_STEP steps from wall-clock time; a repeating clip wraps here with no seek, so physics carries across the loop.
653
+ const previous = time, next = advancePlayback({ time, duration, carry: playbackCarry, elapsed: dt, repeat: canRepeatIdle() && !idleHeld });
654
+ playbackCarry = next.carry; time = next.time;
655
+ const stepped = next.steps.reduce((sum, step) => sum + step, 0);
656
+ // The wrap does what the replaced seek(0) did besides the player: restart the wind clock and re-hold the reference at the wrapped time.
657
+ if (next.wrapped) { stopAudio(); clipMoved({ kind: 'replay' }); if (video) { if (video.readyState >= 1) holdVideoReference(video, referenceGeneration); void video.play().catch(error => { pause(); message(errorText(error), true); }); } }
658
+ if (player && player.current && next.steps.length) { try { stepEnvironment(stepped); drawRig(()=>{ for (const step of next.steps) player!.advance(step); player!.draw(); }); } catch (error) { pause(); message(errorText(error), true); } }
651
659
  if (video && video.readyState >= 1 && time > video.duration) { if (referenceInput.state !== 'out-of-domain') holdVideoReference(video, referenceGeneration); } else if (video && referenceInput.state === 'loaded' && Math.abs(video.currentTime - time) > .15) video.currentTime = time;
652
- if (input('sync-audio').checked) for (const cue of activeCues()) if ((previous < cue.time && cue.time <= time) || (previous === 0 && cue.time === 0 && dt > 0)) void audition(cue.clip);
653
- renderSequenceFrame(); renderTransport(); if(time>=duration){if(canRepeatIdle()&&!idleHeld){stopAudio();seek(0,{kind:'replay'});player?.resume();if(video)void video.play().catch(error=>{pause();message(errorText(error),true);});}else pause();} lastFrame = now;
660
+ if (input('sync-audio').checked) for (const cue of activeCues()) if (cueDue(cue.time, previous, next, duration)) void audition(cue.clip);
661
+ renderSequenceFrame(); renderTransport(); if (next.ended) pause(); lastFrame = now;
654
662
  }
655
663
  requestAnimationFrame(tick);
656
664
  }
@@ -700,7 +708,7 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
700
708
  function chooseAxis(): void {
701
709
  const axis = data.manifest.axes.find(item => item.id === select('axis-select').value);
702
710
  const clip = assets?.animations.find(item => item.name === axis?.animation); if (!axis || !clip || !player) return;
703
- pause(); chooseAnimation(clip.name); axisInspection = true; el('angle-panel').hidden = false;
711
+ pause(); chooseAnimation(clip.name); axisInspection = true; syncPlayerLoop(); el('angle-panel').hidden = false;
704
712
  input('axis-value').min = String(axis.min); input('axis-value').max = String(axis.max); input('axis-value').step = String((axis.max - axis.min) / 200); input('axis-value').value = String((axis.max + axis.min) / 2); text('axis-label', axis.label); applyAxis();
705
713
  }
706
714
 
@@ -963,7 +971,7 @@ function bind(): void {
963
971
  for(const target of ['rig','reference'] as const)viewDisposers.push(bindPan(el(target+'-viewport'),(dx,dy)=>cameraAction(()=>panCamera(target,dx,dy)),()=>!comments?.active(),target==='rig'?carryRig:undefined));
964
972
  for(const [id,key] of [['layer-images','images'],['layer-mesh','mesh'],['layer-bones','bones']] as const)input(id).onchange=()=>{layers[key]=input(id).checked;redrawOverlay(false);};
965
973
  viewDisposers.push(bindLayerShortcuts(document));describeLayerToggles(document,el('layer-state').textContent??'');
966
- input('idle-repeat').onchange=()=>{renderIdle();if(canRepeatIdle())void playPreview();};
974
+ input('idle-repeat').onchange=()=>{syncPlayerLoop();renderIdle();if(canRepeatIdle())void playPreview();};
967
975
  bindEnvironment();
968
976
  for(const id of ['proposal-panel','checkpoint-detail'])el(id).addEventListener('focusin',pause);
969
977
  bindInspector();bindReviewDialog();
@@ -1029,11 +1037,21 @@ function redrawOverlay(fresh:boolean):void {
1029
1037
  lastOverlay=value;
1030
1038
  text('layer-state',value.warnings.join(' · ')||'Actual last-drawn mesh edges / bone points');idlePanel?.place(duration);rigFieldsPanel?.place();if(!fresh&&value.needsCapture&&!playing&&!seekingControl)drawRig(()=>player!.draw());
1031
1039
  }
1040
+ /**
1041
+ * #346: the player loops exactly when Animate repeats, so a repeating clip wraps inside the track and its physics
1042
+ * carries across the seam. Changing the mode reopens the track at the current time, as a seek does.
1043
+ */
1044
+ function syncPlayerLoop():void {
1045
+ const want=canRepeatIdle();
1046
+ if(!player?.current||player.composed||player.entry(0)?.loop===want)return;
1047
+ try{drawRig(()=>{player!.play(animation,{loop:want});if(!playing)player!.pause();player!.seek(time);player!.draw();});}
1048
+ catch(error){message(errorText(error),true);}
1049
+ }
1032
1050
  function canRepeatIdle():boolean{return !!player&&idleAvailable(assets?.animations.map(a=>a.name)??[],animation)&&!axisInspection&&input('idle-repeat').checked&&duration>0;}
1033
1051
  function renderIdle():void {text('idle-state',canRepeatIdle()?'Actual idle · repeat enabled':animation==='idle'?'Idle repeat paused':'Non-idle inspection · no automatic playback');}
1034
1052
  async function playPreview():Promise<void> {
1035
1053
  if((!player&&!video&&!sequence)||duration<=0)return;
1036
- const intent=++playbackIntent;desiredPlay=true;idleHeld=false;if(time>=duration)seek(0,{kind:'replay'});
1054
+ const intent=++playbackIntent;desiredPlay=true;idleHeld=false;syncPlayerLoop();if(time>=duration)seek(0,{kind:'replay'});
1037
1055
  if(video&&referenceInput.state==='loaded'){try{await video.play();}catch(error){pause();message(`Playback is paused: ${errorText(error)}. Use Play to retry.`,true);return;}}
1038
1056
  if(intent!==playbackIntent||!desiredPlay){if(!desiredPlay)video?.pause();return;}playing=true;lastFrame=0;player?.resume();button('play').textContent='Ⅱ';button('play').setAttribute('aria-label','Pause');
1039
1057
  }
@@ -1181,27 +1199,26 @@ async function setupPersistence():Promise<boolean> {
1181
1199
  function chestField(id:string){const node=document.getElementById(id) as HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement|null;return node?{value:node.value,...(node instanceof HTMLInputElement&&node.type==='checkbox'?{checked:node.checked}:{})}:undefined;}
1182
1200
  function chestEvaluation(){return evaluateChestForm(chestField,chestMapping,data.feedbackCatalog.bones);}
1183
1201
  function chestRegions():OverlayRegion[]{
1202
+ // #345: the chest overlay is drawn only while the Chest regions toggle is on.
1203
+ if(!chestEditor?.active())return [];
1184
1204
  const style=getComputedStyle(document.documentElement),token=(name:string)=>style.getPropertyValue(name).trim();
1185
1205
  return chestOverlayPolygons(chestEvaluation(),activeChestMapping()).map((region,i)=>({...region,stroke:token(i?'--rv-region-b':'--rv-region-a'),fill:token(i?'--rv-region-b-fill':'--rv-region-a-fill')}));
1186
1206
  }
1187
- /** Circle regions: in edit mode the editor's circles straight from the fields (handles and labels), else the valid designation's. */
1207
+ /** Circle regions, only while the toggle is on (#345): the editor's circles straight from the fields (handles and labels), or the landmarks' derivation. */
1188
1208
  function chestCircles():OverlayCircle[]{
1189
- const mapping=activeChestMapping();if(!mapping.available)return [];
1209
+ const mapping=activeChestMapping();if(!mapping.available||!chestEditor?.active())return [];
1190
1210
  const style=getComputedStyle(document.documentElement),token=(name:string)=>style.getPropertyValue(name).trim();
1191
1211
  const colors=(row:number,overlap:boolean)=>({stroke:token(overlap?'--rv-bust-overlap':row?'--rv-bust-l':'--rv-bust-r'),fill:token(overlap?'--rv-bust-overlap-fill':row?'--rv-bust-l-fill':'--rv-bust-r-fill'),handle:token('--rv-bust-handle'),ink:token('--rv-bust-ink'),labelBg:token('--rv-bust-label-bg'),flash:token('--rv-bust-flash')});
1192
- if(chestEditor?.active()&&chestEditor.mode()==='landmarks'){
1212
+ if(chestEditor.mode()==='landmarks'){
1193
1213
  // #105: the producer's derivation drawn live; a CONFIG_BUST_CLEARANCE refusal turns both to the overlap colour.
1194
1214
  const read=chestEditor.landmarks();if(!('derived' in read))return [];
1195
1215
  const refused=!!read.derived.refusal;
1196
1216
  return read.derived.regions.filter(r=>r.r>0&&r.band>=0).map((r,row)=>({center:mapping.toWorld(r.cx,r.cy),r:r.r,band:r.band,label:`${r.name} r:${r.r} b:${r.band}`,labelRow:row,handles:false,colors:colors(row,refused)}));
1197
1217
  }
1198
- if(chestEditor?.active()){
1199
- const rows=bustSides.map(({side,row})=>({side,row,circle:rowShape(chestField,row)})),[r,l]=[rows[0]!.circle,rows[1]!.circle];
1200
- // As in the example, overlapping cores turn both circles to the overlap colour.
1201
- const overlap=!!r&&!!l&&r.r+l.r>Math.hypot(l.cx-r.cx,l.cy-r.cy);
1202
- return rows.flatMap(({side,row,circle})=>circle?[{center:mapping.toWorld(circle.cx,circle.cy),r:circle.r,...(circle.ry===undefined?{}:{ry:circle.ry}),...(circle.clip===undefined?{}:{clipX:mapping.toWorld(circle.clip,circle.cy).x}),band:circle.band,label:bustLabel(side,circle),labelRow:row,handles:true,flash:chestEditor!.flashing(side),colors:colors(row,overlap)}]:[]);
1203
- }
1204
- return chestOverlayCircles(chestEvaluation(),mapping).map(c=>({center:c.center,r:c.r,band:c.band,handles:false,colors:colors(c.row,false)}));
1218
+ const rows=bustSides.map(({side,row})=>({side,row,circle:rowShape(chestField,row)})),[r,l]=[rows[0]!.circle,rows[1]!.circle];
1219
+ // As in the example, overlapping cores turn both circles to the overlap colour.
1220
+ const overlap=!!r&&!!l&&r.r+l.r>Math.hypot(l.cx-r.cx,l.cy-r.cy);
1221
+ return rows.flatMap(({side,row,circle})=>circle?[{center:mapping.toWorld(circle.cx,circle.cy),r:circle.r,...(circle.ry===undefined?{}:{ry:circle.ry}),...(circle.clip===undefined?{}:{clipX:mapping.toWorld(circle.clip,circle.cy).x}),band:circle.band,label:bustLabel(side,circle),labelRow:row,handles:true,flash:chestEditor!.flashing(side),colors:colors(row,overlap)}]:[]);
1205
1222
  }
1206
1223
  /** Landmark markers (#105) in Landmarks mode: apexes in the R / L colours, the cleavage with guides to both apexes. */
1207
1224
  function chestMarkers():OverlayMarker[]{
@@ -1242,7 +1259,7 @@ async function exportChest():Promise<void> {
1242
1259
  const environmentInputs=['wind-base','wind-breeze','wind-gust','wind-repeat','wind-gust-peak','wind-gust-duration','gravity','jolt','physics-reset','environment-use','environment-export','environment-check'];
1243
1260
  function environmentApplied():boolean{return input('environment-applied').checked;}
1244
1261
  function gravityValue():number{return Number(input('gravity').value);}
1245
- /** Called from `tick` right before `player.frame(dt)`: the gust clock is the stepped time, so a paused player freezes it. */
1262
+ /** Called from `tick` right before the fixed playback steps (#346): the gust clock is the stepped time, so a paused player freezes it. */
1246
1263
  function stepEnvironment(dt:number):void {
1247
1264
  if(!player)return;
1248
1265
  wind.advance(dt);
@@ -1696,6 +1713,8 @@ async function applyPatch(patch:ConfigPatch,world:StageWorld|null=null):Promise<
1696
1713
  /** #166: undo the last Apply, and the applied records as the server holds them. */
1697
1714
  undo:()=>undoApply(),history:()=>appliedHistory?JSON.parse(JSON.stringify(appliedHistory)):null,
1698
1715
  status:async()=>rebuildStatus??await loadRebuildStatus(),
1716
+ /** #345: what the stage draws for the chest tools right now (zero of each while the toggle is off). */
1717
+ chest:{drawn:()=>({circles:chestCircles().length,regions:chestRegions().length,markers:chestMarkers().length})},
1699
1718
  physics:{rows:()=>physicsPanel?.rows()??[],chains:()=>physicsPanel?.chains()??[],edits:()=>physicsPanel?.edits()??[],preview:()=>physicsPreview.read(),clearPreview:()=>physicsPanel?.clearPreview(),set:(name:string,field:Parameters<PhysicsPanel['set']>[1],value:number)=>physicsPanel?.set(name,field,value),ramp:(id:string,field:Parameters<PhysicsPanel['set']>[1],root:number,tip:number)=>physicsPanel?.ramp(id,field,root,tip),select:(name:string)=>physicsPanel?.select(name),apply:()=>applyPhysics(physicsPanel?.edits().map(e=>({op:e.op,path:e.path,value:e.value,name:e.name}))??[]),reset:()=>resetPhysicsBuild()},
1700
1719
  /** Inspection only: one slot's posed world geometry on the drawn frame (what the stage drew), for comparing against `rigc render --geometry`. */
1701
1720
  posed:(slot:string)=>{const frame=player?.posedFrame();const found=frame?.order.find(item=>item.slot===slot);return found?JSON.parse(JSON.stringify(found,(key,value)=>key==='bitmap'||key==='image'||key==='page'?undefined:value)):null;},
@@ -0,0 +1,31 @@
1
+ /**
2
+ * One labelled line per producer flag (#348). The producer's own object stays available verbatim beside it (the page
3
+ * puts it behind a collapsed details element); this only names its fields. Field names that rig-parts writes are kept
4
+ * as written. A line whose shape is not the known one falls back to its path, never to a guess.
5
+ */
6
+ type Params = Readonly<Record<string, string | number>>;
7
+ export type Translate = (key: string, params?: Params) => string;
8
+ export type LabelledFlag =
9
+ | { kind: 'faint'; item: string; art: number; maxAlpha: number; box: readonly [number, number, number, number] }
10
+ | { kind: 'check'; item: string; path: string; root: string; status: string | null; entry: Readonly<Record<string, unknown>> };
11
+
12
+ const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
13
+ const str = (v: unknown): v is string => typeof v === 'string';
14
+ const box4 = (v: unknown): v is [number, number, number, number] => Array.isArray(v) && v.length === 4 && v.every(num);
15
+
16
+ export function flagLabel(flag: LabelledFlag, t: Translate): string {
17
+ if (flag.kind === 'faint') return t('Faint island left out of the mesh: {art} px, brightest alpha {alpha}, at {x},{y} {width}×{height} (part-image px).', { art: flag.art, alpha: flag.maxAlpha, x: flag.box[0], y: flag.box[1], width: flag.box[2], height: flag.box[3] });
18
+ const e = flag.entry;
19
+ if (flag.root === 'figure_openings' && str(e.under) && str(e.above) && str(e.animation) && num(e.frame) && num(e.time) && num(e.found_cells) && num(e.allowed_cells))
20
+ return t('{under} opens under {above} · {animation} f{frame} ({time} s) · {found} cells found / {allowed} allowed', { under: e.under, above: e.above, animation: e.animation, frame: e.frame, time: e.time, found: e.found_cells, allowed: e.allowed_cells });
21
+ if (flag.root === 'seam_pairs' && Array.isArray(e.parts) && e.parts.length === 2 && e.parts.every(str) && num(e.px_over_40) && num(e.px_over_80)) {
22
+ const line = t('Seam {a} | {b} · {px40} px over 40 · {px80} px over 80', { a: e.parts[0] as string, b: e.parts[1] as string, px40: e.px_over_40, px80: e.px_over_80 });
23
+ return box4(e.rig_box) ? `${line} · ${t('rig box {x},{y} {width}×{height}', { x: e.rig_box[0], y: e.rig_box[1], width: e.rig_box[2], height: e.rig_box[3] })}` : line;
24
+ }
25
+ if (flag.status !== null) {
26
+ // A gate: its name and status, the part, then the entry's own numeric readings by their producer names.
27
+ const readings = Object.entries(e).filter(([, v]) => num(v)).map(([k, v]) => `${k} ${v}`);
28
+ return [t('{gate} {status} on {part}', { gate: flag.root, status: flag.status, part: flag.item }), ...readings].join(' · ');
29
+ }
30
+ return t('Check line {path}', { path: flag.path });
31
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The part view's pixels (#348), apart from the DOM so a test draws them on a server canvas too: the sentinel
3
+ * background, the part, its alpha alone, and the footprints of the parts drawn in front of it.
4
+ *
5
+ * The footprint is the front parts' own alpha, placed by their rig boxes, tinted one colour at one opacity. Nothing is
6
+ * measured: where the part has no pixel under its occluder, the tint lands on the bare sentinel and reads as its own
7
+ * colour, so a back part that stops at its occluder's edge shows the occluder's shape.
8
+ */
9
+ export interface Box { name: string; index: number; x: number; y: number; w: number; h: number }
10
+ type Ctx = CanvasRenderingContext2D;
11
+ type Source = CanvasImageSource;
12
+
13
+ /** Sentinel backgrounds: colours no art is expected to hold, so a sliver of empty canvas is plain. */
14
+ export const SENTINELS: Readonly<Record<string, string>> = { green: '#00ff00', magenta: '#ff00ff', black: '#000000', white: '#ffffff' };
15
+ export const BACKGROUNDS = ['green', 'magenta', 'black', 'white', 'checker'] as const;
16
+ /** The footprint tint and its opacity: cyan at half, so over green it is (0,255,128) and over art it mixes with the art. */
17
+ export const FOOTPRINT_RGB: readonly [number, number, number] = [0, 255, 255], FOOTPRINT_ALPHA = 0.5;
18
+ export const CHECKER = 8;
19
+
20
+ export function paintBackground(ctx: Ctx, w: number, h: number, bg: string): void {
21
+ if (bg === 'checker') {
22
+ for (let y = 0; y < h; y += CHECKER) for (let x = 0; x < w; x += CHECKER) { ctx.fillStyle = ((x + y) / CHECKER) % 2 ? '#bdbdbd' : '#ffffff'; ctx.fillRect(x, y, CHECKER, CHECKER); }
23
+ return;
24
+ }
25
+ ctx.fillStyle = SENTINELS[bg] ?? SENTINELS.green!;
26
+ ctx.fillRect(0, 0, w, h);
27
+ }
28
+
29
+ /** Alpha as grey (white = opaque) over the whole box; the source is drawn on transparent first. */
30
+ export function paintAlphaOnly(ctx: Ctx, source: Source, sx: number, sy: number, w: number, h: number): void {
31
+ ctx.clearRect(0, 0, w, h);
32
+ ctx.drawImage(source, sx, sy, w, h, 0, 0, w, h);
33
+ const data = ctx.getImageData(0, 0, w, h), px = data.data;
34
+ for (let i = 0; i < px.length; i += 4) { const a = px[i + 3]!; px[i] = px[i + 1] = px[i + 2] = a; px[i + 3] = 255; }
35
+ ctx.putImageData(data, 0, 0);
36
+ }
37
+
38
+ /** The parts drawn in front of `item` (later in parts.json, which is in draw order, back first) whose box meets its box. */
39
+ export function frontParts<T extends Box>(items: readonly T[], item: Box): T[] {
40
+ return items.filter(o => o.index > item.index && o.x < item.x + item.w && o.x + o.w > item.x && o.y < item.y + item.h && o.y + o.h > item.y);
41
+ }
42
+
43
+ /** Draws one part's view: background, part (or its alpha), then the tinted footprints of `fronts`. */
44
+ export function paintPart(ctx: Ctx, item: Box, image: Source, options: { bg: string; alpha: boolean; fronts: readonly { box: Box; image: Source }[]; makeCanvas: (w: number, h: number) => HTMLCanvasElement }): void {
45
+ const { w, h } = item;
46
+ if (options.alpha) paintAlphaOnly(ctx, image, 0, 0, w, h);
47
+ else { paintBackground(ctx, w, h, options.bg); ctx.drawImage(image, 0, 0); }
48
+ if (!options.fronts.length) return;
49
+ const mask = options.makeCanvas(w, h), m = mask.getContext('2d')!;
50
+ for (const f of options.fronts) m.drawImage(f.image, f.box.x - item.x, f.box.y - item.y);
51
+ m.globalCompositeOperation = 'source-in';
52
+ m.fillStyle = `rgb(${FOOTPRINT_RGB.join(',')})`;
53
+ m.fillRect(0, 0, w, h);
54
+ ctx.globalAlpha = FOOTPRINT_ALPHA;
55
+ ctx.drawImage(mask, 0, 0);
56
+ ctx.globalAlpha = 1;
57
+ }
package/web/parts.css ADDED
@@ -0,0 +1,51 @@
1
+ :root{--bg:#f6f7f9;--panel:#fff;--line:#d9dde3;--text:#1d232b;--muted:#5f6b7a;--accent:#2563eb;--flag:#d97706;--clean:#15803d;color-scheme:light dark}
2
+ @media (prefers-color-scheme:dark){:root{--bg:#14171c;--panel:#1b2027;--line:#2d343e;--text:#e6e9ee;--muted:#9aa5b4;--accent:#60a5fa;--flag:#f59e0b;--clean:#4ade80}}
3
+ *{box-sizing:border-box}
4
+ body{margin:0;background:var(--bg);color:var(--text);font:13px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif}
5
+ .pv-app{display:flex;flex-direction:column;height:100vh}
6
+ .pv-top{display:flex;align-items:center;gap:16px;padding:8px 14px;border-bottom:1px solid var(--line);background:var(--panel)}
7
+ .pv-brand{font-weight:600;display:flex;align-items:center;gap:6px}
8
+ .pv-mark{display:inline-grid;place-items:center;width:20px;height:20px;border-radius:5px;background:var(--accent);color:#fff;font-size:12px}
9
+ #pv-load{margin-left:auto}
10
+ .pv-subtle{color:var(--muted)}
11
+ .pv-layout{flex:1;display:grid;grid-template-columns:240px minmax(0,1fr) 300px;min-height:0}
12
+ .pv-list,.pv-side{background:var(--panel);overflow:auto;padding:10px}
13
+ .pv-list{border-right:1px solid var(--line)}
14
+ .pv-side{border-left:1px solid var(--line)}
15
+ h2{font-size:11px;letter-spacing:.06em;color:var(--muted);margin:4px 0 8px}
16
+ #pv-items{list-style:none;margin:0;padding:0}
17
+ #pv-items li button{width:100%;display:flex;gap:6px;align-items:center;text-align:left;border:0;background:none;color:inherit;padding:4px 6px;border-radius:5px;cursor:pointer;font:inherit}
18
+ #pv-items li button[aria-current="true"]{background:color-mix(in srgb,var(--accent) 18%,transparent)}
19
+ .pv-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
20
+ .pv-badge{font-size:10px;padding:0 5px;border-radius:8px;border:1px solid var(--line);color:var(--muted)}
21
+ .pv-badge[data-outcome="clean"]{color:var(--clean);border-color:var(--clean)}
22
+ .pv-badge[data-outcome="flagged"]{color:var(--flag);border-color:var(--flag)}
23
+ .pv-count{font-size:10px;color:var(--flag)}
24
+ .pv-stage{display:flex;flex-direction:column;min-width:0;min-height:0}
25
+ .pv-toolbar{display:flex;flex-wrap:wrap;gap:12px;align-items:center;padding:8px 12px;border-bottom:1px solid var(--line)}
26
+ .pv-field{display:flex;align-items:center;gap:5px}
27
+ .pv-group{display:inline-flex;border:1px solid var(--line);border-radius:6px;overflow:hidden}
28
+ .pv-group button{border:0;background:var(--panel);color:inherit;padding:3px 9px;cursor:pointer;font:inherit}
29
+ .pv-group button[aria-pressed="true"]{background:var(--accent);color:#fff}
30
+ .pv-canvas-wrap{flex:1;overflow:auto;padding:16px}
31
+ .pv-canvas-box{position:relative;display:inline-block;line-height:0}
32
+ #pv-canvas{image-rendering:pixelated;image-rendering:crisp-edges;display:block}
33
+ .pv-overlay{position:absolute;inset:0;pointer-events:none}
34
+ .pv-box{position:absolute;border:1px solid #ff0;outline:1px solid #000;pointer-events:auto;cursor:pointer}
35
+ .pv-box[data-flag]{border-color:var(--flag);border-style:dashed;pointer-events:none}
36
+ .pv-box[aria-current="true"]{border-color:#0ff;border-width:2px}
37
+ .pv-box span{position:absolute;left:0;top:-14px;font-size:10px;line-height:12px;background:#000c;color:#fff;padding:0 3px;white-space:nowrap}
38
+ .pv-region-edge{position:absolute;border:1px dashed #0ff;pointer-events:none}
39
+ #pv-caption{padding:0 12px 8px;margin:0}
40
+ #pv-flags{list-style:none;margin:0;padding:0}
41
+ #pv-flags li{border-left:3px solid var(--flag);padding:4px 6px;margin-bottom:6px;background:color-mix(in srgb,var(--flag) 8%,transparent);word-break:break-word}
42
+ #pv-flags code{font-size:11px;display:block;margin-top:4px;color:var(--muted)}
43
+ #pv-flags details{margin-top:3px}
44
+ #pv-flags summary{cursor:pointer;font-size:11px;color:var(--muted)}
45
+ #pv-flags li.pv-none{border-left-color:var(--line);background:none;color:var(--muted)}
46
+ .pv-verdict{margin-top:16px;display:flex;flex-direction:column;gap:6px}
47
+ .pv-outcomes{display:flex;gap:10px}
48
+ .pv-label{font-size:11px;color:var(--muted);margin-top:4px}
49
+ textarea,select{font:inherit;color:inherit;background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px}
50
+ .pv-primary{background:var(--accent);color:#fff;border:0;border-radius:6px;padding:6px 10px;cursor:pointer;font:inherit}
51
+ @media (max-width:900px){.pv-layout{grid-template-columns:1fr}.pv-list,.pv-side{max-height:30vh}}
package/web/parts.html ADDED
@@ -0,0 +1,38 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>rig review parts</title><link rel="stylesheet" href="parts.css"></head>
4
+ <body>
5
+ <div id="parts-app" class="pv-app">
6
+ <header class="pv-top"><div class="pv-brand"><span class="pv-mark">r</span>rig review</div><div><strong id="pv-title">Parts review</strong> <span id="pv-mode" class="pv-subtle"></span></div><span id="pv-load" class="pv-subtle" role="status">Loading…</span></header>
7
+ <div class="pv-layout">
8
+ <aside class="pv-list" aria-label="Parts"><h2 id="pv-list-title">PARTS</h2><ul id="pv-items" data-pv-items></ul></aside>
9
+ <main class="pv-stage">
10
+ <div class="pv-toolbar" role="toolbar" aria-label="View">
11
+ <label class="pv-field">Background <select id="pv-bg" data-pv-bg><option value="green">Green</option><option value="magenta">Magenta</option><option value="black">Black</option><option value="white">White</option><option value="checker">Checker</option></select></label>
12
+ <span class="pv-group" role="group" aria-label="Zoom"><button type="button" data-pv-zoom="1" aria-pressed="true">1×</button><button type="button" data-pv-zoom="2" aria-pressed="false">2×</button><button type="button" data-pv-zoom="4" aria-pressed="false">4×</button></span>
13
+ <label class="pv-field"><input type="checkbox" id="pv-alpha" data-pv-alpha> Alpha only</label>
14
+ <label class="pv-field" id="pv-footprint-control"><input type="checkbox" id="pv-footprints" data-pv-footprints> Footprints of parts in front</label>
15
+ <span class="pv-group" role="group" aria-label="Atlas view" id="pv-atlas-switch" hidden><button type="button" data-pv-view="item" aria-pressed="true">Region</button><button type="button" data-pv-view="page" aria-pressed="false">Pages</button></span>
16
+ </div>
17
+ <div class="pv-canvas-wrap"><div class="pv-canvas-box" id="pv-canvas-box"><canvas id="pv-canvas" data-pv-canvas width="1" height="1"></canvas><div id="pv-overlay" class="pv-overlay"></div></div></div>
18
+ <p id="pv-caption" class="pv-subtle"></p>
19
+ </main>
20
+ <aside class="pv-side">
21
+ <section><h2>PRODUCER FLAGS</h2><ul id="pv-flags" data-pv-flags></ul><p id="pv-flag-sources" class="pv-subtle"></p></section>
22
+ <section class="pv-verdict"><h2>VERDICT</h2>
23
+ <div class="pv-outcomes" role="radiogroup" aria-label="Part outcome">
24
+ <label><input type="radio" name="pv-outcome" value="pending" data-pv-outcome> Pending</label>
25
+ <label><input type="radio" name="pv-outcome" value="clean" data-pv-outcome> Clean</label>
26
+ <label><input type="radio" name="pv-outcome" value="flagged" data-pv-outcome> Flagged</label>
27
+ </div>
28
+ <label class="pv-label" for="pv-note">Note</label><textarea id="pv-note" rows="4" maxlength="10000"></textarea>
29
+ <label class="pv-label" for="pv-overall">Sign-off</label><select id="pv-overall"><option value="pending">Pending</option><option value="approved">Approved</option><option value="changes-requested">Changes requested</option></select>
30
+ <button id="pv-save" type="button" class="pv-primary">Save sign-off</button>
31
+ <p id="pv-save-status" class="pv-subtle" role="status"></p>
32
+ </section>
33
+ </aside>
34
+ </div>
35
+ </div>
36
+ <script type="module" src="parts.js"></script>
37
+ </body>
38
+ </html>
package/web/parts.ts ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The parts and atlas view (#348). Every part on its own, on a sentinel background, at native scale with 2× and 4×
3
+ * nearest-neighbour zoom; the footprints of the parts drawn in front of it; the producer's flags on it; and a
4
+ * per-part verdict saved as `rig-review-parts-verdict/1`. In atlas mode, the pages as packed with every region's box
5
+ * and name, and a click from a region to its own view.
6
+ *
7
+ * Nothing here measures the art: flags come from the producer's files, and the footprint is the front parts' own
8
+ * alpha drawn over the selected part (the parts.json draw order, back first, says which parts are in front).
9
+ */
10
+ import { bindDomI18n, onLanguageChange, t } from './i18n.ts';
11
+ import { pageInstanceAccess } from './instance-access.ts';
12
+ import { connectLiveWindow } from './live-connection.ts';
13
+ import { flagLabel } from './parts-flags.ts';
14
+ import { frontParts, paintAlphaOnly, paintBackground, paintPart } from './parts-render.ts';
15
+
16
+ type Outcome = 'pending' | 'clean' | 'flagged';
17
+ interface Item { name: string; index: number; x: number; y: number; w: number; h: number; page?: string; degrees?: number; image?: boolean }
18
+ interface Page { name: string; width: number; height: number; index: number }
19
+ type Flag =
20
+ | { id: string; item: string; source: 'mesh_report'; kind: 'faint'; art: number; maxAlpha: number; box: [number, number, number, number] }
21
+ | { id: string; item: string; source: 'check'; kind: 'check'; path: string; line: string; root: string; status: string | null; entry: Record<string, unknown> };
22
+ interface ViewData {
23
+ mode: 'parts' | 'atlas'; title: string; rigSize: [number, number] | null; items: Item[]; pages: Page[]; flags: Flag[];
24
+ flagSources: string[]; flagMissing: string[]; verdictFile: string;
25
+ verdict: { status: string; parts: Record<string, { outcome: Outcome; note: string }> } | null; verdictStale: 'files' | 'flags' | null;
26
+ }
27
+
28
+ /** Page pixels shown around a region in its own view, so the packer's bleed and padding are visible. */
29
+ export const REGION_MARGIN = 4;
30
+
31
+ const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
32
+ const access = pageInstanceAccess();
33
+ const state = { data: null as ViewData | null, selected: 0, zoom: 1, bg: 'green', alpha: false, footprints: false, view: 'item' as 'item' | 'page', page: 0, verdict: new Map<string, { outcome: Outcome; note: string }>() };
34
+ const images = new Map<string, HTMLImageElement>();
35
+
36
+ function load(src: string): Promise<HTMLImageElement> {
37
+ const cached = images.get(src);
38
+ if (cached) return Promise.resolve(cached);
39
+ return new Promise((resolve, reject) => {
40
+ const img = new Image();
41
+ img.onload = () => { images.set(src, img); resolve(img); };
42
+ img.onerror = () => reject(new Error(src));
43
+ img.src = access.route(src);
44
+ });
45
+ }
46
+ const itemImage = (item: Item) => load(`/api/parts/image/${item.index}`);
47
+ const pageImage = (name: string) => { const page = state.data!.pages.find(p => p.name === name)!; return load(`/api/parts/page/${page.index}`); };
48
+
49
+ function setCanvas(canvas: HTMLCanvasElement, w: number, h: number): CanvasRenderingContext2D {
50
+ canvas.width = w; canvas.height = h;
51
+ canvas.style.width = `${w * state.zoom}px`; canvas.style.height = `${h * state.zoom}px`;
52
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
53
+ ctx.imageSmoothingEnabled = false;
54
+ return ctx;
55
+ }
56
+
57
+ function overlayBox(x: number, y: number, w: number, h: number): HTMLDivElement {
58
+ const div = document.createElement('div');
59
+ div.className = 'pv-box';
60
+ div.style.left = `${x * state.zoom}px`; div.style.top = `${y * state.zoom}px`;
61
+ div.style.width = `${w * state.zoom}px`; div.style.height = `${h * state.zoom}px`;
62
+ return div;
63
+ }
64
+
65
+ let paintToken = 0;
66
+ async function paint(): Promise<void> {
67
+ const data = state.data;
68
+ if (!data || !data.items.length) return;
69
+ const token = ++paintToken, canvas = $<HTMLCanvasElement>('pv-canvas'), overlay = $('pv-overlay'), caption = $('pv-caption');
70
+ const item = data.items[state.selected]!;
71
+ if (data.mode === 'atlas' && state.view === 'page') {
72
+ const page = data.pages[state.page]!, img = await pageImage(page.name);
73
+ if (token !== paintToken) return;
74
+ const ctx = setCanvas(canvas, page.width, page.height);
75
+ if (state.alpha) paintAlphaOnly(ctx, img, 0, 0, page.width, page.height);
76
+ else { paintBackground(ctx, page.width, page.height, state.bg); ctx.drawImage(img, 0, 0); }
77
+ overlay.replaceChildren(...data.items.filter(r => r.page === page.name).map(r => {
78
+ const box = overlayBox(r.x, r.y, r.w, r.h);
79
+ box.dataset.region = r.name; box.dataset.x = String(r.x); box.dataset.y = String(r.y); box.dataset.w = String(r.w); box.dataset.h = String(r.h);
80
+ if (r.index === item.index) box.setAttribute('aria-current', 'true');
81
+ const label = document.createElement('span'); label.textContent = r.name; box.append(label);
82
+ box.title = `${r.name} · ${r.x},${r.y} ${r.w}×${r.h}${r.degrees ? ` · ${r.degrees}°` : ''}`;
83
+ box.onclick = () => { select(r.index); setView('item'); };
84
+ return box;
85
+ }));
86
+ const regions = data.items.filter(r => r.page === page.name).length;
87
+ caption.textContent = regions === 1
88
+ ? t('Page {name}: {width}×{height} px, 1 region. The background shows through padding; a region box is the packer\'s, and pixels outside it are bleed.', { name: page.name, width: page.width, height: page.height })
89
+ : t('Page {name}: {width}×{height} px, {count} regions. The background shows through padding; a region box is the packer\'s, and pixels outside it are bleed.', { name: page.name, width: page.width, height: page.height, count: regions });
90
+ return;
91
+ }
92
+ if (data.mode === 'atlas') {
93
+ const page = data.pages.find(p => p.name === item.page)!, img = await pageImage(item.page!);
94
+ if (token !== paintToken) return;
95
+ const x0 = Math.max(0, item.x - REGION_MARGIN), y0 = Math.max(0, item.y - REGION_MARGIN);
96
+ const x1 = Math.min(page.width, item.x + item.w + REGION_MARGIN), y1 = Math.min(page.height, item.y + item.h + REGION_MARGIN);
97
+ const ctx = setCanvas(canvas, x1 - x0, y1 - y0);
98
+ if (state.alpha) paintAlphaOnly(ctx, img, x0, y0, x1 - x0, y1 - y0);
99
+ else { paintBackground(ctx, x1 - x0, y1 - y0, state.bg); ctx.drawImage(img, x0, y0, x1 - x0, y1 - y0, 0, 0, x1 - x0, y1 - y0); }
100
+ const edge = overlayBox(item.x - x0, item.y - y0, item.w, item.h);
101
+ edge.className = 'pv-region-edge';
102
+ overlay.replaceChildren(edge);
103
+ caption.textContent = t('Region {name} on {page} at {x},{y}, {width}×{height} px, with {margin} px of the page around it (dashed: the region box).', { name: item.name, page: item.page!, x: item.x, y: item.y, width: item.w, height: item.h, margin: REGION_MARGIN }) + (item.degrees ? ' ' + t('Packed at {degrees}°.', { degrees: item.degrees }) : '');
104
+ return;
105
+ }
106
+ const img = await itemImage(item), front = state.footprints ? frontParts(data.items, item) : [];
107
+ const fronts = await Promise.all(front.map(async o => ({ o, img: await itemImage(o) })));
108
+ if (token !== paintToken) return;
109
+ const ctx = setCanvas(canvas, item.w, item.h);
110
+ paintPart(ctx, item, img, { bg: state.bg, alpha: state.alpha, fronts: fronts.map(f => ({ box: f.o, image: f.img })), makeCanvas: (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }) });
111
+ overlay.replaceChildren(...data.flags.filter((f): f is Extract<Flag, { kind: 'faint' }> => f.item === item.name && f.kind === 'faint').map(f => {
112
+ const box = overlayBox(f.box[0], f.box[1], f.box[2], f.box[3]);
113
+ box.dataset.flag = f.id;
114
+ return box;
115
+ }));
116
+ caption.textContent = t('{name}: {width}×{height} px at {x},{y} in rig px, draw order {order} of {count}.', { name: item.name, width: item.w, height: item.h, x: item.x, y: item.y, order: item.index + 1, count: data.items.length })
117
+ + (state.footprints ? ' ' + (front.length === 1 ? t('Tinted: the footprint of the part drawn in front ({names}).', { names: front[0]!.name }) : front.length ? t('Tinted: the footprints of {count} parts drawn in front ({names}).', { count: front.length, names: front.map(o => o.name).join(', ') }) : t('No part is drawn in front of it.')) : '');
118
+ }
119
+
120
+ function renderFlags(): void {
121
+ const data = state.data!, item = data.items[state.selected];
122
+ const list = $('pv-flags');
123
+ const flags = item ? data.flags.filter(f => f.item === item.name) : [];
124
+ list.replaceChildren(...flags.map(f => {
125
+ const li = document.createElement('li');
126
+ li.dataset.flagId = f.id; li.dataset.flagSource = f.source;
127
+ const label = document.createElement('span'); label.className = 'pv-flag-label'; label.textContent = flagLabel(f, t);
128
+ li.append(label);
129
+ if (f.kind === 'check') {
130
+ // The producer's object, verbatim, one click away: the label names its fields and hides none of it.
131
+ const raw = document.createElement('details'), summary = document.createElement('summary'), code = document.createElement('code');
132
+ summary.textContent = t('Producer line'); code.textContent = `${f.path}: ${f.line}`;
133
+ raw.append(summary, code); li.append(raw);
134
+ }
135
+ return li;
136
+ }));
137
+ if (!flags.length) { const li = document.createElement('li'); li.className = 'pv-none'; li.textContent = t('No producer flag names this part.'); list.replaceChildren(li); }
138
+ $('pv-flag-sources').textContent = [
139
+ data.flagSources.length ? t('Read from: {files}.', { files: data.flagSources.join(', ') }) : '',
140
+ data.flagMissing.length ? t('Not found: {files}.', { files: data.flagMissing.join(', ') }) : '',
141
+ t('Occlusion coverage is not read yet: the producer does not write it.'),
142
+ ].filter(Boolean).join(' ');
143
+ }
144
+
145
+ function renderList(): void {
146
+ const data = state.data!, list = $('pv-items');
147
+ const seen = new Set<string>();
148
+ list.replaceChildren(...data.items.filter(i => !seen.has(i.name) && seen.add(i.name)).map(item => {
149
+ const li = document.createElement('li'), button = document.createElement('button');
150
+ button.type = 'button'; button.dataset.pvItem = item.name; button.title = item.name;
151
+ if (data.items[state.selected]?.name === item.name) button.setAttribute('aria-current', 'true');
152
+ const name = document.createElement('span'); name.className = 'pv-name'; name.textContent = item.name;
153
+ const count = data.flags.filter(f => f.item === item.name).length;
154
+ const flags = document.createElement('span'); flags.className = 'pv-count'; flags.textContent = count ? `⚑${count}` : '';
155
+ const outcome = state.verdict.get(item.name)?.outcome ?? 'pending';
156
+ const badge = document.createElement('span'); badge.className = 'pv-badge'; badge.dataset.outcome = outcome; badge.textContent = t(outcome === 'clean' ? 'Clean' : outcome === 'flagged' ? 'Flagged' : 'Pending');
157
+ button.append(name, flags, badge);
158
+ button.onclick = () => { select(item.index); if (data.mode === 'atlas') setView('item'); };
159
+ li.append(button);
160
+ return li;
161
+ }));
162
+ }
163
+
164
+ function renderVerdict(): void {
165
+ const item = state.data!.items[state.selected];
166
+ if (!item) return;
167
+ const entry = state.verdict.get(item.name) ?? { outcome: 'pending' as Outcome, note: '' };
168
+ for (const radio of document.querySelectorAll<HTMLInputElement>('input[data-pv-outcome]')) radio.checked = radio.value === entry.outcome;
169
+ $<HTMLTextAreaElement>('pv-note').value = entry.note;
170
+ }
171
+
172
+ function select(index: number): void {
173
+ const data = state.data!;
174
+ state.selected = index;
175
+ const item = data.items[index]!;
176
+ if (item.page !== undefined) state.page = data.pages.findIndex(p => p.name === item.page);
177
+ renderList(); renderFlags(); renderVerdict(); void paint();
178
+ }
179
+
180
+ function setView(view: 'item' | 'page'): void {
181
+ state.view = view;
182
+ for (const b of document.querySelectorAll<HTMLButtonElement>('[data-pv-view]')) b.setAttribute('aria-pressed', String(b.dataset.pvView === view));
183
+ void paint();
184
+ }
185
+
186
+ function updateEntry(change: Partial<{ outcome: Outcome; note: string }>): void {
187
+ const item = state.data!.items[state.selected]!;
188
+ const entry = { ...(state.verdict.get(item.name) ?? { outcome: 'pending' as Outcome, note: '' }), ...change };
189
+ state.verdict.set(item.name, entry);
190
+ renderList();
191
+ }
192
+
193
+ async function save(): Promise<void> {
194
+ const status = $('pv-save-status');
195
+ const body = { status: $<HTMLSelectElement>('pv-overall').value, parts: Object.fromEntries(state.verdict) };
196
+ const res = await fetch(access.route('/api/parts/verdict'), { method: 'POST', headers: access.headers({ 'Content-Type': 'application/json' }), body: JSON.stringify(body) });
197
+ const out = await res.json() as { error?: string; verdict?: { source: { sha256: string } } };
198
+ status.textContent = res.ok ? t('Saved {file}: source {hash}.', { file: state.data!.verdictFile, hash: out.verdict!.source.sha256.slice(0, 12) }) : out.error ?? t('Save failed.');
199
+ status.dataset.result = res.ok ? 'saved' : 'refused';
200
+ }
201
+
202
+ async function boot(): Promise<void> {
203
+ bindDomI18n(document);
204
+ connectLiveWindow(access);
205
+ const res = await fetch(access.route('/api/parts'), { headers: access.headers() });
206
+ const data = await res.json() as ViewData & { error?: string };
207
+ if (!res.ok) { $('pv-load').textContent = data.error ?? t('Load failed.'); return; }
208
+ state.data = data;
209
+ for (const item of data.items) state.verdict.set(item.name, { outcome: 'pending', note: '' });
210
+ if (data.verdict) { for (const [name, v] of Object.entries(data.verdict.parts)) if (state.verdict.has(name)) state.verdict.set(name, { outcome: v.outcome, note: v.note ?? '' }); $<HTMLSelectElement>('pv-overall').value = data.verdict.status; }
211
+ document.title = data.title;
212
+ $('pv-title').textContent = data.title;
213
+ $('pv-mode').textContent = data.mode === 'parts' ? t('Parts package, before rigging') : t('Atlas of a built rig');
214
+ $('pv-list-title').textContent = data.mode === 'parts' ? t('PARTS') : t('REGIONS');
215
+ $('pv-load').textContent = data.verdictStale === 'files' ? t('A saved sign-off was made on other files; this review starts fresh.') : data.verdictStale === 'flags' ? t('The saved sign-off is for different producer flags; this review starts fresh.') : data.verdict ? t('Saved sign-off loaded.') : '';
216
+ $('pv-atlas-switch').hidden = data.mode !== 'atlas';
217
+ const footprints = $<HTMLInputElement>('pv-footprints');
218
+ if (data.mode === 'atlas') { footprints.disabled = true; $('pv-footprint-control').title = t('Footprints need a parts package: atlas regions carry no rig placement.'); }
219
+ $<HTMLSelectElement>('pv-bg').onchange = e => { state.bg = (e.target as HTMLSelectElement).value; void paint(); };
220
+ $<HTMLInputElement>('pv-alpha').onchange = e => { state.alpha = (e.target as HTMLInputElement).checked; void paint(); };
221
+ footprints.onchange = e => { state.footprints = (e.target as HTMLInputElement).checked; void paint(); };
222
+ for (const b of document.querySelectorAll<HTMLButtonElement>('[data-pv-zoom]')) b.onclick = () => { state.zoom = Number(b.dataset.pvZoom); for (const o of document.querySelectorAll<HTMLButtonElement>('[data-pv-zoom]')) o.setAttribute('aria-pressed', String(o === b)); void paint(); };
223
+ for (const b of document.querySelectorAll<HTMLButtonElement>('[data-pv-view]')) b.onclick = () => setView(b.dataset.pvView as 'item' | 'page');
224
+ for (const r of document.querySelectorAll<HTMLInputElement>('input[data-pv-outcome]')) r.onchange = () => { if (r.checked) updateEntry({ outcome: r.value as Outcome }); };
225
+ $<HTMLTextAreaElement>('pv-note').oninput = e => updateEntry({ note: (e.target as HTMLTextAreaElement).value });
226
+ $('pv-save').onclick = () => { void save(); };
227
+ onLanguageChange(() => { if (state.data) select(state.selected); });
228
+ if (data.items.length) select(0);
229
+ document.body.dataset.ready = 'true';
230
+ }
231
+
232
+ if (typeof document !== 'undefined' && document.getElementById('parts-app')) void boot();