rig-review 4.2.0 → 4.4.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/docs/PARTS_VIEW.md +17 -8
- package/package.json +1 -1
- package/src/job-front.ts +10 -3
- package/src/parts-view.ts +3 -4
- package/web/catalog-en.ts +4 -0
- package/web/catalog-ko.ts +4 -0
- package/web/compare.ts +1 -1
- package/web/main.ts +4 -3
- package/web/parts-viewport-provider.ts +28 -8
- package/web/stage-comments.ts +111 -20
- package/web/view-controls.ts +15 -9
- package/web/viewport-controller.ts +2 -2
package/docs/PARTS_VIEW.md
CHANGED
|
@@ -324,14 +324,21 @@ The four-stage navigator preserves this entry and its explicit save behavior. Co
|
|
|
324
324
|
|
|
325
325
|
**Comment · C (n)** uses the same capture toggle, dragged region, composer and pins as the rig stage.
|
|
326
326
|
The **Issues** list stays visible in the side panel while C opens or closes capture. While capture is
|
|
327
|
-
on, drag within the rig pane
|
|
328
|
-
pan. Enter adds the issue,
|
|
327
|
+
on, drag within the rig pane, including from an existing pin, to mark a new region; clicking a pin
|
|
328
|
+
opens its comment. Keep controls clear and close capture to pan. Enter adds the issue,
|
|
329
329
|
and **Save sign-off** persists the verdict. Escape cancels the composer or capture while the inline
|
|
330
330
|
list stays visible. Rows and pins use the same edit, delete and jump actions.
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
331
|
+
For an editable saved comment opened in the composer, eight handles resize its area and dragging its
|
|
332
|
+
interior moves it; Enter saves text and geometry, Escape reverts the edit, and Shift+drag starts a
|
|
333
|
+
new area over the selected area or its handles. Tags are recomputed after resize or move only until
|
|
334
|
+
a chip is touched in this edit; reopening a saved comment keeps its chosen tags.
|
|
335
|
+
|
|
336
|
+
Opening a source-bound issue row or pin keeps the current view and camera when its source and view
|
|
337
|
+
mode match the screen and, in item view, it names the same part. Otherwise, a valid issue restores
|
|
338
|
+
its saved item or assembled mode, mesh, painting comparison and any recorded layer visibility,
|
|
339
|
+
then writes the saved rig camera (adjusted for the part placement in item view with painting).
|
|
340
|
+
The reference camera aligns only when camera sync is currently on; stale source or part bindings
|
|
341
|
+
are refused. Atlas inspection remains read only for pointed comments. Joined compiled Stage 1 refuses issue authoring with
|
|
335
342
|
`PARTS_JOINED_ISSUE_UNSUPPORTED` and directs the reviewer to the standing live job route. Its
|
|
336
343
|
zero-issue approval path remains available.
|
|
337
344
|
|
|
@@ -457,8 +464,10 @@ frontmost visible nontransparent art within the marked region. Review the chips
|
|
|
457
464
|
visible parts as needed. At least one referenced part is required, and the rig-space region must
|
|
458
465
|
remain inside their combined bounding box. Editing chips or wording validates and prepares the
|
|
459
466
|
candidate through the same source-bound crop pipeline before replacing the existing issue. A rejected
|
|
460
|
-
edit preserves the existing issue.
|
|
461
|
-
referenced parts
|
|
467
|
+
edit preserves the existing issue. Opening an assembled issue keeps an already matching assembled
|
|
468
|
+
view and shows its referenced parts as selected chips; a valid issue from a different context
|
|
469
|
+
restores its saved assembled view as described above. Assembly visibility stays temporary and is
|
|
470
|
+
excluded from saved issues and verdicts.
|
|
462
471
|
|
|
463
472
|
With `--painting`, the reference pane and Overlay use the same whole-canvas visual mapping described
|
|
464
473
|
above. Without painting the reference names `PARTS_REFERENCE_UNAVAILABLE`. Atlas assembly is disabled
|
package/package.json
CHANGED
package/src/job-front.ts
CHANGED
|
@@ -188,7 +188,8 @@ export function createJobFront(options: {
|
|
|
188
188
|
});
|
|
189
189
|
return new Response(body, { headers: { ...headers, 'Content-Type': 'application/x-ndjson' } });
|
|
190
190
|
}
|
|
191
|
-
|
|
191
|
+
const partsDifferenceQuery = /^publications\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/instances\/[a-f0-9]{64}\/api\/stage-parts\/difference\/(0|[1-9]\d*)$/.test(route);
|
|
192
|
+
if (url.search && !partsDifferenceQuery && !(route === '' && ['?lang=en', '?lang=ko'].includes(url.search))) {
|
|
192
193
|
return failure('JOB_REQUEST_INVALID', 400);
|
|
193
194
|
}
|
|
194
195
|
const instance = /^publications\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/instances\/([a-f0-9]{64})\/(.*)$/.exec(route);
|
|
@@ -436,8 +437,14 @@ export function retainedPublicationRoutes(session: JobSession) {
|
|
|
436
437
|
if(difference&&parts){
|
|
437
438
|
const url=new URL(request.url),threshold=url.searchParams.get('threshold'),footprints=url.searchParams.get('footprints');
|
|
438
439
|
if(!threshold||!/^\d{1,3}$/.test(threshold)||!['true','false'].includes(footprints??''))return failure('JOB_REQUEST_INVALID',400);
|
|
439
|
-
|
|
440
|
-
|
|
440
|
+
try {
|
|
441
|
+
const raster=await partsDifference(parts,Number(difference[1]),Number(threshold),footprints==='true'),png=new PNG({width:raster.width,height:raster.height});png.data=Buffer.from(raster.data);
|
|
442
|
+
return new Response(request.method==='HEAD'?null:new Uint8Array(PNG.sync.write(png)),{headers:{...headers,'Content-Type':'image/png','X-Difference-Count':String(raster.count),'X-Difference-Covered':String(raster.covered),'X-Difference-Compared':String(raster.compared)}});
|
|
443
|
+
} catch (error) {
|
|
444
|
+
const code = error instanceof Error ? /^(PARTS_DIFFERENCE_UNAVAILABLE|PARTS_DIFFERENCE_PNG):/.exec(error.message)?.[1] : undefined;
|
|
445
|
+
if (code) return failure(code, 400);
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
441
448
|
}
|
|
442
449
|
const part = /^api\/stage-parts\/(image|page)\/(0|[1-9]\d*)$/.exec(path);
|
|
443
450
|
if (part && parts) {
|
package/src/parts-view.ts
CHANGED
|
@@ -1130,10 +1130,9 @@ export async function partsDifference(pkg: PartsViewPackage, index: number, thre
|
|
|
1130
1130
|
}
|
|
1131
1131
|
const decode = async (path: string) => {
|
|
1132
1132
|
const bytes = await readFile(path);
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
}
|
|
1136
|
-
return PNG.sync.read(bytes);
|
|
1133
|
+
// pngjs normalizes valid PNG colour types and bit depths from the bound bytes.
|
|
1134
|
+
try { return PNG.sync.read(bytes); }
|
|
1135
|
+
catch { return refuse('PARTS_DIFFERENCE_PNG', 'decodable PNG operands required'); }
|
|
1137
1136
|
};
|
|
1138
1137
|
const painting = await decode(pkg.paintingInRig!.abs);
|
|
1139
1138
|
const part = await decode(pkg.imagePaths[index]!);
|
package/web/catalog-en.ts
CHANGED
|
@@ -175,6 +175,9 @@ export const enCatalog: Readonly<Record<string, string>> = {
|
|
|
175
175
|
"PARTS_DIFFERENCE_UNAVAILABLE: declared painting_in_rig required; legacy records remain readable": "PARTS_DIFFERENCE_UNAVAILABLE: declared painting_in_rig required; legacy records remain readable",
|
|
176
176
|
"PARTS_DIFFERENCE_UNAVAILABLE: known original part required": "PARTS_DIFFERENCE_UNAVAILABLE: known original part required",
|
|
177
177
|
"PARTS_DIFFERENCE_PNG: exact RGBA8 operands required": "PARTS_DIFFERENCE_PNG: exact RGBA8 operands required",
|
|
178
|
+
"PARTS_DIFFERENCE_PNG: decodable PNG operands required": "PARTS_DIFFERENCE_PNG: decodable PNG operands required",
|
|
179
|
+
"PARTS_DIFFERENCE_PNG": "PARTS_DIFFERENCE_PNG",
|
|
180
|
+
"PARTS_DIFFERENCE_UNAVAILABLE": "PARTS_DIFFERENCE_UNAVAILABLE",
|
|
178
181
|
"PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required": "PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required",
|
|
179
182
|
"PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid": "PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid",
|
|
180
183
|
"PARTS_COMPARISON_INVALID: part/overlay with opacity 0..1, or difference with integer threshold 0..255 required": "PARTS_COMPARISON_INVALID: part/overlay with opacity 0..1, or difference with integer threshold 0..255 required",
|
|
@@ -3614,4 +3617,5 @@ export const enCatalog: Readonly<Record<string, string>> = {
|
|
|
3614
3617
|
"Parts ready. Source files remain unchanged.": "Parts ready. Source files remain unchanged.",
|
|
3615
3618
|
"This request has no picture.": "This request has no picture.",
|
|
3616
3619
|
"The selected part has no chest regions. The chest editor keeps its current part.": "The selected part has no chest regions. The chest editor keeps its current part.",
|
|
3620
|
+
'Resize comment area: {0}': 'Resize comment area: {0}',
|
|
3617
3621
|
};
|
package/web/catalog-ko.ts
CHANGED
|
@@ -175,6 +175,9 @@ export const koCatalog: Readonly<Record<string, string>> = {
|
|
|
175
175
|
"PARTS_DIFFERENCE_UNAVAILABLE: declared painting_in_rig required; legacy records remain readable": "PARTS_DIFFERENCE_UNAVAILABLE: 차이 비교에는 선언된 painting_in_rig가 필요해요. 이전 기록은 계속 열 수 있어요.",
|
|
176
176
|
"PARTS_DIFFERENCE_UNAVAILABLE: known original part required": "PARTS_DIFFERENCE_UNAVAILABLE: 패키지에 등록된 원본 파트가 필요해요.",
|
|
177
177
|
"PARTS_DIFFERENCE_PNG: exact RGBA8 operands required": "PARTS_DIFFERENCE_PNG: 비교에 쓰는 이미지는 RGBA8이어야 해요.",
|
|
178
|
+
"PARTS_DIFFERENCE_PNG: decodable PNG operands required": "PARTS_DIFFERENCE_PNG: 비교에 쓰는 PNG 이미지를 읽을 수 있어야 해요.",
|
|
179
|
+
"PARTS_DIFFERENCE_PNG": "PARTS_DIFFERENCE_PNG",
|
|
180
|
+
"PARTS_DIFFERENCE_UNAVAILABLE": "PARTS_DIFFERENCE_UNAVAILABLE",
|
|
178
181
|
"PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required": "PARTS_DIFFERENCE_ALIGNMENT: 원본 배치 좌표가 정수이고 PNG 크기가 선언된 크기와 정확히 같아야 해요.",
|
|
179
182
|
"PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid": "PARTS_DIFFERENCE_ALIGNMENT: 파트의 알파가 0보다 큰 픽셀이 선언된 리그 격자 밖에 있어요.",
|
|
180
183
|
"PARTS_COMPARISON_INVALID: part/overlay with opacity 0..1, or difference with integer threshold 0..255 required": "PARTS_COMPARISON_INVALID: 파트 또는 오버레이의 불투명도는 0~1이어야 하고, 차이 비교의 임계값은 0~255 사이 정수여야 해요.",
|
|
@@ -3614,4 +3617,5 @@ export const koCatalog: Readonly<Record<string, string>> = {
|
|
|
3614
3617
|
"Parts ready. Source files remain unchanged.": "파츠 준비 완료. 원본 파일은 변경되지 않습니다.",
|
|
3615
3618
|
"This request has no picture.": "이 요청에는 그림이 없습니다.",
|
|
3616
3619
|
"The selected part has no chest regions. The chest editor keeps its current part.": "선택한 파츠에는 가슴 영역이 없어요. 가슴 편집기는 지금 파츠를 그대로 둬요.",
|
|
3620
|
+
'Resize comment area: {0}': '코멘트 영역 크기를 조절해요: {0}',
|
|
3617
3621
|
};
|
package/web/compare.ts
CHANGED
|
@@ -438,7 +438,7 @@ function bind(): void {
|
|
|
438
438
|
// #331: a plain drag on either rig pans and carries both rigs, each by its own root scale, so A and B take the same
|
|
439
439
|
// stimulus; the reference pane only pans, as the Family viewer's does.
|
|
440
440
|
const carryBoth={threshold:CLICK_SLOP_PX,move:(dx:number,dy:number)=>{for(const side of ['a','b'] as const){const impulse=dragImpulse(dx,dy,rigScales[side]);if(impulse)players[side]?.moved(impulse);}}};
|
|
441
|
-
viewDisposers.push(viewport.bindNavigation(target=>target==='reference'?undefined:carryBoth,
|
|
441
|
+
viewDisposers.push(viewport.bindNavigation(target=>target==='reference'?undefined:carryBoth,panOnly=>!comments?.active()||!!panOnly));
|
|
442
442
|
for(const [id,key] of [['layer-images','images'],['layer-mesh','mesh'],['layer-bones','bones']] as const)input(id).onchange=()=>{layers[key]=input(id).checked;redrawOverlays(false);};
|
|
443
443
|
input('idle-repeat').onchange=()=>{renderIdle();if(canRepeatIdle())void playComparison().catch(error=>message(describe(error),true));};
|
|
444
444
|
el('inspector-feedback').addEventListener('focusin',()=>{idleHeld=true;const current=lastPresented?.time;stop();if(current!==undefined&&!seeking)void seekTo(current);});
|
package/web/main.ts
CHANGED
|
@@ -386,7 +386,7 @@ function renderCheckpoint(): void {
|
|
|
386
386
|
}
|
|
387
387
|
|
|
388
388
|
function setView(value: typeof view): void {view=value;renderLayout();}
|
|
389
|
-
function chooseInspectionView(id:string):void {
|
|
389
|
+
async function chooseInspectionView(id:string):Promise<void> {
|
|
390
390
|
if(activeInterviewImages){const image=activeInterviewImages[Number(id.replace('interview-image-',''))];if(id.startsWith('interview-image-')&&image){activeInterviewImage=image;void showReference('',image);}return;}
|
|
391
391
|
if(!partsSubject){
|
|
392
392
|
if(id==='difference'){
|
|
@@ -407,8 +407,9 @@ function chooseInspectionView(id:string):void {
|
|
|
407
407
|
return;
|
|
408
408
|
}
|
|
409
409
|
const overlay=document.getElementById('parts-overlay') as HTMLInputElement;
|
|
410
|
+
const subject=partsSubject;
|
|
411
|
+
if(!await subject.setComparison(id==='difference'?'difference':overlay.checked?'overlay':'part')||partsSubject!==subject)return;
|
|
410
412
|
if(id==='difference')overlay.checked=false;
|
|
411
|
-
partsSubject.setComparison(id==='difference'?'difference':overlay.checked?'overlay':'part');
|
|
412
413
|
setView(id==='difference'?'rig':id as SingleLayout);
|
|
413
414
|
}
|
|
414
415
|
/** Availability follows the actual loaded image and declared native rig canvas, never a resized reference. */
|
|
@@ -1251,7 +1252,7 @@ function bind(): void {
|
|
|
1251
1252
|
retargetPanel=bindRetargetPanel({apply:body=>applyRetarget(body),reset:()=>{void resetRebuild(stageWorld());},seek:seekReading});
|
|
1252
1253
|
requirementsPanel=bindRequirementsPanel({check:runRequirements,seek:seekReading,animation:()=>animation,slot:()=>parts?.value()?.slot??stageDraftSelection?.slot??null,hash:sha256Hex});
|
|
1253
1254
|
const tickResize=new ResizeObserver(()=>renderReadingTicks());tickResize.observe(el('transport'));viewDisposers.push(()=>tickResize.disconnect());
|
|
1254
|
-
viewDisposers.push(viewport.bindNavigation(rigPanCarry({player:()=>player},viewport.state),
|
|
1255
|
+
viewDisposers.push(viewport.bindNavigation(rigPanCarry({player:()=>player},viewport.state),panOnly=>!comments?.active()||!!panOnly));
|
|
1255
1256
|
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);};
|
|
1256
1257
|
viewDisposers.push(bindLayerShortcuts(document));describeLayerToggles(document,el('layer-state').textContent??'');
|
|
1257
1258
|
input('idle-repeat').onchange=()=>{syncPlayerLoop();renderIdle();if(canRepeatIdle())void playPreview();};
|
|
@@ -89,6 +89,8 @@ export function bindPartsSubject(host:{
|
|
|
89
89
|
let selected:string|null=null,solo=false,comparison:PartsComparison=defaultPartsComparison(),token=0,disposed=false,busy=false,failed=false;
|
|
90
90
|
let drawnFrame:{w:number;h:number}|null=null,drawnReferenceFrame:{w:number;h:number}|null=null;
|
|
91
91
|
let drawnRegion:Box|null=null,drawnSolo=false;
|
|
92
|
+
let drawnComparison:PartsComparison|null=null;
|
|
93
|
+
let drawnNavigation:{selected:string|null;solo:boolean;hidden:string[]}|null=null;
|
|
92
94
|
let original:Promise<HTMLImageElement>|null=null,comments:ReturnType<typeof bindStageComments<CommentRow,PartsPose>>|null=null;
|
|
93
95
|
const makeCanvas=(w:number,h:number)=>Object.assign(document.createElement('canvas'),{width:w,height:h});
|
|
94
96
|
const item=()=>data.items.find(item=>item.name===selected)??data.items[0]!;
|
|
@@ -143,33 +145,51 @@ export function bindPartsSubject(host:{
|
|
|
143
145
|
const selectionChanged=drawnRegion?.name!==referenceBox?.name||drawnSolo!==!assembled();
|
|
144
146
|
drawnRegion=referenceBox;drawnSolo=!assembled();
|
|
145
147
|
if(reference){host.referenceCanvas.width=reference.width;host.referenceCanvas.height=reference.height;host.referenceCanvas.getContext('2d')!.drawImage(reference,0,0);drawnReferenceFrame={w:reference.width,h:reference.height};}
|
|
146
|
-
drawnFrame={w:frame.w,h:frame.h};failed=false;host.drawn({state:'loaded'});host.el('rig-empty').hidden=true;host.el('rig-label').textContent=t(assembled()?'Assembled parts':'Selected part');
|
|
148
|
+
drawnFrame={w:frame.w,h:frame.h};drawnComparison={...comparison};drawnNavigation={selected,solo,hidden:[...hidden]};failed=false;host.drawn({state:'loaded'});host.el('rig-empty').hidden=true;host.el('rig-label').textContent=t(assembled()?'Assembled parts':'Selected part');
|
|
147
149
|
if(data.painting&&host.viewport.state.cameraSync&&selectionChanged)host.viewport.requestFit();
|
|
148
150
|
host.viewport.fitCamera();comments?.refresh();
|
|
149
|
-
}catch(error){if(!disposed&&navigation===token){
|
|
151
|
+
}catch(error){if(!disposed&&navigation===token){
|
|
152
|
+
if(comparison.mode==='difference'&&drawnComparison&&drawnFrame&&drawnNavigation){comparison={...drawnComparison};selected=drawnNavigation.selected;solo=drawnNavigation.solo;hidden.clear();for(const name of drawnNavigation.hidden)hidden.add(name);host.selectionChanged();host.drawn({state:'loaded'});}
|
|
153
|
+
else{failed=true;drawnFrame=null;drawnReferenceFrame=null;host.drawn({state:'failed',reason:error instanceof Error?error.message:'PARTS_PAINT_FAILED'});host.canvas.getContext('2d')?.clearRect(0,0,host.canvas.width,host.canvas.height);host.referenceCanvas.getContext('2d')?.clearRect(0,0,host.referenceCanvas.width,host.referenceCanvas.height);}
|
|
154
|
+
host.message(error instanceof Error?error.message:'PARTS_PAINT_FAILED',true);throw error;
|
|
155
|
+
}}
|
|
150
156
|
finally{for(const bitmap of bitmaps)bitmap.close();if(navigation===token){busy=false;host.el('stage-layout').setAttribute('aria-busy','false');comments?.refresh();}}
|
|
151
157
|
}
|
|
152
158
|
const redraw=()=>{void paint().catch(()=>{});};
|
|
159
|
+
const commentRegion=(pose:PartsPose,screen:ReturnType<typeof region>)=>{
|
|
160
|
+
const frame=box(),a=unprojectMark(screen,pose.camera),b=unprojectMark({x:screen.x+screen.width,y:screen.y+screen.height},pose.camera);
|
|
161
|
+
const stable=(n:number)=>Math.abs(n-Math.round(n))<1e-6?Math.round(n):n;
|
|
162
|
+
return snapImageRegion(region({x:stable(a.x),y:stable(a.y)},{x:stable(b.x),y:stable(b.y)},{x:0,y:0,width:frame.w,height:frame.h}));
|
|
163
|
+
};
|
|
153
164
|
const codec:CommentCodec<CommentRow,PartsPose>={
|
|
165
|
+
geometry:true,
|
|
154
166
|
read:raw=>{try{const c=parsePartsIssue(raw,false,true,false),camera={space:'image' as const,center:c.view.camera.center,zoom:c.view.camera.zoom,viewport:c.view.camera.viewport,visible:{x:c.view.camera.center.x-c.view.camera.viewport.width/c.view.camera.zoom/2,y:c.view.camera.center.y-c.view.camera.viewport.height/c.view.camera.zoom/2,width:c.view.camera.viewport.width/c.view.camera.zoom,height:c.view.camera.viewport.height/c.view.camera.zoom}},r=c.view.mode==='assembled'?c.rigRegion:c.imageRegion!;return {mode:'parts',viewport:'rig',screen:region(projectMark(r,camera),projectMark({x:r.x+r.width,y:r.y+r.height},camera)),world:r,camera,crop:{...c.crop,png:c.crop.png??''},bookmark:c};}catch{return null;}},
|
|
155
167
|
signature:pose=>[pose.sourceHash,pose.item.name,pose.item.imageHash,pose.view],
|
|
156
|
-
matches:(_mark,pose,raw)=>{try{const c=parsePartsIssue(raw,false,true,false);return pose.sourceHash===c.sourceHash&&pose.view.mode===c.view.mode&&(assembled()||c.parts[0]?.name===pose.item.name);}catch{return false;}},
|
|
168
|
+
matches:(_mark,pose,raw)=>{try{const c=parsePartsIssue(raw,false,true,false);assertPartsIssueBinding(c,sourceItems(),data.sourceHash);return pose.sourceHash===c.sourceHash&&pose.view.mode===c.view.mode&&(assembled()||c.parts[0]?.name===pose.item.name);}catch{return false;}},
|
|
157
169
|
label:raw=>{const issue=parsePartsIssue(raw,false,true,false);return `${issue.parts.map(part=>part.name).join(', ')} · ${issue.summary}`;},
|
|
158
170
|
chips:(pose,screen,existing)=>{
|
|
159
171
|
const visible=data.items.filter(item=>!hidden.has(item.name)),candidates=pose.view.mode==='assembled'?visible.map(item=>item.name):[];
|
|
160
172
|
if(existing)return {selected:parsePartsIssue(existing,false,true,false).parts.map(part=>part.name),candidates};
|
|
161
173
|
if(pose.view.mode==='item')return {selected:[pose.item.name],candidates};
|
|
162
|
-
const
|
|
174
|
+
const r=commentRegion(pose,screen);
|
|
163
175
|
const hits=new Set<string>(),layers=visible.flatMap(box=>{const img=loaded.get(box.name);return img?[sourceAlpha(box,img)]:[];});
|
|
164
176
|
const stepX=Math.max(1,r.width/32),stepY=Math.max(1,r.height/32);
|
|
165
177
|
for(let y=r.y+.5;y<r.y+r.height;y+=stepY)for(let x=r.x+.5;x<r.x+r.width;x+=stepX){const hit=pickAssembly(layers,x,y);if(hit)hits.add(hit.name);}
|
|
166
178
|
return {selected:visible.filter(item=>hits.has(item.name)).map(item=>item.name),candidates};
|
|
167
179
|
},
|
|
168
180
|
create:async(pose,_view,screen,crop,_bookmark,summary,parts)=>{
|
|
169
|
-
const
|
|
181
|
+
const r=commentRegion(pose,screen),single=pose.view.mode==='item';
|
|
170
182
|
return prepare({schema:'rig-review-parts-comment/2',id:crypto.randomUUID(),summary,sourceHash:data.sourceHash,parts:partsBinding(single?[pose.item.name]:parts??[]),rigRegion:single?{...r,x:r.x+pose.item.x,y:r.y+pose.item.y}:r,imageRegion:single?r:null,view:structuredClone(pose.view),crop,nativeCrop:null});
|
|
171
183
|
},
|
|
172
|
-
update:(raw,summary,parts)=>{
|
|
184
|
+
update:(raw,summary,parts,geometry)=>{
|
|
185
|
+
const existing=parsePartsIssue(raw,false,true,false);let updated=existing;
|
|
186
|
+
if(geometry){
|
|
187
|
+
const {pose,screen,crop}=geometry,r=commentRegion(pose,screen),single=pose.view.mode==='item';
|
|
188
|
+
if(pose.sourceHash!==existing.sourceHash)throw new Error('PARTS_COMMENT_STALE_SOURCE');
|
|
189
|
+
updated={...existing,rigRegion:single?{...r,x:r.x+pose.item.x,y:r.y+pose.item.y}:r,imageRegion:single?r:null,view:structuredClone(pose.view),crop,nativeCrop:null};
|
|
190
|
+
}
|
|
191
|
+
return prepare({...updated,summary,parts:existing.view.mode==='assembled'?partsBinding(parts??[]):existing.parts});
|
|
192
|
+
},
|
|
173
193
|
};
|
|
174
194
|
const pose=():PartsPose|null=>{
|
|
175
195
|
let camera=host.viewport.numericView().cameras.rig;const entry=item();if(!camera||!entry||busy||failed||disposed)return null;
|
|
@@ -177,7 +197,7 @@ export function bindPartsSubject(host:{
|
|
|
177
197
|
return {mode:'parts',item:entry,sourceHash:data.sourceHash,camera,view:{mode:assembled()?'assembled':'item',camera:{zoom:camera.zoom,center:camera.center,viewport:camera.viewport},cameraSync:host.viewport.state.cameraSync,referenceCamera:null,background:'checker',alpha:false,footprints:false,mesh:host.mesh(),comparison:{...comparison},...(assembled()&&EMIT_UNPINNED_CREATE_FIELDS?{visibleLayers:partsBinding(data.items.filter(item=>!hidden.has(item.name)).map(item=>item.name))}:{})},capture:{pane:host.el('rig-viewport'),root:host.el('rig-root'),images:true,canvas:host.canvas,backend:'canvas2d',nearest:true}};
|
|
178
198
|
};
|
|
179
199
|
comments=bindStageComments<CommentRow,PartsPose>({general:host.recordComments?{create:summary=>({id:crypto.randomUUID(),summary}),matches:row=>!('schema' in row)}:undefined,toolbar:host.toolbar,listHost:host.commentsHost,openList:host.openComments,hasPicture:host.hasPicture,toggle:host.el<HTMLButtonElement>('stage-comment'),viewports:{rig:host.el('rig-viewport')},pose,pause:async()=>{},bookmark:()=>null,
|
|
180
|
-
restore:async raw=>{const issue=parsePartsIssue(raw,false,true,false);assertPartsIssueBinding(issue,sourceItems(),data.sourceHash);selected=issue.parts[0]!.name;solo=issue.view.mode==='item';comparison=issue.view.comparison??defaultPartsComparison();host.restoreMesh(issue.view.mesh);if(issue.view.visibleLayers){const visible=new Set(issue.view.visibleLayers.map(part=>part.name));hidden.clear();for(const item of data.items)if(!visible.has(item.name))hidden.add(item.name);}await paint();host.viewport.writeCamera('rig',data.painting&&solo?{...issue.view.camera,center:{x:issue.view.camera.center.x+item().x,y:issue.view.camera.center.y+item().y}}:issue.view.camera);host.viewport.activateCamera('rig');if(host.viewport.state.cameraSync)host.viewport.alignCameras();host.viewport.fitCamera();host.selectionChanged();},
|
|
200
|
+
restore:async raw=>{const issue=parsePartsIssue(raw,false,true,false);assertPartsIssueBinding(issue,sourceItems(),data.sourceHash);selected=issue.view.mode==='item'?issue.parts[0]!.name:null;solo=issue.view.mode==='item';comparison=issue.view.comparison??defaultPartsComparison();host.restoreMesh(issue.view.mesh);if(issue.view.visibleLayers){const visible=new Set(issue.view.visibleLayers.map(part=>part.name));hidden.clear();for(const item of data.items)if(!visible.has(item.name))hidden.add(item.name);}await paint();host.viewport.writeCamera('rig',data.painting&&solo?{...issue.view.camera,center:{x:issue.view.camera.center.x+item().x,y:issue.view.camera.center.y+item().y}}:issue.view.camera);host.viewport.activateCamera('rig');if(host.viewport.state.cameraSync)host.viewport.alignCameras();host.viewport.fitCamera();host.selectionChanged();},
|
|
181
201
|
feedback:()=>host.recordComments??host.issues,locked:host.locked,refusal:host.refusal,add:row=>{if(host.recordComments)host.recordComments.push(row);else host.issues.push(row as PartsIssue);},changed:host.changed,error:host.message,blocked:()=>busy||failed||disposed,busy:()=>busy,codec});
|
|
182
202
|
return {
|
|
183
203
|
frameSize:(target:CameraTarget):PartsFrame|null=>{
|
|
@@ -193,7 +213,7 @@ export function bindPartsSubject(host:{
|
|
|
193
213
|
select:(name:string|null)=>{selected=name;if(name===null)solo=false;redraw();host.selectionChanged();},isolate:(value:boolean)=>{solo=value;redraw();host.selectionChanged();},
|
|
194
214
|
show:(name:string,value:boolean)=>{if(value)hidden.delete(name);else hidden.add(name);redraw();},
|
|
195
215
|
differenceAvailable:()=>data.differenceAvailable&&!!data.painting&&!failed,
|
|
196
|
-
comparison:()=>comparison,setComparison:(mode:PartsComparison['mode'])=>{
|
|
216
|
+
comparison:()=>comparison,setComparison:async(mode:PartsComparison['mode'])=>{const next:PartsComparison=mode==='difference'?{mode,opacity:comparison.opacity,threshold:0}:{mode,opacity:comparison.opacity};comparison=next;const navigation=token+1;try{await paint();return !disposed&&navigation===token&&comparison===next;}catch{return false;}},
|
|
197
217
|
opacity:(value:number)=>{comparison.opacity=value;redraw();},paint,redraw,
|
|
198
218
|
async ready(){if(data.painting)host.viewport.state.cameraSync=true;await paint();},
|
|
199
219
|
dispose(){disposed=true;++token;comments?.dispose();images.clear();loaded.clear();assemblyAlpha.clear();},
|
package/web/stage-comments.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type {Feedback} from '../src/session.ts';
|
|
|
5
5
|
import type {ControlNumericCamera} from '../src/control.ts';
|
|
6
6
|
import {drawnSlots,region,projectMark,unprojectMark,parseStageComment,feedbackTimingLabel,type MarkRegion,type MarkPoint,type StageComment} from '../src/stage-comment.ts';
|
|
7
7
|
import {getLanguage as i18nLang,onLanguageChange as i18nOnChange,t as i18nT,tr as i18nTr} from './i18n.ts';
|
|
8
|
-
import {textEntryFocused} from './view-controls.ts';
|
|
8
|
+
import {panSpaceHeld,textEntryFocused} from './view-controls.ts';
|
|
9
9
|
export interface CommentPose {
|
|
10
10
|
mode:StageComment['mode'];camera:ControlNumericCamera;frame:StageComment['frame'];timeBasis?:StageComment['timeBasis'];time:number;animation:string|null;
|
|
11
11
|
turn:unknown;sourceHash:string;modelHash:string|null;referenceHash:string|null;referenceId:string|null;frameReason?:string;
|
|
@@ -19,7 +19,9 @@ export interface CommentCodec<Row extends CommentRow,Pose extends CommentUiPose>
|
|
|
19
19
|
read:(row:Row)=>CommentUiMark|null;signature:(pose:Pose)=>unknown;matches:(mark:CommentUiMark,pose:Pose,row:Row)=>boolean;
|
|
20
20
|
label:(row:Row,mark:CommentUiMark)=>string;
|
|
21
21
|
chips?:(pose:Pose,screen:MarkRegion,existing?:Row)=>{selected:string[];candidates:string[]};
|
|
22
|
-
|
|
22
|
+
/** Opt in only when this codec can prepare replacement geometry and fresh pixel evidence. */
|
|
23
|
+
geometry?:boolean;
|
|
24
|
+
update?:(row:Row,summary:string,parts?:string[],geometry?:{pose:Pose;screen:MarkRegion;crop:StageComment['crop']})=>Promise<Row>|Row;
|
|
23
25
|
create:(pose:Pose,view:StageComment['viewport'],screen:MarkRegion,crop:StageComment['crop'],bookmark:unknown,summary:string,parts?:string[])=>Promise<Row>;
|
|
24
26
|
}
|
|
25
27
|
interface Host<Row extends CommentRow=Feedback,Pose extends CommentUiPose=CommentPose> {
|
|
@@ -37,6 +39,7 @@ const t=(s:string)=>typeof i18nT==='function'?i18nT(s):s;
|
|
|
37
39
|
const toEn=(s:string)=>typeof i18nTr==='function'?i18nTr(s,'en'):s;
|
|
38
40
|
const onLang=(fn:()=>void)=>typeof i18nOnChange==='function'?i18nOnChange(fn):()=>{};
|
|
39
41
|
const curLang=()=>typeof i18nLang==='function'?i18nLang():'en';
|
|
42
|
+
const spaceHeld=()=>typeof panSpaceHeld==='function'&&panSpaceHeld();
|
|
40
43
|
function rectElement(r:MarkRegion):HTMLDivElement{const node=document.createElement('div');node.className='stage-comment-region';Object.assign(node.style,{left:r.x+'px',top:r.y+'px',width:Math.max(2,r.width)+'px',height:Math.max(2,r.height)+'px'});return node;}
|
|
41
44
|
async function crop(pose:CommentUiPose,r:MarkRegion):Promise<StageComment['crop']>{
|
|
42
45
|
if(!pose.capture)throw new Error(t('COMMENT_CROP_UNAVAILABLE: viewport pixel source unavailable'));
|
|
@@ -76,8 +79,12 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
76
79
|
const updateRefusal=()=>{const raw=host.refusal?.()??null,reason=raw?t(raw):null,prev=refusalNote.textContent||'',nextTitle=reason??t(originalTitle);toggle.disabled=!!host.busy?.();toggle.setAttribute('aria-busy',String(toggle.disabled));if(toggle.title!==nextTitle)toggle.title=nextTitle;if(refusalNote.title!==(reason??''))refusalNote.title=reason??'';if(refusalNote.textContent!==(reason??''))refusalNote.textContent=reason??'';refusalNote.hidden=!reason;if(!list.hidden&&(reason??'')!==prev)renderList();return reason;};
|
|
77
80
|
const layers=new Map<StageComment['viewport'],HTMLDivElement>();for(const [key,pane]of Object.entries(host.viewports)){const layer=document.createElement('div');layer.className='stage-comment-layer';pane!.append(layer);layers.set(key as StageComment['viewport'],layer);}
|
|
78
81
|
let enabled=false,disposed=false,pending:{view:StageComment['viewport'];start:MarkPoint;end:MarkPoint;mode:string;id:number;interaction:number;settled:Promise<void>}|null=null,composer:HTMLFormElement|null=null,composerReadOnly=false,composerGeneral=false,syncComposerLang:(()=>void)|null=null,draftMark:{view:StageComment['viewport'];mode:string;screen:MarkRegion}|null=null,busy=false,last='',raf=0,interaction=0;
|
|
82
|
+
let geometryEdit:{view:StageComment['viewport'];screen:MarkRegion;id?:string;update:(screen:MarkRegion)=>void;changed:boolean;camera:string}|null=null;
|
|
83
|
+
let geometryDrag:{id:number;start:MarkPoint;screen:MarkRegion;handle:string}|null=null;
|
|
84
|
+
let suppressPinClick=false;
|
|
85
|
+
let pinPress:{id:number;view:StageComment['viewport'];start:MarkPoint;pin:HTMLButtonElement}|null=null;
|
|
79
86
|
const setCapture=(value:boolean)=>{value=value&&host.hasPicture?.()!==false;enabled=value;toggle.setAttribute('aria-pressed',String(value||!inline&&!list.hidden));for(const pane of Object.values(host.viewports))pane!.classList.toggle('stage-comment-mode',value);};
|
|
80
|
-
const cancel=()=>{++interaction;const previous=pending;pending=null;if(previous){const pane=host.viewports[previous.view];if(pane?.hasPointerCapture(previous.id))pane.releasePointerCapture(previous.id);}composer?.remove();composer=null;composerReadOnly=false;composerGeneral=false;syncComposerLang=null;draftMark=null;last='';};
|
|
87
|
+
const cancel=()=>{++interaction;const previous=pending??(geometryDrag&&geometryEdit?{view:geometryEdit.view,id:geometryDrag.id}:pinPress);geometryEdit=null;geometryDrag=null;pinPress=null;pending=null;if(previous){const pane=host.viewports[previous.view];if(pane?.hasPointerCapture(previous.id))pane.releasePointerCapture(previous.id);}composer?.remove();composer=null;composerReadOnly=false;composerGeneral=false;syncComposerLang=null;draftMark=null;last='';};
|
|
81
88
|
const assertCapture=()=>{const reason=updateRefusal();if(reason){cancel();setCapture(false);host.error(reason);throw new Error(reason);}if(host.blocked())throw new Error(t('COMMENT_BUSY: wait for inspection'));};
|
|
82
89
|
const assertEdit=(general=false)=>{const reason=general?null:updateRefusal();if(reason){setCapture(false);host.error(reason);throw new Error(reason);}if(host.blocked())throw new Error(t('COMMENT_BUSY: wait for inspection'));};
|
|
83
90
|
let jumpGeneration = 0;
|
|
@@ -85,6 +92,10 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
85
92
|
const jump = async (row: Row): Promise<boolean> => {
|
|
86
93
|
const mark = readMark(row);if (!mark) return false;
|
|
87
94
|
cancel();const generation = interaction, request = ++jumpGeneration;
|
|
95
|
+
// Editing a mark already visible in this parts view must not replay its navigation bookmark.
|
|
96
|
+
const pose=host.pose(mark.viewport);
|
|
97
|
+
if(host.codec?.geometry&&pose&&host.codec.matches(mark,pose,row)){last='';return true;}
|
|
98
|
+
|
|
88
99
|
hiddenPanes ??= Object.values(host.viewports).map(pane => ({pane: pane!, visibility: pane!.style.visibility}));
|
|
89
100
|
try {
|
|
90
101
|
for (const {pane} of hiddenPanes) pane.style.visibility = 'hidden';
|
|
@@ -117,7 +128,7 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
117
128
|
if(reason){setCapture(false);host.error(reason);return;}
|
|
118
129
|
setCapture(layers.size>0);for(const view of layers.keys())host.pose(view);
|
|
119
130
|
};
|
|
120
|
-
const openComment=async(f:Row)=>{const mark=readMark(f);if(!mark){if(host.general?.matches(f))openComposer(null,{x:0,y:0,width:0,height:0},f);return;}if(list.hidden)setOpen(true);if(list.hidden)return;if(await jump(f)){const reason=updateRefusal();setCapture(!reason&&!host.blocked());
|
|
131
|
+
const openComment=async(f:Row)=>{const mark=readMark(f);if(!mark){if(host.general?.matches(f))openComposer(null,{x:0,y:0,width:0,height:0},f);return;}if(list.hidden)setOpen(true);if(list.hidden)return;if(await jump(f)){const reason=updateRefusal();setCapture(!reason&&!host.blocked());const pose=host.pose(mark.viewport),screen=host.codec?.geometry&&pose?region(projectMark(mark.world,pose.camera),projectMark({x:mark.world.x+mark.world.width,y:mark.world.y+mark.world.height},pose.camera)):mark.screen;openComposer(mark.viewport,screen,f,pose?.mode??mark.mode);}};
|
|
121
132
|
const renderList=()=>{placeList();list.setAttribute('aria-label',t('Comments'));list.replaceChildren();const title=document.createElement('strong');title.textContent=t('Comments');list.append(title);const rawReason=host.refusal?.()??null,reason=rawReason?t(rawReason):null;if(reason){const note=document.createElement('small');note.className='stage-comment-refusal-note';note.title=reason;note.textContent=reason;Object.assign(note.style,{display:'block',marginTop:'4px',maxWidth:'100%',whiteSpace:inline?'normal':'nowrap',overflow:'hidden',textOverflow:'ellipsis'});list.append(note);}if(host.general){const add=document.createElement('button');add.type='button';add.textContent=t('Add general comment');add.dataset.commentGeneral='';add.onclick=()=>openComposer(null,{x:0,y:0,width:0,height:0});list.append(add);}const all=host.feedback().filter(f=>readMark(f)||host.general?.matches(f));toggle.textContent=t(host.busy?.()?'Comment · C ({0}) · Rendering':'Comment · C ({0})').replace('{0}',String(all.length));if(!all.length){const empty=document.createElement('p');empty.textContent=t(inline?'No comments yet.':reason?'Read only · Escape closes':'Mark a point or region, then type. Enter saves · Escape cancels.');list.append(empty);}for(const [i,f]of all.entries()){
|
|
122
133
|
const mark=readMark(f),row=document.createElement('div');row.className='stage-comment-item';row.dataset.commentId=f.id;
|
|
123
134
|
const go=document.createElement('button');go.type='button';go.className='stage-comment-summary';go.textContent=!mark?`${i+1} · ${t('General comment')} · ${f.summary}`:host.codec?`${i+1} · ${host.codec.label(f,mark)}`:`${i+1} · ${mark.mode.toUpperCase()} · ${mark.viewport.toUpperCase()} · ${mark.frame?`F${mark.frame.index} (${mark.frame.basis})`:t(feedbackTimingLabel(f as unknown as Feedback))} · ${f.summary}`;go.onclick=()=>openComment(f);row.append(go);
|
|
@@ -132,11 +143,20 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
132
143
|
if(!general&&(!placementMode||currentMode&¤tMode!==placementMode)){cancel();return;}
|
|
133
144
|
const locked=!!existing&&host.locked(existing.id),initialRefusal=existing&&!general?updateRefusal():null;
|
|
134
145
|
if(existing&&!initialRefusal&&host.blocked()){host.error(t('COMMENT_BUSY: wait for inspection'));return;}
|
|
135
|
-
composer?.remove();composerReadOnly=locked||!!initialRefusal;composerGeneral=general;draftMark=view?{view,mode:placementMode!,screen}:null;const generation=interaction;const pane=view?host.viewports[view]!:list,form=composer=document.createElement('form');form.className='stage-comment-composer stage-comment-ui';form.setAttribute('aria-label',t('Comment composer'));if(general)form.style.position='relative';
|
|
146
|
+
geometryEdit=null;composer?.remove();composerReadOnly=locked||!!initialRefusal;composerGeneral=general;draftMark=view?{view,mode:placementMode!,screen}:null;const generation=interaction;const pane=view?host.viewports[view]!:list,form=composer=document.createElement('form');form.className='stage-comment-composer stage-comment-ui';form.setAttribute('aria-label',t('Comment composer'));if(general)form.style.position='relative';
|
|
136
147
|
const field=document.createElement('input');field.type='text';field.maxLength=1000;field.setAttribute('aria-label',t('Comment text'));field.placeholder=t('Describe this spot…');field.value=existing?.summary??'';
|
|
137
148
|
if(locked||initialRefusal){field.readOnly=true;field.setAttribute('aria-readonly','true');}
|
|
138
149
|
const hint=document.createElement('small');hint.textContent=composerReadOnly?'Read only · Escape closes':'Enter saves · Escape cancels';hint.textContent=t(hint.textContent);const error=document.createElement('p');error.setAttribute('role','alert');form.append(field,hint,error);
|
|
139
|
-
const place=()=>{if(general)return;
|
|
150
|
+
const place=()=>{if(general)return;
|
|
151
|
+
if(host.codec?.geometry){
|
|
152
|
+
const right=pane.clientWidth-screen.x-screen.width-12,left=screen.x-12,available=Math.max(left,right);
|
|
153
|
+
if(available>=160){
|
|
154
|
+
const width=Math.min(286,available);form.style.width=width+'px';const height=form.offsetHeight||132;
|
|
155
|
+
Object.assign(form.style,{left:(right>=left?screen.x+screen.width+8:screen.x-width-8)+'px',top:Math.max(4,Math.min(screen.y,pane.clientHeight-height-4))+'px'});return;
|
|
156
|
+
}
|
|
157
|
+
form.style.width='';
|
|
158
|
+
}
|
|
159
|
+
const w=form.offsetWidth||294,h=form.offsetHeight||132;Object.assign(form.style,{left:Math.max(4,Math.min(screen.x+screen.width+8,pane.clientWidth-w-4))+'px',top:Math.max(4,Math.min(screen.y+screen.height+8,pane.clientHeight-h-4))+'px'});};
|
|
140
160
|
let removeBtn:HTMLButtonElement|null=null,errorSource='';
|
|
141
161
|
if(existing&&!locked){
|
|
142
162
|
const remove=removeBtn=document.createElement('button');remove.type='button';remove.className='stage-comment-delete';remove.textContent=t('Delete');
|
|
@@ -153,7 +173,7 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
153
173
|
// Capture all view context now; camera or dial changes while typing cannot rebind the mark.
|
|
154
174
|
const pose=view?host.pose(view):null,bookmark=general?null:copy(host.bookmark()),turn=pose?.turn===undefined?null:copy(pose.turn);
|
|
155
175
|
const initialParts = pose ? host.codec?.chips?.(pose, screen, existing) : undefined;
|
|
156
|
-
let selectedParts = initialParts?.selected.slice();
|
|
176
|
+
let selectedParts = initialParts?.selected.slice(),partsTouched=!!existing;
|
|
157
177
|
const chipBox = initialParts ? document.createElement('div') : null;
|
|
158
178
|
const chipNames = initialParts ? [...new Set([...initialParts.selected, ...initialParts.candidates])] : [];
|
|
159
179
|
const syncChips = () => {
|
|
@@ -165,6 +185,7 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
165
185
|
chip.setAttribute('aria-pressed', String(selectedParts!.includes(name)));
|
|
166
186
|
chip.onclick = () => {
|
|
167
187
|
if (busy || composerReadOnly) return;
|
|
188
|
+
partsTouched=true;
|
|
168
189
|
const chosen = new Set(selectedParts);
|
|
169
190
|
if (chosen.has(name)) chosen.delete(name);else chosen.add(name);
|
|
170
191
|
selectedParts = chipNames.filter(part => chosen.has(part));
|
|
@@ -179,16 +200,29 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
179
200
|
syncComposerLang=()=>{if(composer!==form)return;form.setAttribute('aria-label',t('Comment composer'));if(general)form.style.position='relative';field.setAttribute('aria-label',t('Comment text'));field.placeholder=t('Describe this spot…');hint.textContent=t(composerReadOnly?'Read only · Escape closes':'Enter saves · Escape cancels');if(removeBtn)removeBtn.textContent=t('Delete');if(errorSource)error.textContent=t(errorSource);syncChips();};
|
|
180
201
|
pane.append(form);place();
|
|
181
202
|
const previous=existing?readMark(existing):null;
|
|
182
|
-
|
|
203
|
+
let prepared=general?Promise.resolve(null):previous?Promise.resolve(previous.crop):pose?crop(pose,screen):Promise.reject(new Error('COMMENT_VIEW_UNAVAILABLE'));
|
|
183
204
|
prepared.catch(()=>{});
|
|
184
|
-
|
|
205
|
+
if(view&&pose&&host.codec?.geometry&&!composerReadOnly){
|
|
206
|
+
geometryEdit={view,screen:{...screen},id:existing?.id,changed:false,camera:JSON.stringify(pose.camera),update:next=>{
|
|
207
|
+
const a=unprojectMark(next,pose.camera),b=unprojectMark({x:next.x+next.width,y:next.y+next.height},pose.camera);
|
|
208
|
+
let x=Math.round(a.x),y=Math.round(a.y),right=Math.round(b.x),bottom=Math.round(b.y);
|
|
209
|
+
if(right<=x){if(geometryDrag?.handle.includes('w'))x=right-1;else right=x+1;}
|
|
210
|
+
if(bottom<=y){if(geometryDrag?.handle.includes('n'))y=bottom-1;else bottom=y+1;}
|
|
211
|
+
screen=region(projectMark({x,y},pose.camera),projectMark({x:right,y:bottom},pose.camera));draftMark={view,mode:placementMode!,screen};geometryEdit!.screen=screen;geometryEdit!.changed=true;
|
|
212
|
+
if(!partsTouched){selectedParts=host.codec?.chips?.(pose,screen)?.selected.slice();syncChips();}
|
|
213
|
+
prepared=crop(pose,screen);prepared.catch(()=>{});last='';place();
|
|
214
|
+
}};
|
|
215
|
+
}
|
|
216
|
+
form.onkeydown=e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();cancel();renderPins();pane.focus();}};
|
|
185
217
|
form.onsubmit=async e=>{e.preventDefault();if(busy)return;if(generation!==interaction||view&&host.pose(view)&&host.pose(view!)?.mode!==placementMode){cancel();return;}const summary=field.value.trim();if(!summary){field.focus();return;}try{
|
|
186
218
|
if(selectedParts && !selectedParts.length)throw new Error(t('Select at least one part.'));
|
|
187
219
|
if(existing){
|
|
188
220
|
assertEdit(general);if(host.locked(existing.id))throw new Error(t('COMMENT_SUBMITTED: submitted evidence is immutable'));
|
|
189
221
|
busy=true;field.disabled=true;syncChips();
|
|
190
222
|
if(!general&&host.codec?.update){
|
|
191
|
-
const
|
|
223
|
+
const geometry=geometryEdit?.changed&&pose?{pose,screen:{...screen},crop:(await prepared)!}:undefined;
|
|
224
|
+
if(disposed||generation!==interaction)return;assertEdit(general);
|
|
225
|
+
const replacement=await host.codec.update(copy(existing),summary,selectedParts?.slice(),geometry);
|
|
192
226
|
if(disposed||generation!==interaction)return;
|
|
193
227
|
assertEdit(general);if(host.locked(existing.id))throw new Error(t('COMMENT_SUBMITTED: submitted evidence is immutable'));
|
|
194
228
|
const all=host.feedback(),index=all.indexOf(existing);
|
|
@@ -219,26 +253,83 @@ export function bindStageComments<Row extends CommentRow=Feedback,Pose extends C
|
|
|
219
253
|
const disposers:(()=>void)[]=[];
|
|
220
254
|
for(const [key,pane]of Object.entries(host.viewports)){
|
|
221
255
|
const view=key as StageComment['viewport'],local=(e:PointerEvent)=>{const r=pane!.getBoundingClientRect();return {x:Math.max(0,Math.min(pane!.clientWidth,e.clientX-r.left-pane!.clientLeft)),y:Math.max(0,Math.min(pane!.clientHeight,e.clientY-r.top-pane!.clientTop))};};
|
|
222
|
-
const down=(e:PointerEvent)=>{
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
256
|
+
const down=(e:PointerEvent)=>{
|
|
257
|
+
if(e.button!==0||!e.isPrimary||spaceHeld()){if(spaceHeld()&&(e.target as Element)?.closest?.('.stage-comment-pin'))suppressPinClick=true;return;}
|
|
258
|
+
suppressPinClick=false;
|
|
259
|
+
const target=e.target as Element,pin=host.codec?.geometry?target.closest<HTMLButtonElement>('.stage-comment-pin'):null;
|
|
260
|
+
const handle=target.closest<HTMLElement>('[data-comment-handle]')?.dataset.commentHandle;
|
|
261
|
+
if(geometryEdit?.view===view&&handle&&!e.shiftKey){
|
|
262
|
+
if(busy||host.blocked()||geometryEdit.id&&host.locked(geometryEdit.id))return;
|
|
263
|
+
try{assertEdit();}catch{return;}
|
|
264
|
+
e.preventDefault();e.stopImmediatePropagation();suppressPinClick=true;geometryDrag={id:e.pointerId,start:local(e),screen:{...geometryEdit.screen},handle};pane!.setPointerCapture(e.pointerId);return;
|
|
265
|
+
}
|
|
266
|
+
if(pin&&!host.blocked()){
|
|
267
|
+
if(!enabled)setOpen(true);if(!enabled)return;
|
|
268
|
+
try{assertCapture();}catch{return;}
|
|
269
|
+
e.preventDefault();e.stopImmediatePropagation();suppressPinClick=true;pinPress={id:e.pointerId,view,start:local(e),pin};pane!.setPointerCapture(e.pointerId);return;
|
|
270
|
+
}
|
|
271
|
+
if(target.closest('.stage-comment-ui,button,input')&&!(e.shiftKey&&handle&&host.codec?.geometry)){if(host.codec?.geometry)e.stopImmediatePropagation();return;}
|
|
272
|
+
if(enabled||!inline&&!list.hidden){try{assertCapture();}catch{return;}}if(!enabled||host.blocked())return;e.preventDefault();e.stopImmediatePropagation();cancel();const mode=host.pose(view)?.mode;if(!mode)return;const at=local(e),generation=interaction;pending={view,start:at,end:at,mode,id:e.pointerId,interaction:generation,settled:host.pause()};pending.settled.catch(e=>{if(interaction===generation&&!disposed)host.error(String(e));});pane!.setPointerCapture(e.pointerId);};
|
|
273
|
+
const move=(e:PointerEvent)=>{
|
|
274
|
+
if(geometryDrag?.id===e.pointerId&&geometryEdit){
|
|
275
|
+
e.preventDefault();e.stopImmediatePropagation();const p=local(e),g=geometryDrag,r=g.screen,dx=p.x-g.start.x,dy=p.y-g.start.y;
|
|
276
|
+
let x=r.x,y=r.y,right=r.x+r.width,bottom=r.y+r.height;
|
|
277
|
+
if(g.handle==='move'){x=Math.max(0,Math.min(pane!.clientWidth-r.width,x+dx));y=Math.max(0,Math.min(pane!.clientHeight-r.height,y+dy));right=x+r.width;bottom=y+r.height;}
|
|
278
|
+
else {if(g.handle.includes('w'))x=Math.max(0,Math.min(right-1,x+dx));if(g.handle.includes('e'))right=Math.min(pane!.clientWidth,Math.max(x+1,right+dx));if(g.handle.includes('n'))y=Math.max(0,Math.min(bottom-1,y+dy));if(g.handle.includes('s'))bottom=Math.min(pane!.clientHeight,Math.max(y+1,bottom+dy));}
|
|
279
|
+
geometryEdit.update({x,y,width:right-x,height:bottom-y});return;
|
|
280
|
+
}
|
|
281
|
+
if(pinPress?.id===e.pointerId){
|
|
282
|
+
const p=pinPress,at=local(e);if(Math.hypot(at.x-p.start.x,at.y-p.start.y)<4)return;
|
|
283
|
+
e.preventDefault();e.stopImmediatePropagation();// Transfer the held pointer to new capture without releasing it.
|
|
284
|
+
const start=p.start;pinPress=null;cancel();const mode=host.pose(view)?.mode;if(!mode)return;
|
|
285
|
+
pending={view,start,end:at,mode,id:e.pointerId,interaction,settled:host.pause()};pending.settled.catch(error=>host.error(String(error)));
|
|
286
|
+
}
|
|
287
|
+
if(!pending||pending.id!==e.pointerId)return;e.preventDefault();e.stopImmediatePropagation();pending.end=local(e);draftMark={view,mode:pending.mode,screen:region(pending.start,pending.end)};last='';};
|
|
288
|
+
const up=async(e:PointerEvent)=>{
|
|
289
|
+
if(geometryDrag?.id===e.pointerId){e.preventDefault();e.stopImmediatePropagation();geometryDrag=null;if(pane!.hasPointerCapture(e.pointerId))pane!.releasePointerCapture(e.pointerId);return;}
|
|
290
|
+
if(pinPress?.id===e.pointerId){e.preventDefault();e.stopImmediatePropagation();const pin=pinPress.pin;pinPress=null;if(pane!.hasPointerCapture(e.pointerId))pane!.releasePointerCapture(e.pointerId);pin.click();return;}
|
|
291
|
+
if(!pending||pending.id!==e.pointerId)return;e.preventDefault();e.stopImmediatePropagation();const p=pending;pending=null;if(pane!.hasPointerCapture(e.pointerId))pane!.releasePointerCapture(e.pointerId);try{await p.settled;assertCapture();if(disposed||interaction!==p.interaction||!enabled)return;const r=Math.hypot(p.end.x-p.start.x,p.end.y-p.start.y)<4?region(p.start,p.start):region(p.start,p.end);openComposer(view,r,undefined,p.mode);}catch(error){host.error(String(error));cancel();}};
|
|
292
|
+
const abort=(e:PointerEvent)=>{if(pending?.view===view&&pending.id===e.pointerId||geometryDrag?.id===e.pointerId||pinPress?.id===e.pointerId)cancel();};
|
|
293
|
+
const suppressClick=(e:MouseEvent)=>{if((e.target as Element)?.closest('.stage-comment-pin')&&e.isTrusted&&e.detail>0&&(suppressPinClick||spaceHeld())){suppressPinClick=false;e.preventDefault();e.stopImmediatePropagation();}};
|
|
294
|
+
pane!.addEventListener('click',suppressClick,true);disposers.push(()=>pane!.removeEventListener('click',suppressClick,true));
|
|
226
295
|
pane!.addEventListener('pointerdown',down,true);pane!.addEventListener('pointermove',move,true);pane!.addEventListener('pointerup',up,true);pane!.addEventListener('pointercancel',abort,true);pane!.addEventListener('lostpointercapture',abort,true);
|
|
227
296
|
disposers.push(()=>{pane!.removeEventListener('pointerdown',down,true);pane!.removeEventListener('pointermove',move,true);pane!.removeEventListener('pointerup',up,true);pane!.removeEventListener('pointercancel',abort,true);pane!.removeEventListener('lostpointercapture',abort,true);});
|
|
228
297
|
}
|
|
229
|
-
const key=(e:KeyboardEvent)=>{if(host.shortcutActive&&!host.shortcutActive())return;if(e.key==='Escape'&&(pending||composer||
|
|
230
|
-
window.addEventListener('blur',cancel);window.addEventListener('resize',placeList);document.addEventListener('keydown',key);toggle.onclick=()=>setOpen(inline
|
|
298
|
+
const key=(e:KeyboardEvent)=>{if(host.shortcutActive&&!host.shortcutActive())return;if(e.key==='Escape'&&(pending||composer||pinPress)){e.preventDefault();cancel();renderPins();return;}if(e.defaultPrevented||e.repeat||e.ctrlKey||e.metaKey||e.altKey||textEntryFocused(e.target)||host.shortcutBlocked?.())return;if(e.key.toLowerCase()==='c'){e.preventDefault();setOpen(inline?!enabled:list.hidden);}};
|
|
299
|
+
window.addEventListener('blur',cancel);window.addEventListener('resize',placeList);document.addEventListener('keydown',key);toggle.onclick=(e?:MouseEvent)=>{if(e?.detail)toggle.blur?.();setOpen(inline?!enabled:list.hidden);};
|
|
231
300
|
const ro=typeof ResizeObserver==='function'?new ResizeObserver(()=>{if(!disposed&&!list.hidden)placeList();}):null;if(ro){try{ro.observe(host.toolbar);if(workspace)ro.observe(workspace);}catch{}}
|
|
232
301
|
const renderPins=()=>{if(disposed)return;if(enabled&&host.hasPicture?.()===false){cancel();setCapture(false);}if(!list.hidden)placeList();const refusal=updateRefusal();if(refusal&&(enabled||pending||composer&&!composerReadOnly&&!composerGeneral)){cancel();setCapture(false);host.error(refusal);}const all=host.feedback().map(f=>({f,mark:readMark(f)})).filter(x=>x.mark);
|
|
233
302
|
// #356: a pose reads the pane's size (a forced layout after the played frame's writes); with no mark, draft or pending
|
|
234
303
|
// capture there is nothing to place, so this per-frame loop skips it.
|
|
235
304
|
const poses=new Map(all.length||draftMark||pending?[...layers.keys()].map(view=>[view,host.pose(view)]):[]);
|
|
236
305
|
if(draftMark&&poses.get(draftMark.view)?.mode!==draftMark.mode||pending&&poses.get(pending.view)?.mode!==pending.mode)cancel();
|
|
237
|
-
|
|
238
|
-
|
|
306
|
+
if(geometryEdit&&(geometryEdit.id&&host.locked(geometryEdit.id)||JSON.stringify(poses.get(geometryEdit.view)?.camera)!==geometryEdit.camera))cancel();
|
|
307
|
+
const signature=JSON.stringify([geometryEdit?.screen,curLang(),refusal,all.map(({f,mark})=>[f.id,f.summary,mark!.mode,mark!.world]),[...poses].map(([view,p])=>[view,host.codec&&p?host.codec.signature(p):[p?.mode,p?.animation,p?.frame,p?.timeBasis,p?.time,p?.turn,p?.camera,p?.referenceId,p?.referenceHash]]),draftMark]);
|
|
308
|
+
if(signature!==last){last=signature;for(const layer of layers.values())layer.replaceChildren();const occupied=new Map<StageComment['viewport'],{x:number;y:number;width:number;height:number}[]>();for(const [i,{f,mark:m}]of all.entries()){
|
|
239
309
|
const mark=m!,pose=poses.get(mark.viewport),layer=layers.get(mark.viewport);if(refusal||!pose||!layer||(host.codec?!host.codec.matches(mark,pose,f):pose.mode!==mark.mode||pose.animation!==mark.animation||pose.sourceHash!==mark.sourceHash||pose.modelHash!==mark.modelHash||pose.referenceId!==mark.referenceId||pose.referenceHash!==mark.referenceHash||JSON.stringify(pose.frame)!==JSON.stringify(mark.frame)||JSON.stringify(pose.timeBasis??null)!==JSON.stringify(mark.timeBasis??null)||Math.abs((pose.time??0)-(mark.time??0))>1e-7||JSON.stringify(pose.turn)!==JSON.stringify((f.context as any)?.turn??null)))continue;
|
|
240
|
-
const a=projectMark(mark.world,pose.camera),b=projectMark({x:mark.world.x+mark.world.width,y:mark.world.y+mark.world.height},pose.camera),r=region(a,b),box=rectElement(r),pin=document.createElement('button');pin.type='button';pin.className='stage-comment-pin stage-comment-ui';pin.textContent=String(i+1);pin.setAttribute('aria-label',`${t('Comment {0}:').replace('{0}',String(i+1))} ${f.summary}`);pin.title=f.summary;Object.assign(pin.style,{left:r.x+'px',top:r.y+'px'});pin.onclick=()=>openComment(f);layer.append(box,pin);
|
|
241
|
-
|
|
310
|
+
const a=projectMark(mark.world,pose.camera),b=projectMark({x:mark.world.x+mark.world.width,y:mark.world.y+mark.world.height},pose.camera),r=geometryEdit?.id===f.id?geometryEdit.screen:region(a,b),box=rectElement(r),pin=document.createElement('button');pin.type='button';pin.className='stage-comment-pin stage-comment-ui';pin.textContent=String(i+1);pin.setAttribute('aria-label',`${t('Comment {0}:').replace('{0}',String(i+1))} ${f.summary}`);pin.title=f.summary;Object.assign(pin.style,{left:r.x+'px',top:r.y+'px'});pin.onclick=()=>openComment(f);layer.append(box,pin);
|
|
311
|
+
const pane=host.viewports[mark.viewport]!;
|
|
312
|
+
if(host.codec?.geometry&&r.x>=0&&r.y>=0&&r.x<=pane.clientWidth&&r.y<=pane.clientHeight){
|
|
313
|
+
const width=pin.offsetWidth||24,height=pin.offsetHeight||24,placed=occupied.get(mark.viewport)??[];
|
|
314
|
+
if(!occupied.has(mark.viewport)){
|
|
315
|
+
occupied.set(mark.viewport,placed);
|
|
316
|
+
if(geometryEdit?.view===mark.viewport){const r=geometryEdit.screen;for(const [x,y]of [[0,0],[.5,0],[1,0],[1,.5],[1,1],[.5,1],[0,1],[0,.5]])placed.push({x:r.x+r.width*x!,y:r.y+r.height*y!,width:12,height:12});}
|
|
317
|
+
}
|
|
318
|
+
const clamp=(n:number,size:number,limit:number)=>Math.max(size/2,Math.min(limit-size/2,n));
|
|
319
|
+
const clear=(x:number,y:number)=>placed.every(p=>Math.abs(p.x-x)>=(p.width+width)/2+2||Math.abs(p.y-y)>=(p.height+height)/2+2);
|
|
320
|
+
let x=clamp(r.x,width,pane.clientWidth),y=clamp(r.y,height,pane.clientHeight),distance=Infinity;
|
|
321
|
+
if(!clear(x,y))for(let py=height/2;py<=pane.clientHeight-height/2;py+=height+4)for(let px=width/2;px<=pane.clientWidth-width/2;px+=width+4){const d=(px-r.x)**2+(py-r.y)**2;if(d<distance&&clear(px,py)){x=px;y=py;distance=d;}}
|
|
322
|
+
placed.push({x,y,width,height});Object.assign(pin.style,{left:x+'px',top:y+'px'});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
}if(draftMark&&!geometryEdit)layers.get(draftMark.view)?.append(rectElement(draftMark.screen));
|
|
326
|
+
if(geometryEdit){
|
|
327
|
+
const {view,screen:r}=geometryEdit,layer=layers.get(view)!,box=rectElement(r);box.dataset.commentHandle='move';Object.assign(box.style,{pointerEvents:'auto',cursor:'move'});layer.prepend(box);
|
|
328
|
+
for(const [name,x,y]of [['nw',0,0],['n',.5,0],['ne',1,0],['e',1,.5],['se',1,1],['s',.5,1],['sw',0,1],['w',0,.5]] as const){
|
|
329
|
+
const handle=document.createElement('button');handle.type='button';handle.dataset.commentHandle=name;handle.className='stage-comment-ui';handle.setAttribute('aria-label',t('Resize comment area: {0}').replace('{0}',name));
|
|
330
|
+
Object.assign(handle.style,{position:'absolute',left:r.x+r.width*x+'px',top:r.y+r.height*y+'px',width:'12px',height:'12px',minWidth:'12px',minHeight:'12px',padding:'0',transform:'translate(-50%,-50%)',pointerEvents:'auto',cursor:name+'-resize',borderWidth:'2px',borderStyle:'solid',borderColor:'var(--link)',background:'var(--rv-panel)'});layer.append(handle);
|
|
331
|
+
}
|
|
332
|
+
}}};
|
|
242
333
|
const paint=()=>{if(disposed)return;renderPins();raf=requestAnimationFrame(paint);};
|
|
243
334
|
const offLang=onLang(()=>{if(disposed)return;updateRefusal();renderList();syncComposerLang?.();last='';renderPins();});
|
|
244
335
|
refresh();paint();return {active:()=>enabled,draft:()=>!!pending||!!composer&&!composerReadOnly,refresh,dispose:()=>{disposed=true;ro?.disconnect();offLang();cancelAnimationFrame(raf);cancel();window.removeEventListener('blur',cancel);window.removeEventListener('resize',placeList);document.removeEventListener('keydown',key);for(const dispose of disposers)dispose();for(const layer of layers.values())layer.remove();toggle.onclick=null;list.remove();refusalNote.remove();}};
|
package/web/view-controls.ts
CHANGED
|
@@ -58,7 +58,8 @@ export function bindAppearance(control:HTMLSelectElement,initial:ThemePreference
|
|
|
58
58
|
export function syncStageLayout(area:Pick<HTMLElement,'clientWidth'|'clientHeight'|'dataset'>):boolean {const next=stageOrientation(area.clientWidth,area.clientHeight);if(area.dataset.orientation===next)return false;area.dataset.orientation=next;return true;}
|
|
59
59
|
export function bindStageLayout(area:HTMLElement,changed:()=>void):()=>void {
|
|
60
60
|
const render=()=>{if(syncStageLayout(area))changed();};
|
|
61
|
-
const
|
|
61
|
+
const contextMenu=(event:Event)=>{if(!(event.target instanceof Element&&event.target.closest('.stage-comment-composer,input,textarea,select,[contenteditable]:not([contenteditable="false"])')))event.preventDefault();};
|
|
62
|
+
const observer=new ResizeObserver(render);observer.observe(area);area.addEventListener?.('contextmenu',contextMenu);render();return ()=>{observer.disconnect();area.removeEventListener?.('contextmenu',contextMenu);};
|
|
62
63
|
}
|
|
63
64
|
/** Single-key layer toggles. Free of Space (pan), Enter (frame entry), arrows/Home/End (tabs, separators, part list). */
|
|
64
65
|
export const layerShortcuts=Object.freeze([
|
|
@@ -204,8 +205,11 @@ export function createViewControls(options:ViewControlsOptions) {
|
|
|
204
205
|
return {zoomButtons,zoomGroup,syncLabel,value,nativeOne,viewSwitch,get viewModeIds(){return [...modes.keys()];},setMode,setDisabled,replaceViewSwitch};
|
|
205
206
|
}
|
|
206
207
|
|
|
208
|
+
export function panSpaceHeld():boolean {return panSpace;}
|
|
207
209
|
// Nested or separately disposed pan binders must not restore another binder's override.
|
|
208
210
|
const panVideoOverrides=new WeakMap<HTMLVideoElement,{owners:number;value:string;priority:string}>();
|
|
211
|
+
let panSpace=false;
|
|
212
|
+
const panSpaceOwners=new Set<object>();
|
|
209
213
|
/**
|
|
210
214
|
* A drag that also carries the rig (#331): once the press has travelled more than `threshold` px from where it went down
|
|
211
215
|
* (the click/drag line, the same one a stage click reads), each move is handed to `move` as well as panned. The first
|
|
@@ -213,8 +217,9 @@ const panVideoOverrides=new WeakMap<HTMLVideoElement,{owners:number;value:string
|
|
|
213
217
|
* with Space held is a pan only, and a press that never passes the threshold is a click and carries nothing.
|
|
214
218
|
*/
|
|
215
219
|
export interface PanCarry {threshold:number;move:(dx:number,dy:number)=>void}
|
|
216
|
-
export function bindPan(viewport:HTMLElement,move:(dx:number,dy:number)=>void,enabled:()=>boolean=()=>true,carry?:PanCarry,pinch?:(factor:number,at:ViewPoint,delta:ViewPoint)=>void):()=>void {
|
|
220
|
+
export function bindPan(viewport:HTMLElement,move:(dx:number,dy:number)=>void,enabled:(panOnly?:boolean)=>boolean=()=>true,carry?:PanCarry,pinch?:(factor:number,at:ViewPoint,delta:ViewPoint)=>void):()=>void {
|
|
217
221
|
let pointer:number|null=null,x=0,y=0,space=false,press:{x:number;y:number;far:boolean}|null=null;
|
|
222
|
+
const owner={};
|
|
218
223
|
const touches=new Map<number,ViewPoint>();let pinching=false;const pair=()=>{const [a,b]=[...touches.values()];return a&&b?{distance:Math.hypot(a.x-b.x,a.y-b.y),center:{x:(a.x+b.x)/2,y:(a.y+b.y)/2}}:null;};
|
|
219
224
|
const videos=new Set<HTMLVideoElement>();
|
|
220
225
|
const releaseVideo=(video:HTMLVideoElement)=>{
|
|
@@ -231,15 +236,15 @@ export function bindPan(viewport:HTMLElement,move:(dx:number,dy:number)=>void,en
|
|
|
231
236
|
}
|
|
232
237
|
};
|
|
233
238
|
const observer=new MutationObserver(()=>{if(space)syncVideos();});
|
|
234
|
-
const releaseSpace=()=>{space=false;observer.disconnect();for(const video of videos)releaseVideo(video);videos.clear();};
|
|
239
|
+
const releaseSpace=()=>{space=false;panSpaceOwners.delete(owner);panSpace=panSpaceOwners.size>0;observer.disconnect();for(const video of videos)releaseVideo(video);videos.clear();};
|
|
235
240
|
const releasePointer=()=>{const id=pointer;pointer=null;press=null;delete viewport.dataset.panning;if(id!==null&&viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);};
|
|
236
|
-
const keyDown=(event:KeyboardEvent)=>{if(event.code==='Space'&&enabled()&&!(event.target instanceof Element&&event.target.closest('input,textarea,select,button'))){
|
|
237
|
-
if(!space){space=true;syncVideos();observer.observe(viewport,{childList:true,subtree:true,attributes:true,attributeFilter:['controls']});}event.preventDefault();
|
|
241
|
+
const keyDown=(event:KeyboardEvent)=>{if(event.code==='Space'&&enabled(true)&&!(event.target instanceof Element&&event.target.closest('input,textarea,select,button'))){
|
|
242
|
+
if(!space){space=true;panSpaceOwners.add(owner);panSpace=true;syncVideos();observer.observe(viewport,{childList:true,subtree:true,attributes:true,attributeFilter:['controls']});}event.preventDefault();
|
|
238
243
|
}};
|
|
239
244
|
const keyUp=(event:KeyboardEvent)=>{if(event.code==='Space')releaseSpace();};const blur=()=>{for(const id of touches.keys())if(viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);touches.clear();pinching=false;releaseSpace();releasePointer();};
|
|
240
|
-
const start=(event:PointerEvent)=>{if(enabled()&&pinch&&event.pointerType==='touch'&&!(event.target as Element)?.closest?.('button,input,select,textarea,a,[data-viewport-action]')){touches.set(event.pointerId,{x:event.clientX,y:event.clientY});if(touches.size===2){pointer=null;press=null;delete viewport.dataset.panning;pinching=true;viewport.setPointerCapture(event.pointerId);event.preventDefault();return;}}if(!enabled()||!event.isPrimary||event.button!==0)return;const target=event.target;if(target instanceof Element&&(target.closest('button,input,select,textarea,a,[data-viewport-action]')||target.closest('video[controls]')&&!
|
|
245
|
+
const start=(event:PointerEvent)=>{if(enabled(false)&&pinch&&event.pointerType==='touch'&&!(event.target as Element)?.closest?.('button,input,select,textarea,a,[data-viewport-action]')){touches.set(event.pointerId,{x:event.clientX,y:event.clientY});if(touches.size===2){pointer=null;press=null;delete viewport.dataset.panning;pinching=true;viewport.setPointerCapture(event.pointerId);event.preventDefault();return;}}const right=event.button===2,panOnly=space||panSpace||right;if(!enabled(panOnly)||!event.isPrimary||event.button!==0&&!right)return;const target=event.target,onPin=panOnly&&target instanceof Element&&!!target.closest('.stage-comment-pin,[data-comment-handle]');if(target instanceof Element&&(!onPin&&target.closest('button,input,select,textarea,a,[data-viewport-action],.stage-comment-composer')||target.closest('video[controls]')&&!panOnly))return;pointer=event.pointerId;x=event.clientX;y=event.clientY;press=carry&&!panOnly?{x,y,far:false}:null;viewport.setPointerCapture(pointer);viewport.dataset.panning='true';event.preventDefault();};
|
|
241
246
|
const drag=(event:PointerEvent)=>{
|
|
242
|
-
if(touches.has(event.pointerId)){const before=pair();touches.set(event.pointerId,{x:event.clientX,y:event.clientY});const after=pair();if(pinching){if(enabled()&&before&&after&&before.distance>0&&after.distance>0){const r=viewport.getBoundingClientRect();pinch?.(after.distance/before.distance,{x:before.center.x-r.left,y:before.center.y-r.top},{x:after.center.x-before.center.x,y:after.center.y-before.center.y});}event.preventDefault();return;}}
|
|
247
|
+
if(touches.has(event.pointerId)){const before=pair();touches.set(event.pointerId,{x:event.clientX,y:event.clientY});const after=pair();if(pinching){if(enabled(false)&&before&&after&&before.distance>0&&after.distance>0){const r=viewport.getBoundingClientRect();pinch?.(after.distance/before.distance,{x:before.center.x-r.left,y:before.center.y-r.top},{x:after.center.x-before.center.x,y:after.center.y-before.center.y});}event.preventDefault();return;}}
|
|
243
248
|
if(event.pointerId!==pointer)return;const dx=event.clientX-x,dy=event.clientY-y;x=event.clientX;y=event.clientY;move(dx,dy);event.preventDefault();
|
|
244
249
|
if(!press||!carry)return;
|
|
245
250
|
if(press.far)carry.move(dx,dy);
|
|
@@ -247,8 +252,9 @@ export function bindPan(viewport:HTMLElement,move:(dx:number,dy:number)=>void,en
|
|
|
247
252
|
};
|
|
248
253
|
const end=(event:PointerEvent)=>{touches.delete(event.pointerId);if(event.pointerType==='touch'&&viewport.hasPointerCapture(event.pointerId))viewport.releasePointerCapture(event.pointerId);if(touches.size===0)pinching=false;if(event.pointerId===pointer)releasePointer();};
|
|
249
254
|
const native=(event:DragEvent)=>event.preventDefault();
|
|
250
|
-
|
|
251
|
-
|
|
255
|
+
const contextMenu=(event:Event)=>{if(!(event.target instanceof Element&&event.target.closest('.stage-comment-composer,input,textarea,select,[contenteditable]:not([contenteditable="false"])')))event.preventDefault();};
|
|
256
|
+
window.addEventListener('blur',blur);document.addEventListener('keydown',keyDown,true);window.addEventListener('keyup',keyUp,true);viewport.addEventListener('pointerdown',start);viewport.addEventListener('pointermove',drag);viewport.addEventListener('pointerup',end);viewport.addEventListener('pointercancel',end);viewport.addEventListener('lostpointercapture',end);viewport.addEventListener('dragstart',native);viewport.addEventListener('contextmenu',contextMenu);
|
|
257
|
+
return ()=>{blur();window.removeEventListener('blur',blur);document.removeEventListener('keydown',keyDown,true);window.removeEventListener('keyup',keyUp,true);viewport.removeEventListener('pointerdown',start);viewport.removeEventListener('pointermove',drag);viewport.removeEventListener('pointerup',end);viewport.removeEventListener('pointercancel',end);viewport.removeEventListener('lostpointercapture',end);viewport.removeEventListener('dragstart',native);viewport.removeEventListener('contextmenu',contextMenu);};
|
|
252
258
|
}
|
|
253
259
|
|
|
254
260
|
/** A discovered row; the block adapter supplies nodes, never another activation implementation. */
|
|
@@ -43,7 +43,7 @@ export interface ViewportController {
|
|
|
43
43
|
requestFit:()=>void;
|
|
44
44
|
/** Drop an owed or held Fit, for a caller that sets the camera itself (a restored bookmark). */
|
|
45
45
|
cancelFit:()=>void;
|
|
46
|
-
state:ViewportState;paneFrame:(target:CameraTarget,hidden?:boolean)=>CameraFrame|null;paneCamera:(target:CameraTarget)=>PaneCamera;writeCamera:(target:CameraTarget,value:PaneCamera)=>void;activateCamera:(target:CameraTarget)=>void;availableCamera:()=>CameraTarget|null;alignCameras:()=>void;renderCameraControls:()=>void;setCameraSync:(value:boolean)=>void;cameraAction:(action:()=>void)=>void;updateCamera:(target:CameraTarget,value:CameraSignature,group?:readonly CameraTarget[])=>void;zoomCamera:(factor:number,target?:CameraTarget|null,point?:CameraPoint|null)=>void;panCamera:(target:CameraTarget,dx:number,dy:number)=>void;fitActiveCamera:(target?:CameraTarget|null)=>void;fitSelection:(target?:CameraTarget|null)=>void;zoomViewport:(target:CameraTarget,deltaY:number,point?:CameraPoint|null)=>void;fitCamera:()=>void;numericView:()=>ControlView;renderNumericView:()=>void;bindControls:(onUnitScale?:(target:CameraTarget)=>void)=>()=>void;bindNavigation:(carryRig?:PanCarry|((target:CameraTarget)=>PanCarry|undefined),enabled?:()=>boolean)=>()=>void;observeResize:()=>ResizeObserver;
|
|
46
|
+
state:ViewportState;paneFrame:(target:CameraTarget,hidden?:boolean)=>CameraFrame|null;paneCamera:(target:CameraTarget)=>PaneCamera;writeCamera:(target:CameraTarget,value:PaneCamera)=>void;activateCamera:(target:CameraTarget)=>void;availableCamera:()=>CameraTarget|null;alignCameras:()=>void;renderCameraControls:()=>void;setCameraSync:(value:boolean)=>void;cameraAction:(action:()=>void)=>void;updateCamera:(target:CameraTarget,value:CameraSignature,group?:readonly CameraTarget[])=>void;zoomCamera:(factor:number,target?:CameraTarget|null,point?:CameraPoint|null)=>void;panCamera:(target:CameraTarget,dx:number,dy:number)=>void;fitActiveCamera:(target?:CameraTarget|null)=>void;fitSelection:(target?:CameraTarget|null)=>void;zoomViewport:(target:CameraTarget,deltaY:number,point?:CameraPoint|null)=>void;fitCamera:()=>void;numericView:()=>ControlView;renderNumericView:()=>void;bindControls:(onUnitScale?:(target:CameraTarget)=>void)=>()=>void;bindNavigation:(carryRig?:PanCarry|((target:CameraTarget)=>PanCarry|undefined),enabled?:(panOnly?:boolean)=>boolean)=>()=>void;observeResize:()=>ResizeObserver;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
export function createViewportController(provider:ViewportProvider,state=createViewportState()):ViewportController {
|
|
@@ -163,7 +163,7 @@ function renderNumericView():void {const node=document.getElementById('view-coor
|
|
|
163
163
|
}
|
|
164
164
|
return ()=>{for(const dispose of disposers)dispose();if(nativeOne)nativeOne.onclick=null;for(const id of ['zoom-in','zoom-out','fit'])button(id).onclick=null;input('camera-sync').onchange=null;};
|
|
165
165
|
}
|
|
166
|
-
function bindNavigation(carryRig?:PanCarry|((target:CameraTarget)=>PanCarry|undefined),enabled:()=>boolean=()=>true):()=>void {
|
|
166
|
+
function bindNavigation(carryRig?:PanCarry|((target:CameraTarget)=>PanCarry|undefined),enabled:(panOnly?:boolean)=>boolean=()=>true):()=>void {
|
|
167
167
|
const disposers:(()=>void)[]=[];disposers.push(bindStageLayout(el('stage-layout'),fitCamera));
|
|
168
168
|
for(const {target,viewport}of panes())disposers.push(bindPan(viewport,(dx,dy)=>cameraAction(()=>panCamera(target,dx,dy)),enabled,typeof carryRig==='function'?carryRig(target):target==='rig'?carryRig:undefined,provider.pinch===false?undefined:(factor,at,delta)=>cameraAction(()=>{zoomCamera(factor,target,at);panCamera(target,delta.x,delta.y);})));
|
|
169
169
|
return ()=>disposers.forEach(dispose=>dispose());
|