rig-review 0.20.0 → 0.22.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.
@@ -1,11 +1,99 @@
1
- import type {RigPlayer,PosedFrame} from '@rig-c/play';
2
- import {boneHierarchy,CHANNELS,channelSegments,evaluateBoneLocals,evaluateStoredChannel,filterTracks,readAnimationInspection,type AnimationInspection,type InspectionTarget,type InspectionTrack} from '../src/animation-inspection.ts';
1
+ import type {BoneAdjust,PosedFrame,RigPlayer} from '@rig-c/play';
2
+ import {
3
+ boneHierarchy,
4
+ CHANNELS,
5
+ channelSegments,
6
+ evaluateBoneLocals,
7
+ evaluateStoredChannel,
8
+ filterTracks,
9
+ readAnimationInspection,
10
+ type AnimationInspection,
11
+ type InspectionTarget,
12
+ type InspectionTrack,
13
+ } from '../src/animation-inspection.ts';
14
+ import {
15
+ AnimationOpBuilder,
16
+ checkAnimationEditGate,
17
+ classifyAnimationTracks,
18
+ cleanMotionNumber,
19
+ findBoneConstraint,
20
+ MAX_ANIMATION_OPS,
21
+ overlayDraftOnInspection,
22
+ seedCubicCurve,
23
+ type AnimationEditGate,
24
+ type AnimationSourceOp,
25
+ type EasingTuple,
26
+ type TrackClassification,
27
+ } from '../src/animation-ops.ts';
28
+ import type {AppliedAnimation} from '../src/applied-context.ts';
29
+ import type {AnimationSourceView} from './rebuild-client.ts';
3
30
  import {InspectionSelection} from './inspection-selection.ts';
31
+ import {animationPreviewAdjust} from './preview.ts';
32
+
4
33
  const NS='http://www.w3.org/2000/svg';
5
34
  const svg=(tag:string,attrs:Record<string,string|number>)=>{const n=document.createElementNS(NS,tag);for(const [k,v]of Object.entries(attrs))n.setAttribute(k,String(v));return n;};
6
35
  const numeric=(value:number)=>Object.is(value,-0)?'-0':String(value);
7
- const button=(label:string,click:()=>void)=>{const b=document.createElement('button');b.type='button';b.textContent=label;b.onclick=click;return b;};
8
- export interface AnimationPanelOptions {host:HTMLElement;stage:HTMLElement;select:(value:InspectionTarget)=>void;seek:(time:number)=>void;project:(x:number,y:number)=>{x:number;y:number};enabled:()=>boolean}
36
+ const button=(label:string,click:(e?:MouseEvent)=>void)=>{const b=document.createElement('button');b.type='button';b.textContent=label;b.onclick=click;return b;};
37
+
38
+ /** Clean human-readable seconds without Float32 noise (e.g. 1.6 instead of 1.600000023841858). */
39
+ export function formatSeconds(value:number):string {
40
+ if(!Number.isFinite(value))return '0';
41
+ const cleaned=Number(value.toFixed(4));
42
+ return Object.is(cleaned,-0)?'0':String(cleaned);
43
+ }
44
+
45
+ /** Clean ruler tick positions from 0 to end for the given horizontal zoom factor. */
46
+ export function buildRulerTicks(end:number,zoom=1):number[] {
47
+ if(!(end>0)||!Number.isFinite(end))return [0];
48
+ const cleanEnd=Number(end.toFixed(4));
49
+ const niceSteps=[0.02,0.05,0.1,0.2,0.25,0.5,1,2,5,10];
50
+ const targetCount=Math.max(6,Math.min(32,Math.round(8*Math.max(1,zoom))));
51
+ const step=niceSteps.find(s=>cleanEnd/s<=targetCount)??niceSteps.at(-1)!;
52
+ const ticks:number[]=[0];
53
+ for(let i=1;i*step<cleanEnd-step*0.35;i++){
54
+ ticks.push(Number((i*step).toFixed(4)));
55
+ }
56
+ if(ticks.at(-1)!==cleanEnd)ticks.push(cleanEnd);
57
+ return ticks;
58
+ }
59
+
60
+ export interface AnimationPanelOptions {
61
+ host:HTMLElement;
62
+ stage:HTMLElement;
63
+ select:(value:InspectionTarget)=>void;
64
+ seek:(time:number)=>void;
65
+ project:(x:number,y:number)=>{x:number;y:number};
66
+ enabled:()=>boolean;
67
+ preview?:(adjust:BoneAdjust|null,active:boolean)=>void;
68
+ apply?:(ops:readonly AnimationSourceOp[])=>Promise<unknown>;
69
+ reset?:()=>Promise<void>;
70
+ pause?:()=>void;
71
+ readOnlyReason?:string|null|(()=>string|null);
72
+ }
73
+
74
+ export interface SelectedAnimationKey {
75
+ animation:string;
76
+ trackIndex:number;
77
+ keyIndex:number;
78
+ pointer:string;
79
+ }
80
+
81
+ export interface AnimationSideState {
82
+ document?:unknown;
83
+ animation?:string;
84
+ baseInspection?:AnimationInspection|null;
85
+ source:AnimationSourceView|null;
86
+ sourceLoaded:boolean;
87
+ sourceFallbackReason:string|null;
88
+ builder:AnimationOpBuilder|null;
89
+ appliedOps:AnimationSourceOp[];
90
+ selectedKey:SelectedAnimationKey|null;
91
+ selectedKeys:SelectedAnimationKey[];
92
+ editorStatus:{text:string;error:boolean};
93
+ poseMode:'rotate'|'translate';
94
+ poseModeLockedByUser:boolean;
95
+ zoom:number;
96
+ }
9
97
 
10
98
  /** All picking reads the last drawn primitives, including their resolved clip; never a setup bounding box. */
11
99
  export function pickedSlot(frame:PosedFrame,x:number,y:number):string|null {
@@ -17,46 +105,1235 @@ export function pickedSlot(frame:PosedFrame,x:number,y:number):string|null {
17
105
  }return null;
18
106
  }
19
107
 
108
+ export const ANIMATION_APPLY_ISOLATION_NOTE =
109
+ 'An animation Apply builds from the handoff config.json and animations_from file into scratch (rig-parts rig → rigc build → rig-parts check), so it does not carry another kind\'s Apply on the stage.';
110
+
20
111
  export class AnimationInspectionPanel {
21
- private inspection:AnimationInspection|null=null;private document:unknown=null;private animation='';private at=0;private runtimeDuration=0;private track:InspectionTrack|null=null;private channel=0;private view='timeline';private unavailableChannel='';
22
- private selection:InspectionSelection;private panes=new Map<string,HTMLElement>();private views:HTMLButtonElement[]=[];private playhead:SVGElement|null=null;private cursor:SVGElement|null=null;private plot:((t:number,v:number)=>{x:number;y:number})|null=null;
23
- private channelSelect:HTMLSelectElement;private readout:HTMLOutputElement;private status:HTMLElement;private picks:HTMLElement;private bones=new Map<string,{x:number;y:number}>();private frame:PosedFrame|null=null;private down:{x:number;y:number}|null=null;private space=false;
24
- private disposers:(()=>void)[]=[];private boneButtons=new Map<string,HTMLButtonElement>();private bonePoints=false;
112
+ private baseInspection:AnimationInspection|null=null;
113
+ private inspection:AnimationInspection|null=null;
114
+ private document:unknown=null;
115
+ private animation='';
116
+ private at=0;
117
+ private runtimeDuration=0;
118
+ private track:InspectionTrack|null=null;
119
+ private channel=0;
120
+ private view='timeline';
121
+ private zoom=1;
122
+ private poseMode:'rotate'|'translate'='rotate';
123
+ private poseModeLockedByUser=false;
124
+ private unavailableChannel='';
125
+ private selection:InspectionSelection;
126
+ private panes=new Map<string,HTMLElement>();
127
+ private views:HTMLButtonElement[]=[];
128
+ private zoomButtons:HTMLButtonElement[]=[];
129
+ private poseModeButtons:HTMLButtonElement[]=[];
130
+ private playhead:SVGElement|null=null;
131
+ private cursor:SVGElement|null=null;
132
+ private plot:((t:number,v:number)=>{x:number;y:number})|null=null;
133
+ private channelSelect:HTMLSelectElement;
134
+ private segmentSelect:HTMLSelectElement;
135
+ private easeSelect:HTMLSelectElement;
136
+ private curveReadonly:HTMLElement;
137
+ private curvePlot:SVGSVGElement;
138
+ private curveSegment=0;
139
+ private readout:HTMLOutputElement;
140
+ private status:HTMLElement;
141
+ private gateBanner:HTMLElement;
142
+ private previewBadge:HTMLElement;
143
+ private opsSummary:HTMLElement;
144
+ private undoOpBtn:HTMLButtonElement;
145
+ private clearOpsBtn:HTMLButtonElement;
146
+ private applyBtn:HTMLButtonElement;
147
+ private resetBtn:HTMLButtonElement;
148
+ private applyNote:HTMLElement;
149
+ private editorStatus:HTMLElement;
150
+ private picks:HTMLElement;
151
+ private bones=new Map<string,{x:number;y:number;a:number;b:number;c:number;d:number;hasMatrix:boolean}>();
152
+ private frame:PosedFrame|null=null;
153
+ private down:{x:number;y:number}|null=null;
154
+ private space=false;
155
+ private disposers:(()=>void)[]=[];
156
+ private boneButtons=new Map<string,HTMLButtonElement>();
157
+ private bonePoints=false;
158
+
159
+ // Keyed animation editing state (Slice 3 / Slice 3b / Slice 4a / Slice 4b / Slice 4c)
160
+ private source:AnimationSourceView|null=null;
161
+ private sourceLoaded=false;
162
+ private sourceFallbackReason:string|null=null;
163
+ private builder:AnimationOpBuilder|null=null;
164
+ private appliedOps:AnimationSourceOp[]=[];
165
+ private cachedDraftText:string|null=null;
166
+ private cachedDraftDoc:unknown=undefined;
167
+ private cachedTracksKey='';
168
+ private cachedTracks:TrackClassification[]=[];
169
+ private cachedGateKey='';
170
+ private cachedGate:AnimationEditGate|null=null;
171
+ private selectedKey:SelectedAnimationKey|null=null;
172
+ private selectedKeys:SelectedAnimationKey[]=[];
173
+ private lastNonEmptyAnimation='';
174
+ private forceNextModelReload=false;
175
+ private isBusy=false;
176
+ private suppressNextKeyClick=false;
177
+ private suppressNextBoneClick=false;
178
+ private lastDockClientHeight=0;
179
+ private lastLanesHeight=186;
180
+ private draggingKey:{
181
+ pointerId:number;
182
+ trackIndex:number;
183
+ keyIndex:number;
184
+ startX:number;
185
+ moved:boolean;
186
+ wasAlreadyInMulti:boolean;
187
+ undoGroupId:number;
188
+ laneEl:HTMLElement;
189
+ markEl:HTMLButtonElement;
190
+ end:number;
191
+ }|null=null;
192
+ private draggingCurveHandle:{
193
+ pointerId:number;
194
+ trackIndex:number;
195
+ segmentIndex:number;
196
+ handleIndex:1|2;
197
+ channel:number;
198
+ undoGroupId:number;
199
+ low:number;
200
+ high:number;
201
+ span:number;
202
+ end:number;
203
+ }|null=null;
204
+ private draggingStageBone:{
205
+ pointerId:number;
206
+ boneName:string;
207
+ mode:'rotate'|'translate';
208
+ startX:number;
209
+ startY:number;
210
+ moved:boolean;
211
+ undoGroupId:number;
212
+ originWorld:{x:number;y:number};
213
+ parentWorld:{x:number;y:number;a:number;b:number;c:number;d:number};
214
+ }|null=null;
215
+
25
216
  constructor(private options:AnimationPanelOptions){
26
- const {host,stage}=options;host.classList.add('animation-inspection');host.innerHTML='<h3>Animation inspection · read only</h3><p data-inspection-status class="hint"></p><div class="animation-view-buttons" aria-label="Animation inspection views"></div><section data-animation-pane="timeline" aria-label="Timeline"></section><section data-animation-pane="curve" aria-label="Stored curves" hidden><label>Channel <select data-curve-channel aria-label="Stored animation channel"></select></label><label>Time (s) <input data-curve-time type="number" min="0" step="any" aria-label="Exact inspection seconds"></label><button data-curve-seek type="button">Inspect time</button><svg data-curve-plot role="img" aria-label="Exact stored curve and control points" viewBox="0 0 800 230"></svg><output data-curve-readout aria-live="off"></output><p class="hint">Stored curve and handles are exact. Runtime evaluation uses Play’s ten-piece Float32 interpolation; the cursor may sit off the cubic. Values are authored locals before constraints and previews.</p></section><section data-animation-pane="tree" aria-label="Bone tree" hidden></section>';
27
- this.status=host.querySelector('[data-inspection-status]')!;this.channelSelect=host.querySelector('[data-curve-channel]')!;this.readout=host.querySelector('[data-curve-readout]')!;
217
+ const {host,stage}=options;
218
+ host.classList.add('animation-inspection');
219
+ host.innerHTML=`<div class="animation-dock-bar">
220
+ <h3 class="animation-dock-title">Animation timeline &amp; inspection</h3>
221
+ <div class="animation-view-buttons" aria-label="Animation inspection views"></div>
222
+ <div class="animation-zoom-buttons" role="group" aria-label="Timeline horizontal zoom"></div>
223
+ <div class="animation-pose-buttons" role="group" aria-label="Stage bone pose mode"></div>
224
+ <div class="animation-editor-bar" data-animation-editor-bar>
225
+ <div class="animation-editor-actions">
226
+ <span class="animation-preview-badge" data-animation-preview-badge hidden>preview — Apply decides</span>
227
+ <span class="animation-ops-summary" data-animation-ops-summary>0 pending ops</span>
228
+ <button type="button" data-animation-undo-op disabled>Undo op</button>
229
+ <button type="button" data-animation-clear-ops disabled>Discard pending</button>
230
+ <button type="button" data-animation-apply disabled>Apply · Rebuild</button>
231
+ <button type="button" data-animation-reset disabled>Reset</button>
232
+ </div>
233
+ </div>
234
+ </div>
235
+ <div class="animation-dock-status">
236
+ <div class="animation-gate-banner hint" data-animation-gate></div>
237
+ <p class="hint" data-animation-editor-status role="status"></p>
238
+ <p class="hint" data-animation-apply-note></p>
239
+ <p data-inspection-status class="hint"></p>
240
+ </div>
241
+ <section data-animation-pane="timeline" aria-label="Timeline"></section>
242
+ <section data-animation-pane="curve" aria-label="Stored curves" hidden>
243
+ <div class="animation-curve-toolbar">
244
+ <label>Channel <select data-curve-channel aria-label="Stored animation channel"></select></label>
245
+ <label>Segment <select data-curve-segment aria-label="Curve segment"></select></label>
246
+ <label>Curve <select data-curve-ease aria-label="Segment curve or easing"></select></label>
247
+ <label>Time (s) <input data-curve-time type="number" min="0" step="any" aria-label="Exact inspection seconds"></label>
248
+ <button data-curve-seek type="button">Inspect time</button>
249
+ <span class="animation-curve-readonly hint" data-curve-readonly hidden></span>
250
+ <output data-curve-readout aria-live="off"></output>
251
+ </div>
252
+ <svg data-curve-plot role="img" aria-label="Exact stored curve and control points" viewBox="0 0 800 230"></svg>
253
+ <p class="hint">Stored curve and handles are exact. Runtime evaluation uses Play’s ten-piece Float32 interpolation; the cursor may sit off the cubic. Values are authored locals before constraints and previews.</p>
254
+ </section>
255
+ <section data-animation-pane="tree" aria-label="Bone tree" hidden></section>`;
256
+
257
+ this.status=host.querySelector('[data-inspection-status]')!;
258
+ this.gateBanner=host.querySelector('[data-animation-gate]')!;
259
+ this.previewBadge=host.querySelector('[data-animation-preview-badge]')!;
260
+ this.opsSummary=host.querySelector('[data-animation-ops-summary]')!;
261
+ this.undoOpBtn=host.querySelector('[data-animation-undo-op]')!;
262
+ this.clearOpsBtn=host.querySelector('[data-animation-clear-ops]')!;
263
+ this.applyBtn=host.querySelector('[data-animation-apply]')!;
264
+ this.resetBtn=host.querySelector('[data-animation-reset]')!;
265
+ this.applyNote=host.querySelector('[data-animation-apply-note]')!;
266
+ this.editorStatus=host.querySelector('[data-animation-editor-status]')!;
267
+ this.applyNote.textContent=ANIMATION_APPLY_ISOLATION_NOTE;
268
+ this.applyNote.title=ANIMATION_APPLY_ISOLATION_NOTE;
269
+ this.channelSelect=host.querySelector('[data-curve-channel]')!;
270
+ this.segmentSelect=host.querySelector('[data-curve-segment]')!;
271
+ this.easeSelect=host.querySelector('[data-curve-ease]')!;
272
+ this.curveReadonly=host.querySelector('[data-curve-readonly]')!;
273
+ this.curvePlot=host.querySelector('[data-curve-plot]')!;
274
+ this.readout=host.querySelector('[data-curve-readout]')!;
275
+
276
+ this.undoOpBtn.onclick=()=>{this.undoOp();};
277
+ this.clearOpsBtn.onclick=()=>{this.clearPending();};
278
+ this.applyBtn.onclick=()=>{if(this.options.apply)void this.options.apply(this.ops());};
279
+ this.resetBtn.onclick=()=>{this.resetEdits();if(this.options.reset)void this.options.reset();};
280
+
28
281
  for(const pane of host.querySelectorAll<HTMLElement>('[data-animation-pane]'))this.panes.set(pane.dataset.animationPane!,pane);
29
- for(const [id,label]of [['timeline','Timeline'],['curve','Curves'],['tree','Bone tree']]){const b=button(label!,()=>this.show(id!));b.dataset.animationView=id;host.querySelector('.animation-view-buttons')!.append(b);this.views.push(b);}
282
+ const viewButtonsHost=host.querySelector('.animation-view-buttons')!;
283
+ for(const [id,label]of [['timeline','Timeline'],['curve','Curves'],['tree','Bone tree']]){
284
+ const b=button(label!,()=>this.show(id!));
285
+ b.dataset.animationView=id;
286
+ viewButtonsHost.append(b);
287
+ this.views.push(b);
288
+ }
289
+ const zoomHost=host.querySelector('.animation-zoom-buttons');
290
+ if(zoomHost){
291
+ for(const z of [1,2,4,8]){
292
+ const zb=button(`${z}×`,()=>this.setZoom(z));
293
+ zb.dataset.animationZoom=String(z);
294
+ zb.setAttribute('aria-pressed',String(z===this.zoom));
295
+ zb.title=`Timeline horizontal zoom ${z}×`;
296
+ zoomHost.append(zb);
297
+ this.zoomButtons.push(zb);
298
+ }
299
+ }
300
+ const poseHost=host.querySelector('.animation-pose-buttons');
301
+ if(poseHost){
302
+ for(const [mode,label,tip] of [
303
+ ['rotate','Rotate','Drag bone handles on stage to rotate (hold Alt during drag to translate)'],
304
+ ['translate','Move','Drag bone handles on stage to translate (hold Alt during drag to rotate)'],
305
+ ] as const){
306
+ const pb=button(label,()=>this.setStagePoseMode(mode,true));
307
+ pb.dataset.stagePoseMode=mode;
308
+ pb.setAttribute('aria-pressed',String(mode===this.poseMode));
309
+ pb.title=tip;
310
+ poseHost.append(pb);
311
+ this.poseModeButtons.push(pb);
312
+ }
313
+ }
30
314
  this.selection=new InspectionSelection(value=>{options.select(value);this.renderSelection();});
31
315
  host.querySelector<HTMLButtonElement>('[data-curve-seek]')!.onclick=()=>{const value=host.querySelector<HTMLInputElement>('[data-curve-time]')!.value.trim();options.seek(value?Number(value):NaN);};
32
316
  this.channelSelect.onchange=()=>{this.unavailableChannel='';const [pointer,c]=JSON.parse(this.channelSelect.value) as [string,number];this.track=this.inspection?.tracks.find(t=>t.pointer===pointer)??null;this.channel=c;this.renderCurve();this.update(this.at,this.runtimeDuration);};
317
+ this.segmentSelect.onchange=()=>{
318
+ this.curveSegment=Math.max(0,Number(this.segmentSelect.value)||0);
319
+ const cls=this.resolveTrackClassification(this.track);
320
+ if(this.gateInfo().editable&&cls?.editable&&this.track){
321
+ const sel={animation:this.animation,trackIndex:cls.trackIndex,keyIndex:this.curveSegment,pointer:this.track.pointer};
322
+ this.selectedKey=sel;
323
+ this.selectedKeys=[sel];
324
+ this.syncTimelineKeysInPlace();
325
+ this.syncKeyInspectorInPlace();
326
+ }
327
+ this.renderCurve();
328
+ };
329
+ this.easeSelect.onchange=()=>{this.applyCurveModeChange(this.easeSelect.value);};
330
+ this.bindCurveHandleDrag();
33
331
  this.picks=document.createElement('div');this.picks.className='animation-stage-picks';stage.append(this.picks);
34
332
  const down=(e:PointerEvent)=>{this.down=e.isPrimary&&e.button===0?{x:e.clientX,y:e.clientY}:null;};
35
333
  const up=(e:PointerEvent)=>{const start=this.down;this.down=null;if(!start||Math.hypot(e.clientX-start.x,e.clientY-start.y)>3||this.space||!options.enabled()||e.target instanceof Element&&e.target.closest('button,input,select,textarea')||!this.frame)return;
36
334
  const rect=stage.getBoundingClientRect(),p0=options.project(0,0),px=options.project(1,0),py=options.project(0,1),x=(e.clientX-rect.left-p0.x)/(px.x-p0.x),y=(e.clientY-rect.top-p0.y)/(py.y-p0.y),slot=pickedSlot(this.frame,x,y);if(slot)this.select({kind:'slot',name:slot});
37
335
  };
38
- const key=(e:KeyboardEvent)=>{if(e.code==='Space')this.space=e.type==='keydown';};const blur=()=>{this.space=false;this.down=null;};
336
+ const key=(e:KeyboardEvent)=>{
337
+ if(e.code==='Space')this.space=e.type==='keydown';
338
+ if(e.type==='keydown'&&(e.key==='Delete'||e.key==='Backspace')&&!this.isBusy){
339
+ const active=document.activeElement as Element|null;
340
+ const inField=active&&typeof active.closest==='function'&&active.closest('input,textarea,select');
341
+ const inHost=active&&typeof this.options.host.contains==='function'&&this.options.host.contains(active);
342
+ if(!inField&&inHost){
343
+ if(this.selectedKeys.length>1){
344
+ e.preventDefault();
345
+ this.deleteSelection();
346
+ }else if(this.selectedKey&&this.selectedKey.animation===this.animation){
347
+ e.preventDefault();
348
+ this.deleteKey(this.selectedKey.trackIndex,this.selectedKey.keyIndex);
349
+ }
350
+ }
351
+ }
352
+ };
353
+ const blur=()=>{this.space=false;this.down=null;};
39
354
  stage.addEventListener('pointerdown',down);stage.addEventListener('pointerup',up);window.addEventListener('keydown',key);window.addEventListener('keyup',key);window.addEventListener('blur',blur);
40
- this.disposers.push(()=>{stage.removeEventListener('pointerdown',down);stage.removeEventListener('pointerup',up);window.removeEventListener('keydown',key);window.removeEventListener('keyup',key);window.removeEventListener('blur',blur);});this.show('timeline');
355
+ this.disposers.push(()=>{stage.removeEventListener('pointerdown',down);stage.removeEventListener('pointerup',up);window.removeEventListener('keydown',key);window.removeEventListener('keyup',key);window.removeEventListener('blur',blur);});
356
+
357
+ if(typeof ResizeObserver!=='undefined'&&typeof host.closest==='function'){
358
+ const playbackPanel=host.closest<HTMLElement>('[data-inspector-panel]');
359
+ const dockPanel=host.closest<HTMLElement>('.inspector');
360
+ const ro=new ResizeObserver(()=>{this.syncDockHeight(true);});
361
+ if(playbackPanel)ro.observe(playbackPanel);
362
+ if(dockPanel&&dockPanel!==playbackPanel)ro.observe(dockPanel);
363
+ ro.observe(host);
364
+ this.disposers.push(()=>ro.disconnect());
365
+ }
366
+ this.show('timeline');
367
+ this.renderEditorBar();
368
+ }
369
+
370
+ stagePoseMode():'rotate'|'translate'{
371
+ return this.poseMode;
372
+ }
373
+
374
+ setStagePoseMode(mode:'rotate'|'translate',lockedByUser=true){
375
+ if(mode!=='rotate'&&mode!=='translate')return;
376
+ this.poseMode=mode;
377
+ if(lockedByUser)this.poseModeLockedByUser=true;
378
+ for(const pb of this.poseModeButtons){
379
+ pb.setAttribute('aria-pressed',String(pb.dataset.stagePoseMode===this.poseMode));
380
+ }
381
+ this.redraw();
382
+ }
383
+
384
+ private isBoneEditableInMode(boneName:string,mode:'rotate'|'translate'=this.poseMode):boolean{
385
+ if(!this.gateInfo().editable)return false;
386
+ const props=mode==='rotate'?['rotate']:['translate','translatex','translatey'];
387
+ return this.tracksInfo().some(
388
+ c=>c.targetKind==='bone'&&c.target===boneName&&c.editable&&props.includes(c.property),
389
+ );
390
+ }
391
+
392
+ private firstEditableTrackIndexForBone(boneName:string,mode:'rotate'|'translate'=this.poseMode):number{
393
+ const props=mode==='rotate'?['rotate']:['translate','translatex','translatey'];
394
+ const hit=this.tracksInfo().find(
395
+ c=>c.targetKind==='bone'&&c.target===boneName&&c.editable&&props.includes(c.property),
396
+ );
397
+ return hit?hit.trackIndex:Number.MAX_SAFE_INTEGER;
41
398
  }
399
+
400
+ private overlappingBonesFor(boneName:string,maxScreenDistPx:number):string[]{
401
+ const origin=this.bones.get(boneName);
402
+ if(!origin)return [boneName];
403
+ const originScreen=this.options.project(origin.x,origin.y);
404
+ const btn=this.boneButtons.get(boneName);
405
+ const hasRealDomLayout=(btn?.getBoundingClientRect?.().width??0)>0;
406
+ const out:string[]=[];
407
+ for(const [name,p] of this.bones){
408
+ const worldDist=Math.hypot(p.x-origin.x,p.y-origin.y);
409
+ if(worldDist<=1e-3){
410
+ out.push(name);
411
+ continue;
412
+ }
413
+ if(hasRealDomLayout&&maxScreenDistPx>0){
414
+ const sc=this.options.project(p.x,p.y);
415
+ if(Math.hypot(sc.x-originScreen.x,sc.y-originScreen.y)<=maxScreenDistPx){
416
+ out.push(name);
417
+ }
418
+ }
419
+ }
420
+ return out.length>0?out:[boneName];
421
+ }
422
+
423
+ private sortOverlappingBones(candidates:readonly string[],mode:'rotate'|'translate'=this.poseMode):string[]{
424
+ const otherMode:'rotate'|'translate'=mode==='rotate'?'translate':'rotate';
425
+ const boneOrder=new Map((this.inspection?.bones??[]).map((b,i)=>[b.name,i]));
426
+ return [...candidates].sort((a,b)=>{
427
+ const aEdit=this.isBoneEditableInMode(a,mode);
428
+ const bEdit=this.isBoneEditableInMode(b,mode);
429
+ if(aEdit!==bEdit)return aEdit?-1:1;
430
+ if(aEdit&&bEdit){
431
+ const ta=this.firstEditableTrackIndexForBone(a,mode);
432
+ const tb=this.firstEditableTrackIndexForBone(b,mode);
433
+ if(ta!==tb)return ta-tb;
434
+ }
435
+ const aOther=this.isBoneEditableInMode(a,otherMode);
436
+ const bOther=this.isBoneEditableInMode(b,otherMode);
437
+ if(aOther!==bOther)return aOther?-1:1;
438
+ return (boneOrder.get(a)??0)-(boneOrder.get(b)??0);
439
+ });
440
+ }
441
+
442
+ private resolveBoneForStageDrag(boneName:string,mode:'rotate'|'translate'=this.poseMode):string{
443
+ const selected=this.selection.value();
444
+ const exactGroup=this.overlappingBonesFor(boneName,2);
445
+ const editableExact=this.sortOverlappingBones(
446
+ exactGroup.filter(n=>this.isBoneEditableInMode(n,mode)),
447
+ mode,
448
+ );
449
+ if(editableExact.length>0){
450
+ if(selected?.kind==='bone'&&editableExact.includes(selected.name)){
451
+ return selected.name;
452
+ }
453
+ return editableExact[0]!;
454
+ }
455
+ const hitboxGroup=this.overlappingBonesFor(boneName,12);
456
+ const editableNearby=this.sortOverlappingBones(
457
+ hitboxGroup.filter(n=>this.isBoneEditableInMode(n,mode)),
458
+ mode,
459
+ );
460
+ if(editableNearby.length>0){
461
+ if(selected?.kind==='bone'&&editableNearby.includes(selected.name)){
462
+ return selected.name;
463
+ }
464
+ return editableNearby[0]!;
465
+ }
466
+ return boneName;
467
+ }
468
+
469
+ private resolveBoneForStageClick(boneName:string):string{
470
+ const group=this.overlappingBonesFor(boneName,2);
471
+ const candidates=group.length>1?group:this.overlappingBonesFor(boneName,10);
472
+ if(candidates.length<=1)return boneName;
473
+ const ordered=this.sortOverlappingBones(candidates,this.poseMode);
474
+ const selected=this.selection.value();
475
+ const curIdx=selected?.kind==='bone'?ordered.indexOf(selected.name):-1;
476
+ if(curIdx<0)return ordered[0]!;
477
+ return ordered[(curIdx+1)%ordered.length]!;
478
+ }
479
+
480
+ private autoSyncPoseModeFromProperty(property:string|undefined){
481
+ if(this.poseModeLockedByUser||!property)return;
482
+ if(property==='rotate')this.setStagePoseMode('rotate',false);
483
+ else if(property==='translate'||property==='translatex'||property==='translatey')this.setStagePoseMode('translate',false);
484
+ }
485
+
486
+ zoomLevel():number{
487
+ return this.zoom;
488
+ }
489
+
490
+ setZoom(nextZoom:number){
491
+ const clamped=[1,2,4,8].includes(nextZoom)?nextZoom:1;
492
+ if(this.zoom===clamped)return;
493
+ this.zoom=clamped;
494
+ for(const zb of this.zoomButtons){
495
+ zb.setAttribute('aria-pressed',String(Number(zb.dataset.animationZoom)===this.zoom));
496
+ }
497
+ this.renderTimeline();
498
+ }
499
+
500
+ private syncDockHeight(fromResize=false){
501
+ const lanes=this.options.host.querySelector<HTMLElement>('.animation-lanes');
502
+ if(!lanes)return;
503
+ if(typeof this.options.host.closest!=='function'){
504
+ lanes.style.height=`${this.lastLanesHeight}px`;
505
+ lanes.style.maxHeight=`${this.lastLanesHeight}px`;
506
+ return;
507
+ }
508
+ const panel=this.options.host.closest<HTMLElement>('[data-inspector-panel]')??this.options.host.closest<HTMLElement>('.inspector');
509
+ if(!panel||panel.clientHeight<=0){
510
+ lanes.style.height=`${this.lastLanesHeight}px`;
511
+ lanes.style.maxHeight=`${this.lastLanesHeight}px`;
512
+ return;
513
+ }
514
+ if(fromResize||panel.clientHeight!==this.lastDockClientHeight){
515
+ this.lastDockClientHeight=panel.clientHeight;
516
+ const overhead=panel.hasAttribute('data-inspector-panel')?129:159;
517
+ this.lastLanesHeight=Math.max(104,Math.floor(panel.clientHeight-overhead));
518
+ }
519
+ lanes.style.height=`${this.lastLanesHeight}px`;
520
+ lanes.style.maxHeight=`${this.lastLanesHeight}px`;
521
+ }
522
+
523
+ setSourceLoading(){
524
+ this.sourceLoaded=false;
525
+ this.source=null;
526
+ this.sourceFallbackReason=null;
527
+ this.builder=null;
528
+ this.appliedOps=[];
529
+ this.selectedKey=null;
530
+ this.selectedKeys=[];
531
+ this.syncEffectiveInspection(false);
532
+ this.renderGateBanner();
533
+ this.renderEditorBar();
534
+ this.renderSelection();
535
+ }
536
+
537
+ exportSideState():AnimationSideState{
538
+ return {
539
+ document:this.document,
540
+ animation:this.animation,
541
+ baseInspection:this.baseInspection,
542
+ source:this.source,
543
+ sourceLoaded:this.sourceLoaded,
544
+ sourceFallbackReason:this.sourceFallbackReason,
545
+ builder:this.builder,
546
+ appliedOps:this.appliedOps.map(o=>structuredClone(o)),
547
+ selectedKey:this.selectedKey?{...this.selectedKey}:null,
548
+ selectedKeys:this.selectedKeys.map(k=>({...k})),
549
+ editorStatus:{
550
+ text:this.editorStatus.textContent??'',
551
+ error:this.editorStatus.classList.contains('error'),
552
+ },
553
+ poseMode:this.poseMode,
554
+ poseModeLockedByUser:this.poseModeLockedByUser,
555
+ zoom:this.zoom,
556
+ };
557
+ }
558
+
559
+ importSideState(state:AnimationSideState|null){
560
+ this.draggingKey=null;
561
+ this.draggingCurveHandle=null;
562
+ this.draggingStageBone=null;
563
+ this.forceNextModelReload=true;
564
+ if(!state){
565
+ this.document=null;
566
+ this.baseInspection=null;
567
+ this.inspection=null;
568
+ this.source=null;
569
+ this.sourceLoaded=false;
570
+ this.sourceFallbackReason=null;
571
+ this.builder=null;
572
+ this.appliedOps=[];
573
+ this.selectedKey=null;
574
+ this.selectedKeys=[];
575
+ this.setEditorStatus('',false);
576
+ }else{
577
+ this.document=state.document??null;
578
+ if(state.animation!==undefined)this.animation=state.animation;
579
+ this.baseInspection=state.baseInspection??null;
580
+ this.inspection=this.baseInspection;
581
+ this.source=state.source;
582
+ this.sourceLoaded=state.sourceLoaded;
583
+ this.sourceFallbackReason=state.sourceFallbackReason;
584
+ this.builder=state.builder;
585
+ this.appliedOps=state.appliedOps.map(o=>structuredClone(o));
586
+ this.selectedKey=state.selectedKey?{...state.selectedKey}:null;
587
+ this.selectedKeys=state.selectedKeys.map(k=>({...k}));
588
+ this.setEditorStatus(state.editorStatus.text,state.editorStatus.error);
589
+ this.setStagePoseMode(state.poseMode,state.poseModeLockedByUser);
590
+ this.setZoom(state.zoom);
591
+ }
592
+ this.syncEffectiveInspection(true);
593
+ this.renderGateBanner();
594
+ this.renderEditorBar();
595
+ this.renderSelection();
596
+ }
597
+
598
+ loadSource(source:AnimationSourceView|null,fallbackReason:string|null=null){
599
+ this.sourceLoaded=true;
600
+ this.source=source;
601
+ this.sourceFallbackReason=fallbackReason;
602
+ if(source?.available&&source.text){
603
+ if(!this.builder||this.builder.baseText!==source.text){
604
+ const prevOps=this.builder?[...this.builder.ops]:[...this.appliedOps];
605
+ this.builder=new AnimationOpBuilder(source.text,(source.easings??undefined) as Readonly<Record<string,EasingTuple>>|undefined);
606
+ for(const op of prevOps){
607
+ try{this.builder.apply(op);}catch{break;}
608
+ }
609
+ }
610
+ }else{
611
+ this.builder=null;
612
+ this.appliedOps=[];
613
+ this.selectedKey=null;
614
+ this.selectedKeys=[];
615
+ }
616
+ this.syncEffectiveInspection(false);
617
+ this.renderGateBanner();
618
+ this.renderEditorBar();
619
+ this.renderSelection();
620
+ }
621
+
42
622
  model(doc:unknown,animation:string){
43
- if(this.document===doc&&this.animation===animation)return;this.document=doc;this.animation=animation;this.inspection=null;this.track=null;this.unavailableChannel='';this.frame=null;this.bones.clear();this.boneButtons.clear();this.picks.replaceChildren();this.channelSelect.replaceChildren();this.playhead=null;
44
- try{this.inspection=readAnimationInspection(doc,animation);boneHierarchy(this.inspection);this.status.textContent=`${animation||'Setup'} · ${this.inspection.tracks.length} stored tracks · key times in seconds; frames require a declared clock.`;}
45
- catch(e){this.status.textContent=e instanceof Error?e.message:String(e);}
623
+ if(!this.forceNextModelReload&&this.document===doc&&this.animation===animation)return;
624
+ this.forceNextModelReload=false;
625
+ if(animation&&this.lastNonEmptyAnimation&&this.lastNonEmptyAnimation!==animation){
626
+ this.selectedKey=null;
627
+ this.selectedKeys=[];
628
+ this.setEditorStatus('',false);
629
+ }
630
+ if(animation)this.lastNonEmptyAnimation=animation;
631
+ this.document=doc;
632
+ this.animation=animation;
633
+ this.baseInspection=null;
634
+ this.inspection=null;
635
+ this.track=null;
636
+ this.unavailableChannel='';
637
+ this.frame=null;
638
+ this.bones.clear();
639
+ this.boneButtons.clear();
640
+ this.picks.replaceChildren();
641
+ this.channelSelect.replaceChildren();
642
+ this.playhead=null;
643
+ try{
644
+ this.baseInspection=readAnimationInspection(doc,animation);
645
+ boneHierarchy(this.baseInspection);
646
+ this.syncEffectiveInspection(true);
647
+ this.status.textContent=`${animation||'Setup'} · ${this.inspection!.tracks.length} stored tracks · key times in seconds; frames require a declared clock.`;
648
+ this.status.title=this.status.textContent;
649
+ }catch(e){
650
+ this.status.textContent=e instanceof Error?e.message:String(e);
651
+ this.status.title=this.status.textContent;
652
+ }
46
653
  if(this.selection.value()&&!this.has(this.selection.value()))this.selection.select(null);
47
- this.renderTree();this.renderSelection();
654
+ this.renderGateBanner();
655
+ this.renderEditorBar();
656
+ this.renderTree();
657
+ this.renderSelection();
658
+ }
659
+
660
+ private draftDocument():unknown{
661
+ if(!this.builder)return undefined;
662
+ const text=this.builder.text;
663
+ if(text===this.cachedDraftText)return this.cachedDraftDoc;
664
+ this.cachedDraftText=text;
665
+ try{this.cachedDraftDoc=JSON.parse(text);}catch{this.cachedDraftDoc=undefined;}
666
+ return this.cachedDraftDoc;
667
+ }
668
+
669
+ gateInfo():AnimationEditGate{
670
+ if(!this.animation){
671
+ return {editable:false,code:'ANIMATION_NOT_IN_SOURCE',reason:'No animation selected.',note:null};
672
+ }
673
+ if(this.animation==='idle'){
674
+ return checkAnimationEditGate('idle',this.source?.path??null);
675
+ }
676
+ const ro=typeof this.options.readOnlyReason==='function'?this.options.readOnlyReason():this.options.readOnlyReason;
677
+ if(ro||!this.options.apply||!this.options.preview){
678
+ return {
679
+ editable:false,
680
+ code:'ANIMATION_COMPARE_READ_ONLY',
681
+ reason:
682
+ ro??
683
+ 'keyed animation editing is read-only in comparison sessions until per-side animation rebuild is wired.',
684
+ note:null,
685
+ };
686
+ }
687
+ if(!this.sourceLoaded){
688
+ return {
689
+ editable:false,
690
+ code:'ANIMATION_SOURCE_LOADING',
691
+ reason:'Reading the producer handoff…',
692
+ note:null,
693
+ };
694
+ }
695
+ if(!this.source||!this.source.available||!this.source.text){
696
+ const r=this.source?.reason??this.sourceFallbackReason??'config.json does not declare an "animations_from" motion spec file.';
697
+ const clean=r.replace(/^ANIMATION_SOURCE_MISSING:\s*/,'');
698
+ return {editable:false,code:'ANIMATION_SOURCE_MISSING',reason:clean,note:null};
699
+ }
700
+ const gateKey=`${this.animation}\0${this.source.path??''}\0${this.builder?.text??''}`;
701
+ if(gateKey===this.cachedGateKey&&this.cachedGate)return this.cachedGate;
702
+ const gate=checkAnimationEditGate(this.animation,this.source.path,this.draftDocument());
703
+ this.cachedGateKey=gateKey;
704
+ this.cachedGate=gate;
705
+ return gate;
706
+ }
707
+
708
+ tracksInfo():TrackClassification[]{
709
+ const doc=this.draftDocument();
710
+ if(!doc||!this.animation)return [];
711
+ const key=`${this.animation}\0${this.builder?.text??''}`;
712
+ if(key===this.cachedTracksKey)return this.cachedTracks;
713
+ this.cachedTracksKey=key;
714
+ this.cachedTracks=classifyAnimationTracks(doc,this.animation);
715
+ return this.cachedTracks;
716
+ }
717
+
718
+ hasUnappliedPreview():boolean{
719
+ if(!this.builder)return false;
720
+ return JSON.stringify(this.builder.ops)!==JSON.stringify(this.appliedOps);
721
+ }
722
+
723
+ ops():readonly AnimationSourceOp[]{
724
+ return this.builder?this.builder.ops:[];
725
+ }
726
+
727
+ unappliedOps():readonly AnimationSourceOp[]{
728
+ const all=this.ops();
729
+ if(!this.hasUnappliedPreview())return [];
730
+ return all;
731
+ }
732
+
733
+ overlaidInspection():AnimationInspection|null{
734
+ return this.inspection;
735
+ }
736
+
737
+ sourceInfo(){
738
+ return this.source?{
739
+ available:this.source.available,
740
+ reason:this.source.reason,
741
+ path:this.source.path,
742
+ sha256:this.source.sha256,
743
+ }:null;
744
+ }
745
+
746
+ private syncEffectiveInspection(notifyPreview=true){
747
+ if(!this.baseInspection){
748
+ this.inspection=null;
749
+ if(notifyPreview)this.options.preview?.(null,false);
750
+ return;
751
+ }
752
+ const hasPreview=this.hasUnappliedPreview();
753
+ if(hasPreview&&this.builder){
754
+ try{
755
+ this.inspection=overlayDraftOnInspection(
756
+ this.baseInspection,
757
+ this.builder.text,
758
+ (this.source?.easings??undefined) as Readonly<Record<string,EasingTuple>>|undefined,
759
+ );
760
+ }catch{
761
+ this.inspection=this.baseInspection;
762
+ }
763
+ }else{
764
+ this.inspection=this.baseInspection;
765
+ }
766
+
767
+ if(this.track&&this.inspection){
768
+ this.track=this.inspection.tracks.find(t=>t.pointer===this.track!.pointer)??this.track;
769
+ }
770
+
771
+ if(notifyPreview){
772
+ if(hasPreview&&this.inspection&&this.builder){
773
+ const clss=this.tracksInfo();
774
+ const editedBones=new Set<string>();
775
+ for(const op of [...this.builder.ops,...this.appliedOps]){
776
+ if(op.animation===this.animation){
777
+ const c=clss[op.track];
778
+ if(c&&c.targetKind==='bone'&&c.target)editedBones.add(c.target);
779
+ }
780
+ }
781
+ const adjust=animationPreviewAdjust(this.inspection,editedBones,false);
782
+ this.options.preview?.(adjust,editedBones.size>0);
783
+ }else{
784
+ this.options.preview?.(null,false);
785
+ }
786
+ }
787
+ }
788
+
789
+ private renderGateBanner(){
790
+ const gate=this.gateInfo();
791
+ if(!this.animation){
792
+ this.gateBanner.textContent='Select an animation clip to inspect or edit keys.';
793
+ this.gateBanner.title=this.gateBanner.textContent;
794
+ this.gateBanner.dataset.gateCode='NONE';
795
+ this.gateBanner.dataset.editable='false';
796
+ delete this.gateBanner.dataset.loading;
797
+ return;
798
+ }
799
+ if(gate.code==='ANIMATION_SOURCE_LOADING'){
800
+ this.gateBanner.textContent=gate.reason??'Reading the producer handoff…';
801
+ this.gateBanner.title=this.gateBanner.textContent;
802
+ this.gateBanner.dataset.gateCode='LOADING';
803
+ this.gateBanner.dataset.editable='false';
804
+ this.gateBanner.dataset.loading='true';
805
+ return;
806
+ }
807
+ delete this.gateBanner.dataset.loading;
808
+ this.gateBanner.dataset.gateCode=gate.code;
809
+ this.gateBanner.dataset.editable=String(gate.editable);
810
+ if(!gate.editable){
811
+ this.gateBanner.textContent=`Read-only clip · ${gate.code}: ${gate.reason}`;
812
+ }else{
813
+ const srcPath=this.source?.path??'animations_from';
814
+ const hashShort=this.source?.sha256?` (sha256 ${this.source.sha256.slice(0,12)}…)`:'';
815
+ const notePart=gate.note?` · Note: ${gate.note}`:'';
816
+ this.gateBanner.textContent=`Editable clip "${this.animation}" from ${srcPath}${hashShort}${notePart}`;
817
+ }
818
+ this.gateBanner.title=this.gateBanner.textContent;
819
+ }
820
+
821
+ private renderEditorBar(){
822
+ const allOps=this.ops();
823
+ const hasPreview=this.hasUnappliedPreview();
824
+ const appliedCount=this.appliedOps.length;
825
+ this.previewBadge.hidden=!hasPreview;
826
+ if(hasPreview){
827
+ const clips=[...new Set([...allOps,...this.appliedOps].map(o=>o.animation))];
828
+ this.previewBadge.textContent=`preview — Apply decides (${allOps.length} op(s)${clips.length?` on ${clips.join(', ')}`:''})`;
829
+ }
830
+ if(allOps.length===0&&appliedCount===0){
831
+ this.opsSummary.textContent=`0 pending ops (cap ${MAX_ANIMATION_OPS})`;
832
+ }else if(hasPreview){
833
+ this.opsSummary.textContent=`${allOps.length} cumulative op(s) pending${appliedCount?` (${appliedCount} applied on stage)`:''} · cap ${MAX_ANIMATION_OPS}`;
834
+ }else{
835
+ this.opsSummary.textContent=`${appliedCount} op(s) applied on stage · 0 unapplied`;
836
+ }
837
+ const gate=this.gateInfo();
838
+ this.undoOpBtn.disabled=this.isBusy||!gate.editable||allOps.length===0;
839
+ this.clearOpsBtn.disabled=this.isBusy||!gate.editable||!hasPreview;
840
+ this.applyBtn.disabled=this.isBusy||!gate.editable||!hasPreview||allOps.length===0||!this.source?.available;
841
+ this.resetBtn.disabled=this.isBusy||!gate.editable||(allOps.length===0&&appliedCount===0);
842
+ }
843
+
844
+ setEditorStatus(text:string,error=false){
845
+ this.editorStatus.textContent=text;
846
+ this.editorStatus.title=text;
847
+ this.editorStatus.classList.toggle('error',error);
848
+ this.editorStatus.setAttribute('role',error?'alert':'status');
849
+ }
850
+
851
+ busy(isBusy:boolean){
852
+ this.isBusy=isBusy;
853
+ this.options.host.setAttribute('aria-busy',String(isBusy));
854
+ this.renderEditorBar();
855
+ this.syncKeyInspectorInPlace();
856
+ this.renderCurve();
857
+ }
858
+
859
+ markApplied(ops:readonly AnimationSourceOp[],statusText:string,isError=false){
860
+ this.appliedOps=ops.map(o=>structuredClone(o));
861
+ this.syncEffectiveInspection(true);
862
+ this.renderEditorBar();
863
+ this.renderTimeline();
864
+ this.renderChannels();
865
+ this.setEditorStatus(statusText,isError);
866
+ }
867
+
868
+ /**
869
+ * Reconcile the stage's currently active animation record without wiping pending edits in `this.builder`.
870
+ * When another kind of Apply (Bones, Mesh, Idle, Retarget, Chest, etc.) replaces the stage build, `applied` is `null`
871
+ * and `this.appliedOps` clears to `[]` while `this.builder.ops` stays intact as pending unapplied edits.
872
+ */
873
+ reconcileStageApplied(applied:AppliedAnimation|null){
874
+ const nextApplied=applied?applied.ops.map(o=>structuredClone(o)):[];
875
+ if(JSON.stringify(this.appliedOps)===JSON.stringify(nextApplied))return;
876
+ this.appliedOps=nextApplied;
877
+ this.syncEffectiveInspection(true);
878
+ this.renderEditorBar();
879
+ this.renderTimeline();
880
+ this.renderChannels();
881
+ }
882
+
883
+ syncApplied(applied:AppliedAnimation|null){
884
+ this.appliedOps=applied?applied.ops.map(o=>structuredClone(o)):[];
885
+ if(this.source?.available&&this.source.text){
886
+ this.builder=new AnimationOpBuilder(this.source.text,(this.source.easings??undefined) as Readonly<Record<string,EasingTuple>>|undefined);
887
+ for(const op of this.appliedOps){
888
+ try{this.builder.apply(op);}catch{break;}
889
+ }
890
+ }
891
+ this.syncEffectiveInspection(true);
892
+ this.renderEditorBar();
893
+ this.renderSelection();
894
+ }
895
+
896
+ applyOp(
897
+ op:AnimationSourceOp,
898
+ opts:{skipTimelineDomRebuild?:boolean}={},
899
+ ):{ok:true;ops:readonly AnimationSourceOp[]}|{ok:false;error:string}{
900
+ const gate=this.gateInfo();
901
+ if(!gate.editable){
902
+ const err=`${gate.code}: ${gate.reason??'animation is read-only'}`;
903
+ this.setEditorStatus(err,true);
904
+ return {ok:false,error:err};
905
+ }
906
+ if(!this.builder||!this.source?.available){
907
+ const err='ANIMATION_SOURCE_MISSING: animation source is not loaded';
908
+ this.setEditorStatus(err,true);
909
+ return {ok:false,error:err};
910
+ }
911
+ try{
912
+ this.options.pause?.();
913
+ this.builder.apply(op);
914
+ this.syncEffectiveInspection(true);
915
+ this.renderEditorBar();
916
+ if(opts.skipTimelineDomRebuild){
917
+ this.syncTimelineKeysInPlace();
918
+ this.syncKeyInspectorInPlace();
919
+ }else{
920
+ this.renderTimeline();
921
+ }
922
+ this.renderChannels();
923
+ this.setEditorStatus(`Applied ${op.op} on ${op.animation} track ${op.track} (${this.builder.ops.length} pending op(s), preview active).`,false);
924
+ return {ok:true,ops:this.builder.ops};
925
+ }catch(e){
926
+ const msg=e instanceof Error?e.message:String(e);
927
+ this.setEditorStatus(msg,true);
928
+ return {ok:false,error:msg};
929
+ }
930
+ }
931
+
932
+ setKeyTime(trackIndex:number,keyIndex:number,time:number){
933
+ return this.applyOp(
934
+ {op:'set_key_time',animation:this.animation,track:trackIndex,key:keyIndex,time},
935
+ {skipTimelineDomRebuild:true},
936
+ );
937
+ }
938
+
939
+ setKeyValue(trackIndex:number,keyIndex:number,channel:number|undefined,value:number|readonly number[]){
940
+ return this.applyOp(
941
+ channel!==undefined
942
+ ?{op:'set_key_value',animation:this.animation,track:trackIndex,key:keyIndex,channel,value:value as number}
943
+ :{op:'set_key_value',animation:this.animation,track:trackIndex,key:keyIndex,value:value as readonly number[]},
944
+ {skipTimelineDomRebuild:true},
945
+ );
946
+ }
947
+
948
+ setKeyCurve(trackIndex:number,keyIndex:number,curve:readonly number[]|'stepped'|null){
949
+ return this.applyOp(
950
+ {op:'set_key_curve',animation:this.animation,track:trackIndex,key:keyIndex,curve},
951
+ {skipTimelineDomRebuild:true},
952
+ );
953
+ }
954
+
955
+ setKeyEase(trackIndex:number,keyIndex:number,ease:string|null){
956
+ return this.applyOp(
957
+ {op:'set_key_ease',animation:this.animation,track:trackIndex,key:keyIndex,ease},
958
+ {skipTimelineDomRebuild:true},
959
+ );
960
+ }
961
+
962
+ insertKey(trackIndex:number,time:number,value?:readonly number[]){
963
+ const gate=this.gateInfo();
964
+ if(!gate.editable){
965
+ const err=`${gate.code}: ${gate.reason??'animation is read-only'}`;
966
+ this.setEditorStatus(err,true);
967
+ return {ok:false as const,error:err};
968
+ }
969
+ const clss=this.tracksInfo();
970
+ const cls=clss[trackIndex];
971
+ if(!cls||!cls.editable){
972
+ const err=cls?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`:`ANIMATION_TRACK_OUT_OF_RANGE: track ${trackIndex}`;
973
+ this.setEditorStatus(err,true);
974
+ return {ok:false as const,error:err};
975
+ }
976
+ let resolvedValue=value;
977
+ if(!resolvedValue){
978
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===cls.target&&t.name===cls.property);
979
+ const vals:number[]=[];
980
+ for(let c=0;c<cls.channels;c++){
981
+ const sampled=inspTrack?evaluateStoredChannel(inspTrack,c,time):null;
982
+ if(sampled!==null&&Number.isFinite(sampled)){
983
+ vals.push(cleanMotionNumber(sampled));
984
+ }else{
985
+ const doc=this.draftDocument() as {animations?:Record<string,{tracks?:Array<{keys?:Array<{v?:number[]}>}>}>}|undefined;
986
+ const fallback=doc?.animations?.[this.animation]?.tracks?.[trackIndex]?.keys?.[0]?.v?.[c]??0;
987
+ vals.push(cleanMotionNumber(fallback));
988
+ }
989
+ }
990
+ resolvedValue=vals;
991
+ }
992
+ const res=this.applyOp({
993
+ op:'insert_key',
994
+ animation:this.animation,
995
+ track:trackIndex,
996
+ time,
997
+ value:resolvedValue,
998
+ });
999
+ if(res.ok){
1000
+ const rawKeys=this.readDraftTrackKeys(trackIndex);
1001
+ const insertedIdx=rawKeys.findIndex(k=>k.t===cleanMotionNumber(time));
1002
+ if(insertedIdx>=0){
1003
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===cls.target&&t.name===cls.property);
1004
+ const sel={animation:this.animation,trackIndex,keyIndex:insertedIdx,pointer:inspTrack?.pointer??''};
1005
+ this.selectedKey=sel;
1006
+ this.selectedKeys=[sel];
1007
+ this.autoSyncPoseModeFromProperty(cls.property);
1008
+ this.syncTimelineKeysInPlace();
1009
+ this.syncKeyInspectorInPlace();
1010
+ }
1011
+ }
1012
+ return res;
1013
+ }
1014
+
1015
+ deleteKey(trackIndex:number,keyIndex:number){
1016
+ const res=this.applyOp({op:'delete_key',animation:this.animation,track:trackIndex,key:keyIndex});
1017
+ if(res.ok){
1018
+ const rawKeys=this.readDraftTrackKeys(trackIndex);
1019
+ if(this.selectedKey&&this.selectedKey.trackIndex===trackIndex){
1020
+ if(rawKeys.length===0){
1021
+ this.selectedKey=null;
1022
+ this.selectedKeys=[];
1023
+ }else{
1024
+ this.selectedKey={...this.selectedKey,keyIndex:Math.min(keyIndex,rawKeys.length-1)};
1025
+ this.selectedKeys=[this.selectedKey];
1026
+ }
1027
+ this.syncTimelineKeysInPlace();
1028
+ this.syncKeyInspectorInPlace();
1029
+ }
1030
+ }
1031
+ return res;
1032
+ }
1033
+
1034
+ deleteSelection(
1035
+ selections?:ReadonlyArray<{track:number;key:number}>,
1036
+ ):{ok:true;ops:readonly AnimationSourceOp[]}|{ok:false;error:string}{
1037
+ const gate=this.gateInfo();
1038
+ if(!gate.editable){
1039
+ const err=`${gate.code}: ${gate.reason??'animation is read-only'}`;
1040
+ this.setEditorStatus(err,true);
1041
+ return {ok:false,error:err};
1042
+ }
1043
+ if(!this.builder||!this.source?.available){
1044
+ const err='ANIMATION_SOURCE_MISSING: animation source is not loaded';
1045
+ this.setEditorStatus(err,true);
1046
+ return {ok:false,error:err};
1047
+ }
1048
+ const targets=
1049
+ selections??
1050
+ this.selectedKeys
1051
+ .filter(s=>s.animation===this.animation)
1052
+ .map(s=>({track:s.trackIndex,key:s.keyIndex}));
1053
+ if(targets.length===0){
1054
+ const err='ANIMATION_KEY_OUT_OF_RANGE: no keys selected to delete';
1055
+ this.setEditorStatus(err,true);
1056
+ return {ok:false,error:err};
1057
+ }
1058
+ try{
1059
+ this.options.pause?.();
1060
+ this.builder.deleteSelection(this.animation,targets);
1061
+ this.selectedKey=null;
1062
+ this.selectedKeys=[];
1063
+ this.syncEffectiveInspection(true);
1064
+ this.renderEditorBar();
1065
+ this.renderTimeline();
1066
+ this.renderChannels();
1067
+ this.setEditorStatus(`Deleted ${targets.length} selected key(s) (${this.builder.ops.length} pending op(s)).`,false);
1068
+ return {ok:true,ops:this.builder.ops};
1069
+ }catch(e){
1070
+ const msg=e instanceof Error?e.message:String(e);
1071
+ this.setEditorStatus(msg,true);
1072
+ return {ok:false,error:msg};
1073
+ }
1074
+ }
1075
+
1076
+ moveSelection(
1077
+ selections:ReadonlyArray<{track:number;key:number}>,
1078
+ deltaTime:number,
1079
+ ):{ok:true;ops:readonly AnimationSourceOp[]}|{ok:false;error:string}{
1080
+ const gate=this.gateInfo();
1081
+ if(!gate.editable){
1082
+ const err=`${gate.code}: ${gate.reason??'animation is read-only'}`;
1083
+ this.setEditorStatus(err,true);
1084
+ return {ok:false,error:err};
1085
+ }
1086
+ if(!this.builder||!this.source?.available){
1087
+ const err='ANIMATION_SOURCE_MISSING: animation source is not loaded';
1088
+ this.setEditorStatus(err,true);
1089
+ return {ok:false,error:err};
1090
+ }
1091
+ try{
1092
+ this.options.pause?.();
1093
+ this.builder.moveSelection(this.animation,selections,deltaTime);
1094
+ this.syncEffectiveInspection(true);
1095
+ this.renderEditorBar();
1096
+ this.syncTimelineKeysInPlace();
1097
+ this.syncKeyInspectorInPlace();
1098
+ this.renderChannels();
1099
+ this.setEditorStatus(`Moved ${selections.length} selected key(s) by ${deltaTime} s (${this.builder.ops.length} pending op(s)).`,false);
1100
+ return {ok:true,ops:this.builder.ops};
1101
+ }catch(e){
1102
+ const msg=e instanceof Error?e.message:String(e);
1103
+ this.setEditorStatus(msg,true);
1104
+ return {ok:false,error:msg};
1105
+ }
1106
+ }
1107
+
1108
+ undoOp():boolean{
1109
+ if(!this.builder)return false;
1110
+ const undone=this.builder.undo();
1111
+ if(!undone)return false;
1112
+ this.syncEffectiveInspection(true);
1113
+ this.renderEditorBar();
1114
+ this.renderTimeline();
1115
+ this.renderChannels();
1116
+ this.setEditorStatus(`Undid last pending op (${this.builder.ops.length} pending op(s) remaining).`,false);
1117
+ return true;
1118
+ }
1119
+
1120
+ clearPending():void{
1121
+ if(!this.builder||!this.source?.text)return;
1122
+ this.builder=new AnimationOpBuilder(this.source.text,(this.source.easings??undefined) as Readonly<Record<string,EasingTuple>>|undefined);
1123
+ for(const op of this.appliedOps){
1124
+ try{this.builder.apply(op);}catch{break;}
1125
+ }
1126
+ this.syncEffectiveInspection(true);
1127
+ this.renderEditorBar();
1128
+ this.renderTimeline();
1129
+ this.renderChannels();
1130
+ this.setEditorStatus('Discarded unapplied animation edits.',false);
1131
+ }
1132
+
1133
+ resetEdits():void{
1134
+ this.appliedOps=[];
1135
+ if(this.source?.available&&this.source.text){
1136
+ this.builder=new AnimationOpBuilder(this.source.text,(this.source.easings??undefined) as Readonly<Record<string,EasingTuple>>|undefined);
1137
+ }
1138
+ this.selectedKey=null;
1139
+ this.selectedKeys=[];
1140
+ this.syncEffectiveInspection(true);
1141
+ this.renderEditorBar();
1142
+ this.renderTimeline();
1143
+ this.renderChannels();
1144
+ this.setEditorStatus('Reset: no pending animation ops.',false);
1145
+ }
1146
+
1147
+ isKeySelected(trackIndex:number,keyIndex:number):boolean{
1148
+ if(this.selectedKeys.some(s=>s.animation===this.animation&&s.trackIndex===trackIndex&&s.keyIndex===keyIndex)){
1149
+ return true;
1150
+ }
1151
+ return (
1152
+ this.selectedKey!==null&&
1153
+ this.selectedKey.animation===this.animation&&
1154
+ this.selectedKey.trackIndex===trackIndex&&
1155
+ this.selectedKey.keyIndex===keyIndex
1156
+ );
1157
+ }
1158
+
1159
+ selectedKeysInfo():SelectedAnimationKey[]{
1160
+ const list=this.selectedKeys.filter(s=>s.animation===this.animation);
1161
+ if(list.length>0)return [...list];
1162
+ if(this.selectedKey&&this.selectedKey.animation===this.animation)return [this.selectedKey];
1163
+ return [];
1164
+ }
1165
+
1166
+ toggleKeySelection(trackIndex:number,keyIndex:number,pointerHint?:string):boolean{
1167
+ const gate=this.gateInfo();
1168
+ if(!gate.editable){
1169
+ this.setEditorStatus(`${gate.code}: ${gate.reason}`,true);
1170
+ return false;
1171
+ }
1172
+ const clss=this.tracksInfo();
1173
+ const cls=clss[trackIndex];
1174
+ if(!cls){
1175
+ this.setEditorStatus(`ANIMATION_TRACK_OUT_OF_RANGE: track ${trackIndex}`,true);
1176
+ return false;
1177
+ }
1178
+ if(!cls.editable){
1179
+ this.setEditorStatus(`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`,true);
1180
+ return false;
1181
+ }
1182
+ const rawKeys=this.readDraftTrackKeys(trackIndex);
1183
+ const k=rawKeys[keyIndex];
1184
+ if(!k){
1185
+ this.setEditorStatus(`ANIMATION_KEY_OUT_OF_RANGE: key ${keyIndex} on track ${trackIndex}`,true);
1186
+ return false;
1187
+ }
1188
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===cls.target&&t.name===cls.property)??null;
1189
+ const pointer=pointerHint??inspTrack?.pointer??'';
1190
+ const current=this.selectedKeysInfo();
1191
+ const existingIdx=current.findIndex(s=>s.trackIndex===trackIndex&&s.keyIndex===keyIndex);
1192
+ if(existingIdx>=0){
1193
+ current.splice(existingIdx,1);
1194
+ this.selectedKeys=current;
1195
+ this.selectedKey=current.at(-1)??null;
1196
+ }else{
1197
+ const entry:SelectedAnimationKey={animation:this.animation,trackIndex,keyIndex,pointer};
1198
+ current.push(entry);
1199
+ this.selectedKeys=current;
1200
+ this.selectedKey=entry;
1201
+ this.autoSyncPoseModeFromProperty(cls.property);
1202
+ }
1203
+ this.syncTimelineKeysInPlace();
1204
+ this.syncKeyInspectorInPlace();
1205
+ this.setEditorStatus(`Selected ${this.selectedKeys.length} key(s) across ${new Set(this.selectedKeys.map(s=>s.trackIndex)).size} track(s).`,false);
1206
+ return true;
1207
+ }
1208
+
1209
+ selectKeys(selections:ReadonlyArray<{track:number;key:number}>):boolean{
1210
+ const gate=this.gateInfo();
1211
+ if(!gate.editable){
1212
+ this.setEditorStatus(`${gate.code}: ${gate.reason}`,true);
1213
+ return false;
1214
+ }
1215
+ const clss=this.tracksInfo();
1216
+ const next:SelectedAnimationKey[]=[];
1217
+ const seen=new Set<string>();
1218
+ const skippedReadonly=new Set<string>();
1219
+ for(const sel of selections){
1220
+ const cls=clss[sel.track];
1221
+ if(!cls)continue;
1222
+ if(!cls.editable){
1223
+ skippedReadonly.add(`${cls.target}.${cls.property}`);
1224
+ continue;
1225
+ }
1226
+ const rawKeys=this.readDraftTrackKeys(sel.track);
1227
+ if(!rawKeys[sel.key])continue;
1228
+ const id=`${sel.track}:${sel.key}`;
1229
+ if(seen.has(id))continue;
1230
+ seen.add(id);
1231
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===cls.target&&t.name===cls.property)??null;
1232
+ next.push({animation:this.animation,trackIndex:sel.track,keyIndex:sel.key,pointer:inspTrack?.pointer??''});
1233
+ }
1234
+ this.selectedKeys=next;
1235
+ this.selectedKey=next.at(-1)??null;
1236
+ if(this.selectedKey){
1237
+ const lastCls=clss[this.selectedKey.trackIndex];
1238
+ this.autoSyncPoseModeFromProperty(lastCls?.property);
1239
+ }
1240
+ this.syncTimelineKeysInPlace();
1241
+ this.syncKeyInspectorInPlace();
1242
+ if(skippedReadonly.size>0){
1243
+ this.setEditorStatus(
1244
+ `Selected ${next.length} editable key(s); skipped read-only track(s): ${[...skippedReadonly].join(', ')} (ANIMATION_TRACK_READ_ONLY).`,
1245
+ false,
1246
+ );
1247
+ }else{
1248
+ this.setEditorStatus(`Selected ${next.length} key(s) across ${new Set(next.map(s=>s.trackIndex)).size} track(s).`,false);
1249
+ }
1250
+ return next.length>0;
1251
+ }
1252
+
1253
+ selectKey(trackIndex:number,keyIndex:number):boolean{
1254
+ const gate=this.gateInfo();
1255
+ if(!gate.editable){
1256
+ this.setEditorStatus(`${gate.code}: ${gate.reason}`,true);
1257
+ return false;
1258
+ }
1259
+ const clss=this.tracksInfo();
1260
+ const cls=clss[trackIndex];
1261
+ if(!cls){
1262
+ this.setEditorStatus(`ANIMATION_TRACK_OUT_OF_RANGE: track ${trackIndex}`,true);
1263
+ return false;
1264
+ }
1265
+ if(!cls.editable){
1266
+ this.setEditorStatus(`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`,true);
1267
+ return false;
1268
+ }
1269
+ const rawKeys=this.readDraftTrackKeys(trackIndex);
1270
+ const k=rawKeys[keyIndex];
1271
+ if(!k){
1272
+ this.setEditorStatus(`ANIMATION_KEY_OUT_OF_RANGE: key ${keyIndex} on track ${trackIndex}`,true);
1273
+ return false;
1274
+ }
1275
+ const curTarget=this.selection.value();
1276
+ if(curTarget&&(curTarget.kind!==cls.targetKind||curTarget.name!==cls.target)){
1277
+ this.selection.select(null);
1278
+ }
1279
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===cls.target&&t.name===cls.property)??null;
1280
+ const sel={animation:this.animation,trackIndex,keyIndex,pointer:inspTrack?.pointer??''};
1281
+ this.selectedKey=sel;
1282
+ this.selectedKeys=[sel];
1283
+ this.autoSyncPoseModeFromProperty(cls.property);
1284
+ if(inspTrack){
1285
+ this.track=inspTrack;
1286
+ this.channel=0;
1287
+ this.renderChannels();
1288
+ }
1289
+ if(k.t>=0&&k.t<=this.runtimeDuration){
1290
+ this.options.seek(k.t);
1291
+ }
1292
+ this.syncTimelineKeysInPlace();
1293
+ this.syncKeyInspectorInPlace();
1294
+ return true;
1295
+ }
1296
+
1297
+ selectedKeyInfo(){
1298
+ if(!this.selectedKey||this.selectedKey.animation!==this.animation)return null;
1299
+ const clss=this.tracksInfo();
1300
+ const cls=clss[this.selectedKey.trackIndex];
1301
+ if(!cls||!cls.editable)return null;
1302
+ const rawKeys=this.readDraftTrackKeys(this.selectedKey.trackIndex);
1303
+ const k=rawKeys[this.selectedKey.keyIndex];
1304
+ if(!k)return null;
1305
+ const spec=CHANNELS[cls.property]??[];
1306
+ return {
1307
+ animation:this.animation,
1308
+ trackIndex:this.selectedKey.trackIndex,
1309
+ keyIndex:this.selectedKey.keyIndex,
1310
+ bone:cls.target,
1311
+ property:cls.property,
1312
+ time:k.t,
1313
+ values:[...k.v],
1314
+ channels:spec.map((ch,idx)=>({index:idx,field:ch.field,local:ch.local,value:k.v[idx]!})),
1315
+ };
1316
+ }
1317
+
1318
+ private readDraftTrackKeys(trackIndex:number):Array<{t:number;v:number[];ease?:string;curve?:number[]|'stepped'}>{
1319
+ const doc=this.draftDocument() as {animations?:Record<string,{tracks?:Array<{keys?:Array<{t:number;v:number[];ease?:string;curve?:number[]|'stepped'}>}>}>}|undefined;
1320
+ const keys=doc?.animations?.[this.animation]?.tracks?.[trackIndex]?.keys;
1321
+ return Array.isArray(keys)?keys:[];
48
1322
  }
1323
+
49
1324
  private has(value:InspectionTarget){return !value||!!this.inspection&&(value.kind==='bone'?this.inspection.bones:this.inspection.slots).some(x=>x.name===value.name);}
50
1325
  unavailable(reason:string){this.model(null,'');this.capture(null,undefined);this.status.textContent=reason;}
51
1326
  select(value:InspectionTarget){if(this.has(value))this.selection.select(value);}
52
1327
  fromParts(slot:string|null){this.selection.select(slot?{kind:'slot',name:slot}:null);}
53
1328
  value(){return this.selection.value();}
54
1329
  show(view:string){this.view=view;for(const [id,pane]of this.panes)pane.hidden=id!==view;for(const b of this.views)b.setAttribute('aria-pressed',String(b.dataset.animationView===view));}
1330
+
55
1331
  private renderSelection(){
56
1332
  const selected=this.selection.value();this.options.host.dataset.selectedKind=selected?.kind??'';this.options.host.dataset.selectedName=selected?.name??'';
57
1333
  for(const b of this.options.host.querySelectorAll<HTMLButtonElement>('[data-tree-kind]'))b.setAttribute('aria-pressed',String(b.dataset.treeKind===selected?.kind&&b.dataset.treeName===selected?.name));
58
1334
  this.renderTimeline();this.renderChannels();this.redraw();
59
1335
  }
1336
+
60
1337
  private renderTree(){
61
1338
  const pane=this.panes.get('tree')!;pane.replaceChildren();if(!this.inspection)return;
62
1339
  pane.append(button('Whole rig',()=>this.select(null)));const root=document.createElement('ul');root.className='animation-tree';pane.append(root);const parents=new Map<string,HTMLElement>();
@@ -67,23 +1344,846 @@ export class AnimationInspectionPanel {
67
1344
  }
68
1345
  const note=document.createElement('p');note.className='hint';note.textContent='Enable Bone points to pick bones on stage. Overlapping points pick the last active bone in source order; use the tree for an exact target. Attached Parts rows highlight together.';pane.prepend(note);
69
1346
  }
1347
+
1348
+ /**
1349
+ * Fixed-height single-row Key Bar. Both the insert controls and the selected-key fields
1350
+ * always occupy the same 26px bar so selecting or editing a key produces zero layout shift.
1351
+ */
1352
+ private renderKeyInspector(host:HTMLElement){
1353
+ const box=document.createElement('div');
1354
+ box.className='animation-key-inspector';
1355
+ box.dataset.keyInspector='';
1356
+ const gate=this.gateInfo();
1357
+ const clss=this.tracksInfo();
1358
+ const editableTracks=clss.filter(c=>c.editable);
1359
+
1360
+ const addBar=document.createElement('div');
1361
+ addBar.className='animation-insert-bar';
1362
+ const trackLabel=document.createElement('label');
1363
+ trackLabel.className='animation-bar-field';
1364
+ trackLabel.textContent='Track ';
1365
+ const trackSel=document.createElement('select');
1366
+ trackSel.dataset.insertTrack='';
1367
+ trackSel.disabled=!gate.editable||editableTracks.length===0;
1368
+ if(editableTracks.length===0){
1369
+ const opt=document.createElement('option');
1370
+ opt.value='';
1371
+ opt.textContent='No editable tracks';
1372
+ trackSel.append(opt);
1373
+ }else{
1374
+ for(const c of editableTracks){
1375
+ const opt=document.createElement('option');
1376
+ opt.value=String(c.trackIndex);
1377
+ opt.textContent=`#${c.trackIndex} ${c.target} · ${c.property}`;
1378
+ if(this.selectedKey?.trackIndex===c.trackIndex)opt.selected=true;
1379
+ trackSel.append(opt);
1380
+ }
1381
+ }
1382
+ trackLabel.append(trackSel);
1383
+
1384
+ const timeLabel=document.createElement('label');
1385
+ timeLabel.className='animation-bar-field';
1386
+ timeLabel.textContent='t ';
1387
+ const timeIn=document.createElement('input');
1388
+ timeIn.type='number';
1389
+ timeIn.step='any';
1390
+ timeIn.min='0';
1391
+ timeIn.dataset.insertTime='';
1392
+ timeIn.disabled=!gate.editable||editableTracks.length===0;
1393
+ timeIn.value=String(cleanMotionNumber(this.at));
1394
+ timeLabel.append(timeIn);
1395
+
1396
+ const addBtn=button('+ Add key',()=>{
1397
+ const tIdx=Number(trackSel.value);
1398
+ const tVal=Number(timeIn.value);
1399
+ this.insertKey(tIdx,tVal);
1400
+ });
1401
+ addBtn.dataset.insertKey='';
1402
+ addBtn.disabled=!gate.editable||editableTracks.length===0;
1403
+ addBar.append(trackLabel,timeLabel,addBtn);
1404
+ box.append(addBar);
1405
+
1406
+ const detail=document.createElement('div');
1407
+ detail.className='animation-key-detail';
1408
+ detail.dataset.keyDetail='';
1409
+ const title=document.createElement('strong');
1410
+ title.className='animation-key-title';
1411
+ title.dataset.keyInspectorTitle='';
1412
+ detail.append(title);
1413
+
1414
+ const timeWrap=document.createElement('label');
1415
+ timeWrap.className='animation-bar-field';
1416
+ timeWrap.textContent='Key t (s) ';
1417
+ const timeInput=document.createElement('input');
1418
+ timeInput.type='number';
1419
+ timeInput.step='any';
1420
+ timeInput.min='0';
1421
+ timeInput.dataset.keyTimeInput='';
1422
+ timeWrap.append(timeInput);
1423
+ detail.append(timeWrap);
1424
+
1425
+ const channelsHost=document.createElement('span');
1426
+ channelsHost.className='animation-key-channels';
1427
+ channelsHost.dataset.keyChannelsHost='';
1428
+ detail.append(channelsHost);
1429
+
1430
+ const delBtn=button('Delete key',()=>{});
1431
+ delBtn.dataset.deleteKey='';
1432
+ detail.append(delBtn);
1433
+
1434
+ const hint=document.createElement('span');
1435
+ hint.className='hint animation-key-empty';
1436
+ hint.dataset.keyInspectorEmpty='';
1437
+ detail.append(hint);
1438
+
1439
+ box.append(detail);
1440
+ host.append(box);
1441
+ this.syncKeyInspectorInPlace();
1442
+ }
1443
+
1444
+ private syncKeyInspectorInPlace(){
1445
+ const box=this.options.host.querySelector<HTMLElement>('[data-key-inspector]');
1446
+ if(!box)return;
1447
+ const gate=this.gateInfo();
1448
+ const info=this.selectedKeyInfo();
1449
+ const multi=this.selectedKeysInfo();
1450
+
1451
+ const trackSel=box.querySelector<HTMLSelectElement>('[data-insert-track]');
1452
+ if(trackSel&&info){
1453
+ for(const opt of trackSel.options){
1454
+ opt.selected=opt.value===String(info.trackIndex);
1455
+ }
1456
+ }
1457
+
1458
+ const title=box.querySelector<HTMLElement>('[data-key-inspector-title]');
1459
+ const timeInput=box.querySelector<HTMLInputElement>('[data-key-time-input]');
1460
+ const channelsHost=box.querySelector<HTMLElement>('[data-key-channels-host]');
1461
+ const delBtn=box.querySelector<HTMLButtonElement>('[data-delete-key]');
1462
+ const emptyHint=box.querySelector<HTMLElement>('[data-key-inspector-empty]');
1463
+
1464
+ if(!info){
1465
+ const hideInputs=!gate.editable;
1466
+ if(title){
1467
+ title.hidden=hideInputs;
1468
+ title.textContent='No key selected';
1469
+ title.title='';
1470
+ }
1471
+ if(timeInput){
1472
+ timeInput.disabled=true;
1473
+ if(timeInput.parentElement)timeInput.parentElement.hidden=hideInputs;
1474
+ if(document.activeElement!==timeInput)timeInput.value='';
1475
+ timeInput.onchange=null;
1476
+ }
1477
+ if(channelsHost){
1478
+ channelsHost.hidden=hideInputs;
1479
+ const existing=channelsHost.querySelectorAll<HTMLInputElement>('[data-key-channel]');
1480
+ if(existing.length!==1||!existing[0]!.disabled){
1481
+ const chWrap=document.createElement('label');
1482
+ chWrap.className='animation-bar-field';
1483
+ chWrap.textContent='val ';
1484
+ const chInput=document.createElement('input');
1485
+ chInput.type='number';
1486
+ chInput.step='any';
1487
+ chInput.dataset.keyChannel='0';
1488
+ chInput.disabled=true;
1489
+ chInput.value='';
1490
+ chWrap.append(chInput);
1491
+ channelsHost.replaceChildren(chWrap);
1492
+ }
1493
+ }
1494
+ if(delBtn){
1495
+ delBtn.hidden=hideInputs;
1496
+ delBtn.disabled=true;
1497
+ delBtn.textContent='Delete key';
1498
+ delBtn.onclick=null;
1499
+ }
1500
+ if(emptyHint){
1501
+ emptyHint.hidden=gate.editable;
1502
+ emptyHint.textContent=gate.editable
1503
+ ?''
1504
+ :`Key editing disabled (${gate.code})`;
1505
+ emptyHint.title=gate.editable?'':`${gate.code}: ${gate.reason}`;
1506
+ }
1507
+ return;
1508
+ }
1509
+
1510
+ if(title){
1511
+ title.hidden=false;
1512
+ if(multi.length>1){
1513
+ const trackCount=new Set(multi.map(s=>s.trackIndex)).size;
1514
+ title.textContent=`${multi.length} keys selected (${trackCount} track${trackCount===1?'':'s'})`;
1515
+ title.title=`${multi.length} keys selected (${trackCount} track(s)) · anchor ${info.bone} · ${info.property} #${info.keyIndex}`;
1516
+ }else{
1517
+ title.textContent=`${info.bone} · ${info.property} · key #${info.keyIndex} (track #${info.trackIndex})`;
1518
+ title.title=title.textContent;
1519
+ }
1520
+ }
1521
+ if(timeInput){
1522
+ if(timeInput.parentElement)timeInput.parentElement.hidden=false;
1523
+ timeInput.disabled=this.isBusy;
1524
+ if(document.activeElement!==timeInput)timeInput.value=String(cleanMotionNumber(info.time));
1525
+ timeInput.onchange=()=>{
1526
+ const nextT=Number(timeInput.value);
1527
+ if(multi.length>1){
1528
+ const delta=cleanMotionNumber(nextT-info.time);
1529
+ this.moveSelection(multi.map(s=>({track:s.trackIndex,key:s.keyIndex})),delta);
1530
+ }else{
1531
+ this.setKeyTime(info.trackIndex,info.keyIndex,nextT);
1532
+ }
1533
+ };
1534
+ }
1535
+ if(channelsHost){
1536
+ channelsHost.hidden=multi.length>1;
1537
+ const existing=channelsHost.querySelectorAll<HTMLInputElement>('[data-key-channel]');
1538
+ const sameShape=
1539
+ existing.length===info.channels.length&&
1540
+ info.channels.every((ch,idx)=>existing[idx]?.dataset.channelLocal===ch.local&&existing[idx]?.dataset.channelField===ch.field);
1541
+ if(sameShape){
1542
+ info.channels.forEach((ch,idx)=>{
1543
+ const chIn=existing[idx]!;
1544
+ chIn.disabled=this.isBusy;
1545
+ if(document.activeElement!==chIn)chIn.value=String(ch.value);
1546
+ chIn.onchange=()=>{
1547
+ const nextV=Number(chIn.value);
1548
+ this.setKeyValue(info.trackIndex,info.keyIndex,ch.index,nextV);
1549
+ };
1550
+ });
1551
+ }else{
1552
+ const nodes:HTMLElement[]=[];
1553
+ for(const ch of info.channels){
1554
+ const chWrap=document.createElement('label');
1555
+ chWrap.className='animation-bar-field';
1556
+ chWrap.textContent=`${ch.local} (${ch.field}) `;
1557
+ const chInput=document.createElement('input');
1558
+ chInput.type='number';
1559
+ chInput.step='any';
1560
+ chInput.disabled=this.isBusy;
1561
+ chInput.dataset.keyChannel=String(ch.index);
1562
+ chInput.dataset.channelLocal=ch.local;
1563
+ chInput.dataset.channelField=ch.field;
1564
+ chInput.value=String(ch.value);
1565
+ chInput.onchange=()=>{
1566
+ const nextV=Number(chInput.value);
1567
+ this.setKeyValue(info.trackIndex,info.keyIndex,ch.index,nextV);
1568
+ };
1569
+ chWrap.append(chInput);
1570
+ nodes.push(chWrap);
1571
+ }
1572
+ channelsHost.replaceChildren(...nodes);
1573
+ }
1574
+ }
1575
+ if(delBtn){
1576
+ delBtn.hidden=false;
1577
+ delBtn.disabled=this.isBusy;
1578
+ delBtn.textContent=multi.length>1?`Delete ${multi.length} keys`:'Delete key';
1579
+ delBtn.onclick=()=>{
1580
+ if(multi.length>1){
1581
+ this.deleteSelection();
1582
+ }else{
1583
+ this.deleteKey(info.trackIndex,info.keyIndex);
1584
+ }
1585
+ };
1586
+ }
1587
+ if(emptyHint){
1588
+ emptyHint.hidden=true;
1589
+ emptyHint.textContent='';
1590
+ }
1591
+ }
1592
+
1593
+ private effectiveEnd():number{
1594
+ return Math.max(
1595
+ this.runtimeDuration,
1596
+ ...(this.inspection?.tracks??[]).map(t=>t.keys.at(-1)?.time??0),
1597
+ Number.MIN_VALUE,
1598
+ );
1599
+ }
1600
+
1601
+ private syncRulerInPlace(end:number){
1602
+ const cleanEnd=formatSeconds(end);
1603
+ const axis=this.options.host.querySelector<HTMLElement>('.animation-axis');
1604
+ if(axis)axis.textContent=`0 s → ${cleanEnd} s`;
1605
+ const rulerTrack=this.options.host.querySelector<HTMLElement>('[data-animation-ruler-track]');
1606
+ if(!rulerTrack)return;
1607
+ for(const oldTick of [...rulerTrack.querySelectorAll('.animation-ruler-tick')])oldTick.remove();
1608
+ const playhead=rulerTrack.querySelector('[data-playhead]');
1609
+ for(const tickTime of buildRulerTicks(end,this.zoom)){
1610
+ const tick=document.createElement('span');
1611
+ tick.className='animation-ruler-tick';
1612
+ tick.dataset.rulerTick=formatSeconds(tickTime);
1613
+ tick.style.left=`${Math.max(0,Math.min(100,tickTime/end*100))}%`;
1614
+ tick.textContent=`${formatSeconds(tickTime)} s`;
1615
+ rulerTrack.append(tick);
1616
+ }
1617
+ if(playhead)rulerTrack.append(playhead);
1618
+ }
1619
+
1620
+ private syncTimelineKeysInPlace(){
1621
+ if(!this.inspection)return;
1622
+ const end=this.effectiveEnd();
1623
+ this.syncRulerInPlace(end);
1624
+ const marks=this.options.host.querySelectorAll<HTMLButtonElement>('.animation-key');
1625
+ for(const mark of marks){
1626
+ const ptr=mark.dataset.track;
1627
+ const track=ptr?this.inspection.tracks.find(t=>t.pointer===ptr):undefined;
1628
+ const kIdx=Number(mark.dataset.keyIndex);
1629
+ const srcTrack=mark.dataset.sourceTrack!==undefined?Number(mark.dataset.sourceTrack):undefined;
1630
+ const isEditable=mark.dataset.editable==='true';
1631
+ const isSelected=isEditable&&srcTrack!==undefined&&this.isKeySelected(srcTrack,kIdx);
1632
+ mark.classList.toggle('selected',isSelected);
1633
+ mark.setAttribute('aria-pressed',String(isSelected));
1634
+ if(track&&track.keys[kIdx]){
1635
+ const key=track.keys[kIdx]!;
1636
+ const cleanT=formatSeconds(key.time);
1637
+ mark.dataset.keyTime=cleanT;
1638
+ mark.style.left=`${Math.max(0,Math.min(100,key.time/end*100))}%`;
1639
+ mark.title=`${track.target} · ${track.name} · key ${kIdx} · ${cleanT} s${isEditable?' (drag to retime)':' (read-only)'}`;
1640
+ mark.setAttribute('aria-label',mark.title);
1641
+ }
1642
+ }
1643
+ this.placePlayheads();
1644
+ }
1645
+
70
1646
  private renderTimeline(){
71
- const pane=this.panes.get('timeline')!;pane.replaceChildren();this.playhead=null;if(!this.inspection)return;
72
- const tracks=filterTracks(this.inspection,this.selection.value()),end=Math.max(this.runtimeDuration,...this.inspection.tracks.map(t=>t.keys.at(-1)?.time??0),Number.MIN_VALUE);
73
- const list=document.createElement('div');list.className='animation-lanes';pane.append(list);
74
- const axis=document.createElement('div');axis.className='animation-axis';axis.textContent=`0 s → ${end} s`;list.append(axis);
75
- for(const kind of ['bone','slot']){
76
- const group=document.createElement('h4');group.textContent=kind==='bone'?'Bones':'Slots';list.append(group);
1647
+ const pane=this.panes.get('timeline')!;
1648
+ const prevLanes=pane.querySelector<HTMLElement>('.animation-lanes');
1649
+ const prevScrollTop=prevLanes?.scrollTop??0;
1650
+ const prevScrollLeft=prevLanes?.scrollLeft??0;
1651
+ pane.replaceChildren();
1652
+ this.playhead=null;
1653
+ if(!this.inspection)return;
1654
+ this.renderKeyInspector(pane);
1655
+
1656
+ const gate=this.gateInfo();
1657
+ const clss=this.tracksInfo();
1658
+ const clsByBoneProp=new Map<string,TrackClassification>();
1659
+ for(const c of clss){
1660
+ if(c.targetKind==='bone')clsByBoneProp.set(`${c.target}\0${c.property}`,c);
1661
+ }
1662
+
1663
+ const tracks=filterTracks(this.inspection,this.selection.value());
1664
+ const end=this.effectiveEnd();
1665
+ const cleanEnd=formatSeconds(end);
1666
+ const rowWidth=this.zoom>1?`calc(190px + (100% - 190px) * ${this.zoom})`:'100%';
1667
+
1668
+ const list=document.createElement('div');
1669
+ list.className='animation-lanes';
1670
+ list.dataset.animationLanes='';
1671
+ pane.append(list);
1672
+ this.bindLaneBoxSelection(list);
1673
+
1674
+ // Sticky top time ruler with ticks and scrub support
1675
+ const ruler=document.createElement('div');
1676
+ ruler.className='animation-ruler';
1677
+ ruler.dataset.animationRuler='';
1678
+ ruler.style.width=rowWidth;
1679
+ const rulerCorner=document.createElement('div');
1680
+ rulerCorner.className='animation-ruler-corner';
1681
+ const axis=document.createElement('div');
1682
+ axis.className='animation-axis';
1683
+ axis.textContent=`0 s → ${cleanEnd} s`;
1684
+ rulerCorner.append(axis);
1685
+
1686
+ const rulerTrack=document.createElement('div');
1687
+ rulerTrack.className='animation-ruler-track';
1688
+ rulerTrack.dataset.animationRulerTrack='';
1689
+ for(const tickTime of buildRulerTicks(end,this.zoom)){
1690
+ const tick=document.createElement('span');
1691
+ tick.className='animation-ruler-tick';
1692
+ tick.dataset.rulerTick=formatSeconds(tickTime);
1693
+ tick.style.left=`${Math.max(0,Math.min(100,tickTime/end*100))}%`;
1694
+ tick.textContent=`${formatSeconds(tickTime)} s`;
1695
+ rulerTrack.append(tick);
1696
+ }
1697
+ const rulerPlayhead=document.createElement('span');
1698
+ rulerPlayhead.className='animation-playhead';
1699
+ rulerPlayhead.dataset.playhead='';
1700
+ rulerTrack.append(rulerPlayhead);
1701
+ this.bindRulerScrub(rulerTrack);
1702
+ ruler.append(rulerCorner,rulerTrack);
1703
+ list.append(ruler);
1704
+
1705
+ const matchedSourceIndices=new Set<number>();
1706
+
1707
+ for(const kind of ['bone','slot'] as const){
77
1708
  for(const track of tracks.filter(t=>t.kind===kind)){
78
- const row=document.createElement('div');row.className='animation-lane';row.dataset.track=track.pointer;
79
- const label=button(`${track.target} · ${track.name}`,()=>{this.track=track;this.channel=0;this.renderChannels();this.show('curve');});label.className='animation-lane-label';row.append(label);
80
- const marks=document.createElement('div');marks.className='animation-key-lane';marks.dataset.track=track.pointer;row.append(marks);
81
- track.keys.forEach((key,index)=>{const mark=button('◆',()=>{this.track=track;this.channel=0;this.renderChannels();this.options.seek(key.time);});mark.className='animation-key';Object.assign(mark.dataset,{targetKind:kind,target:track.target,timeline:track.name,keyIndex:String(index),keyTime:String(key.time)});mark.style.left=`${key.time/end*100}%`;mark.title=`${track.target} · ${track.name} · key ${index} · ${key.time} s`;mark.setAttribute('aria-label',mark.title);marks.append(mark);});
82
- const line=document.createElement('span');line.className='animation-playhead';line.dataset.playhead='';marks.append(line);list.append(row);
1709
+ const trackPointer=track.pointer;
1710
+ const cls=kind==='bone'?clsByBoneProp.get(`${track.target}\0${track.name}`):clss.find(c=>c.targetKind==='slot'&&c.target===track.target&&c.property===track.name);
1711
+ if(cls)matchedSourceIndices.add(cls.trackIndex);
1712
+ const isEditable=gate.editable&&!!cls?.editable;
1713
+ const readonlyReason=!gate.editable
1714
+ ?`${gate.code}: ${gate.reason}`
1715
+ :cls&&!cls.editable
1716
+ ?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`
1717
+ :kind==='slot'
1718
+ ?`ANIMATION_TRACK_READ_ONLY: slot track "${track.target}.${track.name}" is read-only in v1`
1719
+ :`ANIMATION_TRACK_READ_ONLY: bone track "${track.target}.${track.name}" is not an editable source track in ${this.source?.path??'animations_from'}`;
1720
+
1721
+ const row=document.createElement('div');
1722
+ row.className='animation-lane';
1723
+ row.style.width=rowWidth;
1724
+ row.dataset.track=trackPointer;
1725
+ row.dataset.editable=String(isEditable);
1726
+ if(cls!==undefined)row.dataset.sourceTrack=String(cls.trackIndex);
1727
+ if(!isEditable)row.dataset.readonlyReason=readonlyReason;
1728
+
1729
+ const head=document.createElement('div');
1730
+ head.className='animation-lane-head';
1731
+ head.dataset.laneHead='';
1732
+
1733
+ const label=button(`${track.target} · ${track.name}`,()=>{
1734
+ const liveTrack=this.inspection?.tracks.find(t=>t.pointer===trackPointer)??track;
1735
+ this.track=liveTrack;this.channel=0;this.autoSyncPoseModeFromProperty(track.name);this.renderChannels();this.show('curve');
1736
+ });
1737
+ label.className='animation-lane-label';
1738
+ label.title=`${track.target} · ${track.name}`;
1739
+ head.append(label);
1740
+
1741
+ if(isEditable&&cls){
1742
+ const addKeyBtn=button('+ Key',()=>{
1743
+ this.insertKey(cls.trackIndex,this.at);
1744
+ });
1745
+ addKeyBtn.className='animation-lane-add';
1746
+ addKeyBtn.dataset.addKeyTrack=String(cls.trackIndex);
1747
+ addKeyBtn.title=`Insert key on ${track.target} · ${track.name} at playhead (${formatSeconds(this.at)} s)`;
1748
+ head.append(addKeyBtn);
1749
+ }
1750
+ row.append(head);
1751
+
1752
+ const marks=document.createElement('div');
1753
+ marks.className='animation-key-lane';
1754
+ marks.dataset.track=trackPointer;
1755
+ if(!isEditable){
1756
+ marks.onclick=e=>{if(e.target===marks)this.setEditorStatus(readonlyReason,true);};
1757
+ }
1758
+ if(!isEditable&&track.keys.length===0){
1759
+ const badge=document.createElement('span');
1760
+ badge.className='animation-readonly-badge';
1761
+ badge.dataset.readonlyBadge='';
1762
+ badge.textContent=readonlyReason;
1763
+ badge.title=readonlyReason;
1764
+ marks.append(badge);
1765
+ }
1766
+ row.append(marks);
1767
+
1768
+ track.keys.forEach((key,index)=>{
1769
+ const cleanT=formatSeconds(key.time);
1770
+ const mark=button('◆',e=>{
1771
+ if(this.suppressNextKeyClick||(isEditable&&cls&&(e?.detail??0)>0)){
1772
+ this.suppressNextKeyClick=false;
1773
+ return;
1774
+ }
1775
+ const liveTrack=this.inspection?.tracks.find(t=>t.pointer===trackPointer)??track;
1776
+ const liveIdx=Number(mark.dataset.keyIndex??index);
1777
+ const liveKey=liveTrack.keys[liveIdx]??key;
1778
+ this.track=liveTrack;this.channel=0;this.renderChannels();
1779
+ if(isEditable&&cls){
1780
+ if(e?.shiftKey){
1781
+ this.toggleKeySelection(cls.trackIndex,liveIdx,trackPointer);
1782
+ }else{
1783
+ const sel={animation:this.animation,trackIndex:cls.trackIndex,keyIndex:liveIdx,pointer:trackPointer};
1784
+ this.selectedKey=sel;
1785
+ this.selectedKeys=[sel];
1786
+ this.autoSyncPoseModeFromProperty(cls.property);
1787
+ this.syncTimelineKeysInPlace();
1788
+ this.syncKeyInspectorInPlace();
1789
+ }
1790
+ }else{
1791
+ this.setEditorStatus(readonlyReason,true);
1792
+ }
1793
+ if(liveKey.time>=0&&liveKey.time<=this.runtimeDuration){
1794
+ this.options.seek(liveKey.time);
1795
+ }
1796
+ });
1797
+ mark.className='animation-key';
1798
+ const isSelected=isEditable&&cls!==undefined&&this.isKeySelected(cls.trackIndex,index);
1799
+ if(isSelected)mark.classList.add('selected');
1800
+ mark.setAttribute('aria-pressed',String(isSelected));
1801
+ Object.assign(mark.dataset,{
1802
+ track:trackPointer,
1803
+ targetKind:kind,
1804
+ target:track.target,
1805
+ timeline:track.name,
1806
+ keyIndex:String(index),
1807
+ keyTime:cleanT,
1808
+ editable:String(isEditable),
1809
+ ...(cls!==undefined?{sourceTrack:String(cls.trackIndex)}:{}),
1810
+ });
1811
+ mark.style.left=`${Math.max(0,Math.min(100,key.time/end*100))}%`;
1812
+ mark.title=`${track.target} · ${track.name} · key ${index} · ${cleanT} s${isEditable?' (drag to retime)':' (read-only)'}`;
1813
+ mark.setAttribute('aria-label',mark.title);
1814
+
1815
+ if(isEditable&&cls){
1816
+ this.bindKeyDrag(mark,marks,cls.trackIndex,index,trackPointer);
1817
+ }
1818
+ marks.append(mark);
1819
+ });
1820
+
1821
+ const line=document.createElement('span');
1822
+ line.className='animation-playhead';
1823
+ line.dataset.playhead='';
1824
+ marks.append(line);
1825
+ if(gate.editable&&!isEditable&&track.keys.length>0){
1826
+ row.classList.add('has-readonly-note');
1827
+ const badge=document.createElement('div');
1828
+ badge.className='animation-readonly-badge animation-readonly-subrow';
1829
+ badge.dataset.readonlyBadge='';
1830
+ badge.textContent=readonlyReason;
1831
+ badge.title=readonlyReason;
1832
+ row.append(badge);
1833
+ }
1834
+ list.append(row);
83
1835
  }
84
1836
  }
85
- if(!tracks.length){const empty=document.createElement('p');empty.textContent='No stored tracks for this selection.';list.append(empty);}this.placePlayheads();
1837
+
1838
+ // Render any additional read-only source tracks from animations_from (e.g. physics, group, path, slider, bone.inherit)
1839
+ const selectedTarget=this.selection.value();
1840
+ const extraReadonly=clss.filter(c=>{
1841
+ if(matchedSourceIndices.has(c.trackIndex))return false;
1842
+ if(!selectedTarget)return true;
1843
+ if(selectedTarget.kind==='bone'&&c.targetKind==='bone'&&c.target===selectedTarget.name)return true;
1844
+ if(selectedTarget.kind==='slot'&&c.targetKind==='slot'&&c.target===selectedTarget.name)return true;
1845
+ return false;
1846
+ });
1847
+ for(const c of extraReadonly){
1848
+ const reason=gate.editable?`ANIMATION_TRACK_READ_ONLY: ${c.reason}`:`${gate.code}: ${gate.reason}`;
1849
+ const row=document.createElement('div');
1850
+ row.className='animation-readonly-lane';
1851
+ row.style.width=rowWidth;
1852
+ row.dataset.sourceTrack=String(c.trackIndex);
1853
+ row.dataset.targetKind=c.targetKind;
1854
+ row.dataset.target=c.target;
1855
+ row.dataset.property=c.property;
1856
+ row.dataset.editable='false';
1857
+ row.dataset.readonlyReason=reason;
1858
+
1859
+ const head=document.createElement('div');
1860
+ head.className='animation-lane-head';
1861
+ head.dataset.laneHead='';
1862
+ const lbl=document.createElement('span');
1863
+ lbl.className='animation-lane-label';
1864
+ lbl.textContent=`${c.targetKind}:${c.target} · ${c.property}`;
1865
+ lbl.title=lbl.textContent;
1866
+ head.append(lbl);
1867
+
1868
+ const trackArea=document.createElement('div');
1869
+ trackArea.className='animation-key-lane readonly-lane-track';
1870
+ const badge=document.createElement('span');
1871
+ badge.className='animation-readonly-badge';
1872
+ badge.dataset.readonlyBadge='';
1873
+ badge.textContent=reason;
1874
+ badge.title=reason;
1875
+ const line=document.createElement('span');
1876
+ line.className='animation-playhead';
1877
+ line.dataset.playhead='';
1878
+ trackArea.append(badge,line);
1879
+
1880
+ row.append(head,trackArea);
1881
+ list.append(row);
1882
+ }
1883
+
1884
+ if(!tracks.length&&!extraReadonly.length){
1885
+ const empty=document.createElement('p');
1886
+ empty.textContent='No stored tracks for this selection.';
1887
+ list.append(empty);
1888
+ }
1889
+ this.syncDockHeight(false);
1890
+ this.placePlayheads();
1891
+ if(prevScrollTop>0)list.scrollTop=prevScrollTop;
1892
+ if(prevScrollLeft>0)list.scrollLeft=prevScrollLeft;
1893
+ }
1894
+
1895
+ /**
1896
+ * Box-drag selection (>= 3 px) across `.animation-lanes` / `.animation-key-lane`,
1897
+ * while a plain click (< 3 px) on an empty editable `.animation-key-lane` seeks the playhead.
1898
+ * Playhead scrub remains on `.animation-ruler-track`.
1899
+ */
1900
+ private bindLaneBoxSelection(list:HTMLElement){
1901
+ let activeBox:{
1902
+ pointerId:number;
1903
+ startX:number;
1904
+ startY:number;
1905
+ shiftKey:boolean;
1906
+ baseSelection:SelectedAnimationKey[];
1907
+ clickedLane:HTMLElement|null;
1908
+ clickedRow:HTMLElement|null;
1909
+ moved:boolean;
1910
+ boxEl:HTMLElement|null;
1911
+ }|null=null;
1912
+
1913
+ list.addEventListener('pointerdown',e=>{
1914
+ if(!e.isPrimary||e.button!==0||this.isBusy)return;
1915
+ const rawTarget=e.target as (Element&{dataset?:DOMStringMap;className?:string})|null;
1916
+ const hitInteractive=rawTarget?.closest?.('button,input,select,textarea,[data-animation-ruler],[data-lane-head]');
1917
+ if(hitInteractive)return;
1918
+ const clickedLane=rawTarget?.closest?.<HTMLElement>('.animation-key-lane')??(rawTarget?.className?.includes('animation-key-lane')?rawTarget as unknown as HTMLElement:null);
1919
+ const clickedRow=rawTarget?.closest?.<HTMLElement>('.animation-lane,.animation-readonly-lane')??(clickedLane?.parentElement as HTMLElement|null)??null;
1920
+ e.preventDefault();
1921
+ if(typeof window!=='undefined'&&typeof window.getSelection==='function'){
1922
+ window.getSelection()?.removeAllRanges?.();
1923
+ }
1924
+ activeBox={
1925
+ pointerId:e.pointerId,
1926
+ startX:e.clientX,
1927
+ startY:e.clientY,
1928
+ shiftKey:e.shiftKey,
1929
+ baseSelection:e.shiftKey?this.selectedKeysInfo():[],
1930
+ clickedLane,
1931
+ clickedRow,
1932
+ moved:false,
1933
+ boxEl:null,
1934
+ };
1935
+ list.setPointerCapture?.(e.pointerId);
1936
+ });
1937
+
1938
+ list.addEventListener('pointermove',e=>{
1939
+ if(!activeBox||activeBox.pointerId!==e.pointerId)return;
1940
+ const dist=Math.hypot(e.clientX-activeBox.startX,e.clientY-activeBox.startY);
1941
+ if(!activeBox.moved&&dist<3)return;
1942
+ activeBox.moved=true;
1943
+ e.preventDefault();
1944
+ if(typeof window!=='undefined'&&typeof window.getSelection==='function'){
1945
+ window.getSelection()?.removeAllRanges?.();
1946
+ }
1947
+ const listRect=list.getBoundingClientRect();
1948
+ const minX=Math.min(activeBox.startX,e.clientX);
1949
+ const maxX=Math.max(activeBox.startX,e.clientX);
1950
+ const minY=Math.min(activeBox.startY,e.clientY);
1951
+ const maxY=Math.max(activeBox.startY,e.clientY);
1952
+
1953
+ if(!activeBox.boxEl){
1954
+ const boxEl=document.createElement('div');
1955
+ boxEl.className='animation-selection-box';
1956
+ boxEl.dataset.selectionBox='';
1957
+ list.append(boxEl);
1958
+ activeBox.boxEl=boxEl;
1959
+ }
1960
+ activeBox.boxEl.style.left=`${minX-listRect.left+(list.scrollLeft||0)}px`;
1961
+ activeBox.boxEl.style.top=`${minY-listRect.top+(list.scrollTop||0)}px`;
1962
+ activeBox.boxEl.style.width=`${maxX-minX}px`;
1963
+ activeBox.boxEl.style.height=`${maxY-minY}px`;
1964
+
1965
+ const merged=new Map<string,SelectedAnimationKey>();
1966
+ for(const s of activeBox.baseSelection){
1967
+ merged.set(`${s.trackIndex}:${s.keyIndex}`,s);
1968
+ }
1969
+ const skippedReadonly=new Set<string>();
1970
+ const allMarks=list.querySelectorAll<HTMLButtonElement>('.animation-key');
1971
+ for(const mark of allMarks){
1972
+ const r=mark.getBoundingClientRect();
1973
+ const cx=(r.left+r.right)/2;
1974
+ const cy=(r.top+r.bottom)/2;
1975
+ const intersects=r.right>=minX&&r.left<=maxX&&r.bottom>=minY&&r.top<=maxY&&(cx>=minX-4&&cx<=maxX+4&&cy>=minY-4&&cy<=maxY+4);
1976
+ if(!intersects)continue;
1977
+ if(mark.dataset.editable==='true'&&mark.dataset.sourceTrack!==undefined){
1978
+ const tr=Number(mark.dataset.sourceTrack);
1979
+ const kIdx=Number(mark.dataset.keyIndex);
1980
+ merged.set(`${tr}:${kIdx}`,{
1981
+ animation:this.animation,
1982
+ trackIndex:tr,
1983
+ keyIndex:kIdx,
1984
+ pointer:mark.dataset.track??'',
1985
+ });
1986
+ }else{
1987
+ skippedReadonly.add(`${mark.dataset.target??''}.${mark.dataset.timeline??''}`);
1988
+ }
1989
+ }
1990
+ this.selectedKeys=[...merged.values()];
1991
+ this.selectedKey=this.selectedKeys.at(-1)??null;
1992
+ this.syncTimelineKeysInPlace();
1993
+ this.syncKeyInspectorInPlace();
1994
+ if(skippedReadonly.size>0){
1995
+ this.setEditorStatus(
1996
+ `Selected ${this.selectedKeys.length} editable key(s); skipped read-only track(s): ${[...skippedReadonly].join(', ')} (ANIMATION_TRACK_READ_ONLY).`,
1997
+ false,
1998
+ );
1999
+ }else{
2000
+ this.setEditorStatus(
2001
+ `Selected ${this.selectedKeys.length} key(s) across ${new Set(this.selectedKeys.map(s=>s.trackIndex)).size} track(s).`,
2002
+ false,
2003
+ );
2004
+ }
2005
+ });
2006
+
2007
+ const endBox=(e:PointerEvent)=>{
2008
+ if(!activeBox||activeBox.pointerId!==e.pointerId)return;
2009
+ const box=activeBox;
2010
+ activeBox=null;
2011
+ if(list.hasPointerCapture?.(e.pointerId))list.releasePointerCapture(e.pointerId);
2012
+ if(box.boxEl)box.boxEl.remove();
2013
+ if(!box.moved&&box.clickedLane){
2014
+ const rowEditable=box.clickedRow?.dataset.editable==='true';
2015
+ const roReason=box.clickedRow?.dataset.readonlyReason;
2016
+ if(!rowEditable&&roReason){
2017
+ this.setEditorStatus(roReason,true);
2018
+ return;
2019
+ }
2020
+ if(rowEditable){
2021
+ if(!box.shiftKey){
2022
+ this.selectedKey=null;
2023
+ this.selectedKeys=[];
2024
+ this.syncTimelineKeysInPlace();
2025
+ this.syncKeyInspectorInPlace();
2026
+ }
2027
+ const rect=box.clickedLane.getBoundingClientRect();
2028
+ if(rect.width>0){
2029
+ const end=this.effectiveEnd();
2030
+ const ratio=Math.max(0,Math.min(1,(e.clientX-rect.left)/rect.width));
2031
+ const rawTime=cleanMotionNumber(ratio*end);
2032
+ this.at=rawTime;
2033
+ this.placePlayheads();
2034
+ const maxSeek=this.runtimeDuration>0?Math.min(end,this.runtimeDuration):end;
2035
+ this.options.seek(cleanMotionNumber(Math.min(maxSeek,rawTime)));
2036
+ }
2037
+ }
2038
+ }
2039
+ };
2040
+ list.addEventListener('pointerup',endBox);
2041
+ list.addEventListener('pointercancel',endBox);
86
2042
  }
2043
+
2044
+ private bindRulerScrub(rulerTrack:HTMLElement){
2045
+ let scrubbingId:number|null=null;
2046
+ const scrubAt=(clientX:number)=>{
2047
+ const rect=rulerTrack.getBoundingClientRect();
2048
+ if(rect.width<=0)return;
2049
+ const end=this.effectiveEnd();
2050
+ const ratio=Math.max(0,Math.min(1,(clientX-rect.left)/rect.width));
2051
+ const rawTime=cleanMotionNumber(ratio*end);
2052
+ this.at=rawTime;
2053
+ this.placePlayheads();
2054
+ const maxSeek=this.runtimeDuration>0?Math.min(end,this.runtimeDuration):end;
2055
+ const target=cleanMotionNumber(Math.min(maxSeek,rawTime));
2056
+ this.options.seek(target);
2057
+ };
2058
+ rulerTrack.addEventListener('pointerdown',e=>{
2059
+ if(!e.isPrimary||e.button!==0)return;
2060
+ e.preventDefault();
2061
+ e.stopPropagation();
2062
+ scrubbingId=e.pointerId;
2063
+ rulerTrack.setPointerCapture?.(e.pointerId);
2064
+ scrubAt(e.clientX);
2065
+ });
2066
+ rulerTrack.addEventListener('pointermove',e=>{
2067
+ if(scrubbingId!==e.pointerId)return;
2068
+ scrubAt(e.clientX);
2069
+ });
2070
+ const endScrub=(e:PointerEvent)=>{
2071
+ if(scrubbingId!==e.pointerId)return;
2072
+ scrubbingId=null;
2073
+ if(rulerTrack.hasPointerCapture?.(e.pointerId))rulerTrack.releasePointerCapture(e.pointerId);
2074
+ };
2075
+ rulerTrack.addEventListener('pointerup',endScrub);
2076
+ rulerTrack.addEventListener('pointercancel',endScrub);
2077
+ }
2078
+
2079
+ private bindKeyDrag(
2080
+ mark:HTMLButtonElement,
2081
+ laneEl:HTMLElement,
2082
+ trackIndex:number,
2083
+ keyIndex:number,
2084
+ trackPointer:string,
2085
+ ){
2086
+ mark.addEventListener('pointerdown',e=>{
2087
+ if(!e.isPrimary||e.button!==0||this.isBusy)return;
2088
+ e.preventDefault();
2089
+ e.stopPropagation();
2090
+ this.suppressNextKeyClick=true;
2091
+ // Immediately select the key in place on pointerdown without rebuilding the DOM,
2092
+ // so pressing and dragging an unselected key works in a single gesture with zero layout shift.
2093
+ const liveTrack=this.inspection?.tracks.find(t=>t.pointer===trackPointer)??null;
2094
+ const liveIdx=Number(mark.dataset.keyIndex??keyIndex);
2095
+ if(liveTrack)this.track=liveTrack;
2096
+ this.channel=0;
2097
+ if(e.shiftKey){
2098
+ this.toggleKeySelection(trackIndex,liveIdx,trackPointer);
2099
+ this.renderChannels();
2100
+ return;
2101
+ }
2102
+ const alreadyInMulti=this.selectedKeys.length>1&&this.isKeySelected(trackIndex,liveIdx);
2103
+ const sel={animation:this.animation,trackIndex,keyIndex:liveIdx,pointer:trackPointer};
2104
+ this.selectedKey=sel;
2105
+ if(!alreadyInMulti){
2106
+ this.selectedKeys=[sel];
2107
+ }
2108
+ this.autoSyncPoseModeFromProperty(liveTrack?.name);
2109
+ this.syncTimelineKeysInPlace();
2110
+ this.syncKeyInspectorInPlace();
2111
+ this.renderChannels();
2112
+ const k=liveTrack?.keys[liveIdx];
2113
+ if(k&&k.time>=0&&k.time<=this.runtimeDuration){
2114
+ this.options.seek(k.time);
2115
+ }
2116
+ this.draggingKey={
2117
+ pointerId:e.pointerId,
2118
+ trackIndex,
2119
+ keyIndex:liveIdx,
2120
+ startX:e.clientX,
2121
+ moved:false,
2122
+ wasAlreadyInMulti:alreadyInMulti,
2123
+ undoGroupId:this.builder?this.builder.beginUndoGroup():1,
2124
+ laneEl,
2125
+ markEl:mark,
2126
+ end:this.effectiveEnd(),
2127
+ };
2128
+ mark.setPointerCapture?.(e.pointerId);
2129
+ });
2130
+
2131
+ mark.addEventListener('pointermove',e=>{
2132
+ const drag=this.draggingKey;
2133
+ if(!drag||drag.pointerId!==e.pointerId)return;
2134
+ if(!drag.moved&&Math.abs(e.clientX-drag.startX)<1)return;
2135
+ drag.moved=true;
2136
+ this.selectedKey={animation:this.animation,trackIndex:drag.trackIndex,keyIndex:drag.keyIndex,pointer:trackPointer};
2137
+ const rect=drag.laneEl.getBoundingClientRect();
2138
+ if(rect.width<=0)return;
2139
+ const ratio=Math.max(0,(e.clientX-rect.left)/rect.width);
2140
+ const rawTime=Math.round(ratio*drag.end*10000)/10000;
2141
+ if(this.selectedKeys.length>1&&this.isKeySelected(drag.trackIndex,drag.keyIndex)){
2142
+ const anchorKey=this.readDraftTrackKeys(drag.trackIndex)[drag.keyIndex];
2143
+ if(!anchorKey)return;
2144
+ const delta=cleanMotionNumber(rawTime-anchorKey.t);
2145
+ if(Math.abs(delta)<1e-6)return;
2146
+ const runMove=()=>
2147
+ this.moveSelection(
2148
+ this.selectedKeys.map(s=>({track:s.trackIndex,key:s.keyIndex})),
2149
+ delta,
2150
+ );
2151
+ const res=this.builder?this.builder.withUndoGroup(drag.undoGroupId,runMove):runMove();
2152
+ if(res.ok&&rawTime>=0&&rawTime<=this.runtimeDuration){
2153
+ this.options.seek(rawTime);
2154
+ }
2155
+ return;
2156
+ }
2157
+ const res=this.applyOp(
2158
+ {op:'set_key_time',animation:this.animation,track:drag.trackIndex,key:drag.keyIndex,time:rawTime},
2159
+ {skipTimelineDomRebuild:true},
2160
+ );
2161
+ if(res.ok&&rawTime>=0&&rawTime<=this.runtimeDuration){
2162
+ this.options.seek(rawTime);
2163
+ }
2164
+ });
2165
+
2166
+ const finishDrag=(e:PointerEvent)=>{
2167
+ const drag=this.draggingKey;
2168
+ if(!drag||drag.pointerId!==e.pointerId){
2169
+ if(mark.hasPointerCapture?.(e.pointerId))mark.releasePointerCapture(e.pointerId);
2170
+ if(e.type==="pointercancel")this.suppressNextKeyClick=false;
2171
+ return;
2172
+ }
2173
+ this.draggingKey=null;
2174
+ if(mark.hasPointerCapture?.(e.pointerId))mark.releasePointerCapture(e.pointerId);
2175
+ if(!drag.moved&&drag.wasAlreadyInMulti&&this.selectedKey){
2176
+ this.selectedKeys=[this.selectedKey];
2177
+ this.syncTimelineKeysInPlace();
2178
+ this.syncKeyInspectorInPlace();
2179
+ }
2180
+ e.preventDefault();
2181
+ if(e.type==="pointercancel")this.suppressNextKeyClick=false;
2182
+ };
2183
+ mark.addEventListener('pointerup',finishDrag);
2184
+ mark.addEventListener('pointercancel',finishDrag);
2185
+ }
2186
+
87
2187
  private renderChannels(){
88
2188
  const unsupported=this.track&&(this.track.kind!=='bone'||!CHANNELS[this.track.name])?`${this.track.target} · ${this.track.name} has no numeric curve evaluator`:'';this.unavailableChannel=unsupported;
89
2189
  this.channelSelect.replaceChildren();const tracks=this.inspection?filterTracks(this.inspection,this.selection.value()):[];
@@ -94,43 +2194,686 @@ export class AnimationInspectionPanel {
94
2194
  else{const first=this.channelSelect.options[0];if(first){const [pointer,c]=JSON.parse(first.value);this.track=tracks.find(t=>t.pointer===pointer)??null;this.channel=c;}else this.track=null;}
95
2195
  this.channelSelect.disabled=this.channelSelect.options.length===0;this.renderCurve();this.update(this.at,this.runtimeDuration);
96
2196
  }
2197
+
2198
+ private resolveTrackClassification(track:InspectionTrack|null):TrackClassification|undefined{
2199
+ if(!track||track.kind!=='bone')return undefined;
2200
+ return this.tracksInfo().find(c=>c.targetKind==='bone'&&c.target===track.target&&c.property===track.name);
2201
+ }
2202
+
2203
+ private availableEasings():Record<string,EasingTuple>{
2204
+ const out:Record<string,EasingTuple>={...(this.source?.easings??{})};
2205
+ const doc=this.draftDocument() as {easings?:Record<string,unknown>}|undefined;
2206
+ if(doc?.easings&&typeof doc.easings==='object'&&!Array.isArray(doc.easings)){
2207
+ for(const [k,v] of Object.entries(doc.easings)){
2208
+ if(Array.isArray(v)&&v.length===4&&v.every(n=>typeof n==='number'&&Number.isFinite(n))){
2209
+ out[k]=[v[0] as number,v[1] as number,v[2] as number,v[3] as number];
2210
+ }
2211
+ }
2212
+ }
2213
+ return out;
2214
+ }
2215
+
2216
+ private fullSegmentCubic(trackIndex:number,segmentIndex:number):number[]|null{
2217
+ const rawKeys=this.readDraftTrackKeys(trackIndex);
2218
+ const k0=rawKeys[segmentIndex],k1=rawKeys[segmentIndex+1];
2219
+ if(!k0||!k1)return null;
2220
+ const numChannels=k0.v.length;
2221
+ if(Array.isArray(k0.curve)&&k0.curve.length===numChannels*4){
2222
+ return k0.curve.map(n=>cleanMotionNumber(n));
2223
+ }
2224
+ if(typeof k0.ease==='string'&&k0.ease!=='stepped'){
2225
+ const handles=this.availableEasings()[k0.ease];
2226
+ if(handles&&handles.length===4){
2227
+ const [hx1,hy1,hx2,hy2]=handles;
2228
+ const dt=k1.t-k0.t;
2229
+ const out:number[]=[];
2230
+ for(let c=0;c<numChannels;c++){
2231
+ const v1=k0.v[c]!,dv=k1.v[c]!-v1;
2232
+ out.push(
2233
+ cleanMotionNumber(k0.t+dt*hx1),
2234
+ cleanMotionNumber(v1+dv*hy1),
2235
+ cleanMotionNumber(k0.t+dt*hx2),
2236
+ cleanMotionNumber(v1+dv*hy2),
2237
+ );
2238
+ }
2239
+ return out;
2240
+ }
2241
+ }
2242
+ return seedCubicCurve(k0.t,k0.v,k1.t,k1.v);
2243
+ }
2244
+
2245
+ private applyCurveModeChange(mode:string){
2246
+ const gate=this.gateInfo();
2247
+ const cls=this.resolveTrackClassification(this.track);
2248
+ if(!gate.editable||!cls?.editable){
2249
+ const reason=!gate.editable?`${gate.code}: ${gate.reason}`:cls?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`:'ANIMATION_TRACK_READ_ONLY: track is read-only';
2250
+ this.setEditorStatus(reason,true);
2251
+ return;
2252
+ }
2253
+ const segIdx=this.curveSegment;
2254
+ if(mode==='linear'){
2255
+ this.setKeyCurve(cls.trackIndex,segIdx,null);
2256
+ }else if(mode==='stepped'){
2257
+ this.setKeyCurve(cls.trackIndex,segIdx,'stepped');
2258
+ }else if(mode==='cubic'){
2259
+ const seeded=this.fullSegmentCubic(cls.trackIndex,segIdx);
2260
+ if(seeded)this.setKeyCurve(cls.trackIndex,segIdx,seeded);
2261
+ }else if(mode.startsWith('ease:')){
2262
+ this.setKeyEase(cls.trackIndex,segIdx,mode.slice(5));
2263
+ }
2264
+ }
2265
+
2266
+ private renderCurveControls(
2267
+ t:InspectionTrack|null,
2268
+ segments:ReturnType<typeof channelSegments>,
2269
+ cls:TrackClassification|undefined,
2270
+ trackEditable:boolean,
2271
+ ){
2272
+ const gate=this.gateInfo();
2273
+ this.segmentSelect.replaceChildren();
2274
+ this.easeSelect.replaceChildren();
2275
+ if(!t||segments.length===0){
2276
+ const opt=document.createElement('option');
2277
+ opt.value='0';
2278
+ opt.textContent='No segments';
2279
+ this.segmentSelect.append(opt);
2280
+ this.segmentSelect.disabled=true;
2281
+ const eOpt=document.createElement('option');
2282
+ eOpt.value='linear';
2283
+ eOpt.textContent='Linear';
2284
+ this.easeSelect.append(eOpt);
2285
+ this.easeSelect.disabled=true;
2286
+ const reason=!gate.editable
2287
+ ?`${gate.code}: ${gate.reason}`
2288
+ :cls&&!cls.editable
2289
+ ?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`
2290
+ :t
2291
+ ?'Track has fewer than 2 keys (no curve segments).'
2292
+ :'Select a bone channel.';
2293
+ this.curveReadonly.hidden=false;
2294
+ this.curveReadonly.textContent=reason;
2295
+ this.curveReadonly.title=reason;
2296
+ return;
2297
+ }
2298
+
2299
+ if(
2300
+ cls&&
2301
+ this.selectedKey?.animation===this.animation&&
2302
+ this.selectedKey.trackIndex===cls.trackIndex&&
2303
+ this.selectedKey.keyIndex>=0&&
2304
+ this.selectedKey.keyIndex<segments.length
2305
+ ){
2306
+ this.curveSegment=this.selectedKey.keyIndex;
2307
+ }
2308
+ this.curveSegment=Math.max(0,Math.min(this.curveSegment,segments.length-1));
2309
+
2310
+ segments.forEach((s,idx)=>{
2311
+ const opt=document.createElement('option');
2312
+ opt.value=String(idx);
2313
+ opt.textContent=`#${idx} · ${formatSeconds(s.from[0])}s → ${formatSeconds(s.to[0])}s`;
2314
+ if(idx===this.curveSegment)opt.selected=true;
2315
+ this.segmentSelect.append(opt);
2316
+ });
2317
+ this.segmentSelect.disabled=segments.length<=1;
2318
+
2319
+ const easings=this.availableEasings();
2320
+ const modeOptions:Array<[string,string]>=[
2321
+ ['linear','Linear'],
2322
+ ['cubic','Cubic Bézier (handles)'],
2323
+ ['stepped','Stepped (hold)'],
2324
+ ...Object.keys(easings).map((name):[string,string]=>[`ease:${name}`,`Ease: ${name}`]),
2325
+ ];
2326
+ for(const [val,label] of modeOptions){
2327
+ const opt=document.createElement('option');
2328
+ opt.value=val;
2329
+ opt.textContent=label;
2330
+ this.easeSelect.append(opt);
2331
+ }
2332
+
2333
+ let currentMode='linear';
2334
+ if(cls){
2335
+ const rawKey=this.readDraftTrackKeys(cls.trackIndex)[this.curveSegment];
2336
+ if(rawKey){
2337
+ if(rawKey.curve==='stepped'||rawKey.ease==='stepped')currentMode='stepped';
2338
+ else if(Array.isArray(rawKey.curve))currentMode='cubic';
2339
+ else if(typeof rawKey.ease==='string'&&rawKey.ease){
2340
+ const eVal=`ease:${rawKey.ease}`;
2341
+ if(![...this.easeSelect.options].some(o=>o.value===eVal)){
2342
+ const extra=document.createElement('option');
2343
+ extra.value=eVal;
2344
+ extra.textContent=`Ease: ${rawKey.ease}`;
2345
+ this.easeSelect.append(extra);
2346
+ }
2347
+ currentMode=eVal;
2348
+ }
2349
+ }
2350
+ }else{
2351
+ const seg=segments[this.curveSegment];
2352
+ if(seg?.curve==='stepped')currentMode='stepped';
2353
+ else if(Array.isArray(seg?.curve))currentMode='cubic';
2354
+ }
2355
+ this.easeSelect.value=currentMode;
2356
+ this.easeSelect.disabled=this.isBusy||!trackEditable;
2357
+
2358
+ if(!trackEditable){
2359
+ const readonlyReason=!gate.editable
2360
+ ?`${gate.code}: ${gate.reason}`
2361
+ :cls&&!cls.editable
2362
+ ?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`
2363
+ :`ANIMATION_TRACK_READ_ONLY: bone track "${t.target}.${t.name}" is not an editable source track in ${this.source?.path??'animations_from'}`;
2364
+ this.curveReadonly.hidden=false;
2365
+ this.curveReadonly.textContent=readonlyReason;
2366
+ this.curveReadonly.title=readonlyReason;
2367
+ }else{
2368
+ this.curveReadonly.hidden=true;
2369
+ this.curveReadonly.textContent='';
2370
+ this.curveReadonly.title='';
2371
+ }
2372
+ }
2373
+
2374
+ private onCurveHandlePointerDown(e:PointerEvent,target:SVGElement){
2375
+ if(!e.isPrimary||e.button!==0||this.isBusy||this.draggingCurveHandle)return;
2376
+ e.preventDefault();
2377
+ e.stopPropagation();
2378
+ const gate=this.gateInfo();
2379
+ const cls=this.resolveTrackClassification(this.track);
2380
+ const trackEditable=gate.editable&&!!cls?.editable;
2381
+ if(!trackEditable||!cls||!this.track){
2382
+ const reason=!gate.editable
2383
+ ?`${gate.code}: ${gate.reason}`
2384
+ :cls&&!cls.editable
2385
+ ?`ANIMATION_TRACK_READ_ONLY: ${cls.reason}`
2386
+ :'ANIMATION_TRACK_READ_ONLY: curve handles are read-only on this track';
2387
+ this.setEditorStatus(reason,true);
2388
+ return;
2389
+ }
2390
+ const segIdx=Number(target.dataset.segment??0);
2391
+ const handleIdx=Number(target.dataset.curveHandle)===2?2:1;
2392
+ this.curveSegment=segIdx;
2393
+ const sel={animation:this.animation,trackIndex:cls.trackIndex,keyIndex:segIdx,pointer:this.track.pointer};
2394
+ this.selectedKey=sel;
2395
+ this.selectedKeys=[sel];
2396
+ this.syncTimelineKeysInPlace();
2397
+ this.syncKeyInspectorInPlace();
2398
+ const field=CHANNELS[this.track.name]?.[this.channel]?.field;
2399
+ if(!field||!this.track.keys.length)return;
2400
+ const segments=channelSegments(this.track,this.channel);
2401
+ const values=this.track.keys.map(k=>k[field] as number);
2402
+ for(const s of segments)if(Array.isArray(s.curve))values.push(s.curve[1]!,s.curve[3]!);
2403
+ const low=Math.min(...values),high=Math.max(...values),span=high-low||1;
2404
+ const end=Math.max(this.runtimeDuration,this.track.keys.at(-1)!.time,Number.MIN_VALUE);
2405
+ this.draggingCurveHandle={
2406
+ pointerId:e.pointerId,
2407
+ trackIndex:cls.trackIndex,
2408
+ segmentIndex:segIdx,
2409
+ handleIndex:handleIdx,
2410
+ channel:this.channel,
2411
+ undoGroupId:this.builder?this.builder.beginUndoGroup():1,
2412
+ low,
2413
+ high,
2414
+ span,
2415
+ end,
2416
+ };
2417
+ this.curvePlot.setPointerCapture?.(e.pointerId);
2418
+ }
2419
+
2420
+ private bindCurveHandleDrag(){
2421
+ const svgHost=this.curvePlot;
2422
+ svgHost.addEventListener('pointerdown',e=>{
2423
+ const rawTarget=e.target as (Element&{dataset?:DOMStringMap})|null;
2424
+ const target=rawTarget?.closest?.<SVGElement>('[data-curve-handle]')??(rawTarget?.dataset?.curveHandle?rawTarget as unknown as SVGElement:null);
2425
+ if(target)this.onCurveHandlePointerDown(e,target);
2426
+ });
2427
+
2428
+ svgHost.addEventListener('pointermove',e=>{
2429
+ const drag=this.draggingCurveHandle;
2430
+ if(!drag||drag.pointerId!==e.pointerId)return;
2431
+ const rect=svgHost.getBoundingClientRect();
2432
+ if(rect.width<=0||rect.height<=0)return;
2433
+ const toPlot=svgHost.getScreenCTM()?.inverse();
2434
+ if(!toPlot)return;
2435
+ const svgX=toPlot.a*e.clientX+toPlot.c*e.clientY+toPlot.e;
2436
+ const svgY=toPlot.b*e.clientX+toPlot.d*e.clientY+toPlot.f;
2437
+ const rawT=((svgX-48)/728)*drag.end;
2438
+ const rawV=drag.low+((195-svgY)/160)*drag.span;
2439
+ const rawKeys=this.readDraftTrackKeys(drag.trackIndex);
2440
+ const k0=rawKeys[drag.segmentIndex],k1=rawKeys[drag.segmentIndex+1];
2441
+ if(!k0||!k1)return;
2442
+ const cx=cleanMotionNumber(Math.max(k0.t,Math.min(k1.t,rawT)));
2443
+ const cy=cleanMotionNumber(rawV);
2444
+ const baseCurve=this.fullSegmentCubic(drag.trackIndex,drag.segmentIndex);
2445
+ if(!baseCurve)return;
2446
+ const nextCurve=[...baseCurve];
2447
+ const offset=drag.channel*4+(drag.handleIndex===2?2:0);
2448
+ nextCurve[offset]=cx;
2449
+ nextCurve[offset+1]=cy;
2450
+ this.setKeyCurve(drag.trackIndex,drag.segmentIndex,nextCurve);
2451
+ });
2452
+
2453
+ const endDrag=(e:PointerEvent)=>{
2454
+ const drag=this.draggingCurveHandle;
2455
+ if(!drag||drag.pointerId!==e.pointerId)return;
2456
+ this.draggingCurveHandle=null;
2457
+ if(svgHost.hasPointerCapture?.(e.pointerId))svgHost.releasePointerCapture(e.pointerId);
2458
+ this.renderCurve();
2459
+ };
2460
+ svgHost.addEventListener('pointerup',endDrag);
2461
+ svgHost.addEventListener('pointercancel',endDrag);
2462
+ }
2463
+
97
2464
  private renderCurve(){
98
- const host=this.options.host.querySelector('[data-curve-plot]')!;host.replaceChildren();this.cursor=null;this.plot=null;
99
- const t=this.track,field=t&&CHANNELS[t.name]?.[this.channel]?.field;if(!t||!field||!t.keys.length)return;
100
- const segments=channelSegments(t,this.channel),values=t.keys.map(k=>k[field] as number);for(const s of segments)if(Array.isArray(s.curve))values.push(s.curve[1]!,s.curve[3]!);
101
- const low=Math.min(...values),high=Math.max(...values),span=high-low||1,end=Math.max(this.runtimeDuration,t.keys.at(-1)!.time,Number.MIN_VALUE);
2465
+ const host=this.curvePlot;host.replaceChildren();this.cursor=null;this.plot=null;
2466
+ const t=this.track,field=t&&CHANNELS[t.name]?.[this.channel]?.field;
2467
+ const cls=this.resolveTrackClassification(t);
2468
+ const trackEditable=this.gateInfo().editable&&!!cls?.editable;
2469
+ if(!t||!field||!t.keys.length){
2470
+ this.renderCurveControls(null,[],cls,false);
2471
+ return;
2472
+ }
2473
+ const segments=channelSegments(t,this.channel);
2474
+ this.renderCurveControls(t,segments,cls,trackEditable);
2475
+ const values=t.keys.map(k=>k[field] as number);for(const s of segments)if(Array.isArray(s.curve))values.push(s.curve[1]!,s.curve[3]!);
2476
+ const activeDrag=this.draggingCurveHandle&&cls&&this.draggingCurveHandle.trackIndex===cls.trackIndex&&this.draggingCurveHandle.channel===this.channel?this.draggingCurveHandle:null;
2477
+ const low=activeDrag?activeDrag.low:Math.min(...values);
2478
+ const high=activeDrag?activeDrag.high:Math.max(...values);
2479
+ const span=activeDrag?activeDrag.span:(high-low||1);
2480
+ const end=activeDrag?activeDrag.end:Math.max(this.runtimeDuration,t.keys.at(-1)!.time,Number.MIN_VALUE);
102
2481
  const plot=this.plot=(time:number,value:number)=>({x:48+time/end*728,y:195-(value-low)/span*160});
103
2482
  host.append(svg('path',{d:'M48 20 V195 H776',class:'animation-axes'}));
104
- for(const [time,value]of [[0,low],[end,high]]){const n=svg('text',{x:time===0?48:650,y:time===0?220:15});n.textContent=`${time} s · ${value}`;host.append(n);}
2483
+ for(const [time,value]of [[0,low],[end,high]]){const n=svg('text',{x:time===0?48:650,y:time===0?220:15});n.textContent=`${formatSeconds(time)} s · ${formatSeconds(value)}`;host.append(n);}
105
2484
  for(const [index,s]of segments.entries()){
106
2485
  const a=plot(...s.from),b=plot(...s.to);let d=`M${a.x} ${a.y}`;
107
2486
  if(Array.isArray(s.curve)){const c=plot(s.curve[0]!,s.curve[1]!),e=plot(s.curve[2]!,s.curve[3]!);d+=` C${c.x} ${c.y} ${e.x} ${e.y} ${b.x} ${b.y}`;
108
- host.append(svg('path',{d:`M${a.x} ${a.y} L${c.x} ${c.y} M${b.x} ${b.y} L${e.x} ${e.y}`,class:'animation-handles'}));for(const p of [c,e])host.append(svg('circle',{cx:p.x,cy:p.y,r:3,class:'animation-handle'}));
2487
+ const hLine=svg('path',{d:`M${a.x} ${a.y} L${c.x} ${c.y} M${b.x} ${b.y} L${e.x} ${e.y}`,class:'animation-handles'});
2488
+ hLine.dataset.handleLines=String(index);
2489
+ host.append(hLine);
2490
+ for(const [hIdx,p] of [[1,c],[2,e]] as const){
2491
+ const hCircle=svg('circle',{cx:p.x,cy:p.y,r:trackEditable?5:3,class:`animation-handle${index===this.curveSegment?' active':''}`});
2492
+ hCircle.dataset.curveHandle=String(hIdx);
2493
+ hCircle.dataset.segment=String(index);
2494
+ hCircle.dataset.editable=String(trackEditable);
2495
+ hCircle.addEventListener('pointerdown',e=>this.onCurveHandlePointerDown(e as PointerEvent,hCircle));
2496
+ host.append(hCircle);
2497
+ }
109
2498
  }else d+=s.curve==='stepped'?` H${b.x} V${b.y}`:` L${b.x} ${b.y}`;
110
2499
  const path=svg('path',{d,class:'animation-curve'});path.dataset.segment=String(index);path.dataset.stored=JSON.stringify(s);host.append(path);
111
2500
  }
112
2501
  for(const k of t.keys){const p=plot(k.time,k[field] as number);host.append(svg('circle',{cx:p.x,cy:p.y,r:3,class:'animation-curve-key'}));}
113
2502
  this.cursor=svg('circle',{r:5,class:'animation-runtime-cursor'});host.append(this.cursor);
114
2503
  }
2504
+
115
2505
  update(time:number,duration:number){
116
- this.at=time;this.runtimeDuration=duration;const timeInput=this.options.host.querySelector<HTMLInputElement>('[data-curve-time]')!;timeInput.max=String(duration);if(document.activeElement!==timeInput)timeInput.value=String(time);this.placePlayheads();const t=this.track,c=t&&CHANNELS[t.name]?.[this.channel];this.readout.textContent=`Runtime evaluation unavailable: ${this.unavailableChannel||'select a numeric stored channel'}.`;for(const key of ['time','channelValue','localValue','bone','property'])delete this.readout.dataset[key];
2506
+ this.at=time;this.runtimeDuration=duration;const timeInput=this.options.host.querySelector<HTMLInputElement>('[data-curve-time]')!;timeInput.max=String(formatSeconds(duration));if(document.activeElement!==timeInput)timeInput.value=String(formatSeconds(time));
2507
+ const insertTimeInput=this.options.host.querySelector<HTMLInputElement>('[data-insert-time]');
2508
+ if(insertTimeInput&&document.activeElement!==insertTimeInput)insertTimeInput.value=String(cleanMotionNumber(time));
2509
+ this.placePlayheads();const t=this.track,c=t&&CHANNELS[t.name]?.[this.channel];this.readout.textContent=`Runtime evaluation unavailable: ${this.unavailableChannel||'select a numeric stored channel'}.`;for(const key of ['time','channelValue','localValue','bone','property'])delete this.readout.dataset[key];
117
2510
  if(!t||!c||!this.inspection)return;
118
2511
  const value=evaluateStoredChannel(t,this.channel,time),local=evaluateBoneLocals(this.inspection,t.target,time)[c.local];
119
2512
  Object.assign(this.readout.dataset,{time:String(time),channelValue:value===null?'setup':numeric(value),localValue:numeric(local),bone:t.target,property:c.local});
120
- this.readout.textContent=`Runtime evaluation · ${time} s · ${c.local} track: ${value===null?'before first key (setup)':numeric(value)} · authored local: ${numeric(local)}`;
2513
+ this.readout.textContent=`Runtime evaluation · ${formatSeconds(time)} s · ${c.local} track: ${value===null?'before first key (setup)':numeric(value)} · authored local: ${numeric(local)}`;
121
2514
  if(this.cursor&&this.plot){this.cursor.setAttribute('visibility',value===null?'hidden':'visible');if(value!==null){const p=this.plot(time,value);this.cursor.setAttribute('cx',String(p.x));this.cursor.setAttribute('cy',String(p.y));}}
122
2515
  }
123
- private placePlayheads(){const end=Math.max(this.runtimeDuration,...(this.inspection?.tracks??[]).map(t=>t.keys.at(-1)?.time??0),Number.MIN_VALUE);for(const n of this.options.host.querySelectorAll<HTMLElement>('[data-playhead]'))n.style.left=`${this.at/end*100}%`;}
2516
+
2517
+ private placePlayheads(){const end=this.effectiveEnd();for(const n of this.options.host.querySelectorAll<HTMLElement>('[data-playhead]'))n.style.left=`${Math.max(0,Math.min(100,this.at/end*100))}%`;}
2518
+
2519
+ boneWorldMatrix(boneName:string):{x:number;y:number;a:number;b:number;c:number;d:number}{
2520
+ const captured=this.bones.get(boneName);
2521
+ if(captured&&captured.hasMatrix){
2522
+ return {x:captured.x,y:captured.y,a:captured.a,b:captured.b,c:captured.c,d:captured.d};
2523
+ }
2524
+ if(!this.inspection)return {x:captured?.x??0,y:captured?.y??0,a:1,b:0,c:0,d:1};
2525
+ const chain:string[]=[];
2526
+ let curr:string|undefined=boneName;
2527
+ const visited=new Set<string>();
2528
+ while(curr&&!visited.has(curr)){
2529
+ visited.add(curr);
2530
+ chain.unshift(curr);
2531
+ const b=this.inspection.bones.find(x=>x.name===curr);
2532
+ curr=b?.parent;
2533
+ }
2534
+ let wa=1,wb=0,wc=0,wd=1,wx=0,wy=0;
2535
+ for(const name of chain){
2536
+ const locals=evaluateBoneLocals(this.inspection,name,this.at);
2537
+ const rx=(locals.rotation+locals.shearX)*(Math.PI/180);
2538
+ const ry=(locals.rotation+90+locals.shearY)*(Math.PI/180);
2539
+ const la=Math.cos(rx)*locals.scaleX;
2540
+ const lb=Math.cos(ry)*locals.scaleY;
2541
+ const lc=Math.sin(rx)*locals.scaleX;
2542
+ const ld=Math.sin(ry)*locals.scaleY;
2543
+ const nx=wa*locals.x+wb*locals.y+wx;
2544
+ const ny=wc*locals.x+wd*locals.y+wy;
2545
+ const na=wa*la+wb*lc;
2546
+ const nb=wa*lb+wb*ld;
2547
+ const nc=wc*la+wd*lc;
2548
+ const nd=wc*lb+wd*ld;
2549
+ wx=nx;wy=ny;wa=na;wb=nb;wc=nc;wd=nd;
2550
+ }
2551
+ return {x:wx,y:wy,a:wa,b:wb,c:wc,d:wd};
2552
+ }
2553
+
2554
+ private clientToWorld(clientX:number,clientY:number):{x:number;y:number}{
2555
+ const pickRect=this.picks.getBoundingClientRect();
2556
+ const rect=pickRect.width>0?pickRect:this.options.stage.getBoundingClientRect();
2557
+ const p0=this.options.project(0,0);
2558
+ const px=this.options.project(1,0);
2559
+ const py=this.options.project(0,1);
2560
+ const sx=px.x-p0.x||1;
2561
+ const sy=py.y-p0.y||1;
2562
+ return {
2563
+ x:(clientX-rect.left-p0.x)/sx,
2564
+ y:(clientY-rect.top-p0.y)/sy,
2565
+ };
2566
+ }
2567
+
2568
+ /**
2569
+ * Pose `boneName` on stage in `mode` ('rotate' or 'translate') at viewport client coordinates
2570
+ * `(clientX, clientY)`. When the playhead sits on an existing key (within 5e-4 s), sets that key's
2571
+ * value; otherwise inserts a key at the playhead (`this.at`) and sets it as one undo group.
2572
+ */
2573
+ poseBoneOnStage(
2574
+ boneName:string,
2575
+ mode:'rotate'|'translate',
2576
+ clientX:number,
2577
+ clientY:number,
2578
+ gesture?:{
2579
+ undoGroupId:number;
2580
+ originWorld:{x:number;y:number};
2581
+ parentWorld:{x:number;y:number;a:number;b:number;c:number;d:number};
2582
+ },
2583
+ ):{ok:true;ops:readonly AnimationSourceOp[]}|{ok:false;error:string}{
2584
+ const gate=this.gateInfo();
2585
+ if(!gate.editable){
2586
+ const err=`${gate.code}: ${gate.reason??'animation is read-only'}`;
2587
+ this.setEditorStatus(err,true);
2588
+ return {ok:false,error:err};
2589
+ }
2590
+ if(!this.builder||!this.source?.available||!this.inspection){
2591
+ const err='ANIMATION_SOURCE_MISSING: animation source is not loaded';
2592
+ this.setEditorStatus(err,true);
2593
+ return {ok:false,error:err};
2594
+ }
2595
+ const setup=this.inspection.bones.find(b=>b.name===boneName);
2596
+ if(!setup){
2597
+ const err=`ANIMATION_BONE_NO_TRACK: unknown bone "${boneName}"`;
2598
+ this.setEditorStatus(err,true);
2599
+ return {ok:false,error:err};
2600
+ }
2601
+ const clss=this.tracksInfo();
2602
+ const boneTracks=clss.filter(c=>c.targetKind==='bone'&&c.target===boneName);
2603
+ const matchingProps=mode==='rotate'?['rotate']:['translate','translatex','translatey'];
2604
+ const matchingTracks=boneTracks.filter(c=>matchingProps.includes(c.property));
2605
+ const readonlyMatch=matchingTracks.find(c=>!c.editable);
2606
+ if(readonlyMatch){
2607
+ const err=`ANIMATION_TRACK_READ_ONLY: ${readonlyMatch.reason}`;
2608
+ this.setEditorStatus(err,true);
2609
+ return {ok:false,error:err};
2610
+ }
2611
+ // Also check if compiled inspection has a bone track for this property that is missing from source
2612
+ const editableMatches=matchingTracks.filter(c=>c.editable);
2613
+ if(editableMatches.length===0){
2614
+ const constraint=findBoneConstraint(this.document,boneName);
2615
+ if(constraint){
2616
+ const err=`ANIMATION_BONE_CONSTRAINED: bone "${boneName}" is driven by ${constraint.kind} constraint "${constraint.name}" and cannot be posed directly on stage`;
2617
+ this.setEditorStatus(err,true);
2618
+ return {ok:false,error:err};
2619
+ }
2620
+ const compiledOnly=this.inspection.tracks.find(
2621
+ t=>t.kind==='bone'&&t.target===boneName&&matchingProps.includes(t.name),
2622
+ );
2623
+ if(compiledOnly){
2624
+ const err=`ANIMATION_TRACK_READ_ONLY: bone track "${boneName}.${compiledOnly.name}" is not an editable source track in ${this.source.path??'animations_from'}`;
2625
+ this.setEditorStatus(err,true);
2626
+ return {ok:false,error:err};
2627
+ }
2628
+ const err=`ANIMATION_BONE_NO_TRACK: bone "${boneName}" has no editable "${mode}" track in animation "${this.animation}" (${this.source.path??'animations_from'})`;
2629
+ this.setEditorStatus(err,true);
2630
+ return {ok:false,error:err};
2631
+ }
2632
+
2633
+ const worldPt=this.clientToWorld(clientX,clientY);
2634
+ const parentWorld=
2635
+ gesture?.parentWorld??
2636
+ (setup.parent?this.boneWorldMatrix(setup.parent):{x:0,y:0,a:1,b:0,c:0,d:1});
2637
+ const originWorld=gesture?.originWorld??this.boneWorldMatrix(boneName);
2638
+ const det=parentWorld.a*parentWorld.d-parentWorld.b*parentWorld.c;
2639
+
2640
+ let targetOps:Array<{trackIndex:number;property:string;channel?:number;value:number|readonly number[]}>=[];
2641
+
2642
+ if(mode==='rotate'){
2643
+ const rotTrack=editableMatches.find(c=>c.property==='rotate')!;
2644
+ const vx=worldPt.x-originWorld.x;
2645
+ const vy=worldPt.y-originWorld.y;
2646
+ if(Math.hypot(vx,vy)<1e-6){
2647
+ return {ok:true,ops:this.builder.ops};
2648
+ }
2649
+ const lvx=Math.abs(det)>1e-8?(parentWorld.d*vx-parentWorld.b*vy)/det:vx;
2650
+ const lvy=Math.abs(det)>1e-8?(-parentWorld.c*vx+parentWorld.a*vy)/det:vy;
2651
+ const angleDeg=Math.atan2(lvy,lvx)*(180/Math.PI);
2652
+ const rawDelta=angleDeg-(setup.rotation??0);
2653
+ const wrapped=((((rawDelta+180)%360)+360)%360)-180;
2654
+ const rotVal=cleanMotionNumber(wrapped);
2655
+ targetOps=[{trackIndex:rotTrack.trackIndex,property:'rotate',value:[rotVal]}];
2656
+ }else{
2657
+ const dx=worldPt.x-parentWorld.x;
2658
+ const dy=worldPt.y-parentWorld.y;
2659
+ const localX=Math.abs(det)>1e-8?(parentWorld.d*dx-parentWorld.b*dy)/det:dx;
2660
+ const localY=Math.abs(det)>1e-8?(-parentWorld.c*dx+parentWorld.a*dy)/det:dy;
2661
+ const trackValX=cleanMotionNumber(localX-(setup.x??0));
2662
+ const trackValY=cleanMotionNumber(localY-(setup.y??0));
2663
+ const tr2d=editableMatches.find(c=>c.property==='translate');
2664
+ if(tr2d){
2665
+ targetOps=[{trackIndex:tr2d.trackIndex,property:'translate',value:[trackValX,trackValY]}];
2666
+ }else{
2667
+ const trx=editableMatches.find(c=>c.property==='translatex');
2668
+ const tryTrack=editableMatches.find(c=>c.property==='translatey');
2669
+ if(trx)targetOps.push({trackIndex:trx.trackIndex,property:'translatex',value:[trackValX]});
2670
+ if(tryTrack)targetOps.push({trackIndex:tryTrack.trackIndex,property:'translatey',value:[trackValY]});
2671
+ }
2672
+ }
2673
+
2674
+ const groupId=gesture?.undoGroupId??this.builder.beginUndoGroup();
2675
+ const savedText=this.builder.text;
2676
+ try{
2677
+ this.options.pause?.();
2678
+ if(gesture){
2679
+ this.builder.unwindUndoGroup(groupId);
2680
+ }
2681
+ let keyCountChanged=false;
2682
+ const playheadTime=cleanMotionNumber(this.at);
2683
+ this.builder.withUndoGroup(groupId,()=>{
2684
+ for(const item of targetOps){
2685
+ const beforeKeys=this.readDraftTrackKeys(item.trackIndex);
2686
+ const existingIdx=beforeKeys.findIndex(k=>Math.abs(k.t-playheadTime)<=5e-4);
2687
+ const arrVal=Array.isArray(item.value)?item.value:[item.value as number];
2688
+ if(existingIdx>=0){
2689
+ this.builder!.apply({
2690
+ op:'set_key_value',
2691
+ animation:this.animation,
2692
+ track:item.trackIndex,
2693
+ key:existingIdx,
2694
+ value:arrVal,
2695
+ });
2696
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===boneName&&t.name===item.property);
2697
+ const sel={animation:this.animation,trackIndex:item.trackIndex,keyIndex:existingIdx,pointer:inspTrack?.pointer??''};
2698
+ this.selectedKey=sel;
2699
+ this.selectedKeys=[sel];
2700
+ }else{
2701
+ this.builder!.apply({
2702
+ op:'insert_key',
2703
+ animation:this.animation,
2704
+ track:item.trackIndex,
2705
+ time:playheadTime,
2706
+ value:arrVal,
2707
+ });
2708
+ const afterKeys=this.readDraftTrackKeys(item.trackIndex);
2709
+ const newIdx=afterKeys.findIndex(k=>Math.abs(k.t-playheadTime)<=5e-4);
2710
+ const inspTrack=this.inspection?.tracks.find(t=>t.kind==='bone'&&t.target===boneName&&t.name===item.property);
2711
+ if(newIdx>=0){
2712
+ const sel={animation:this.animation,trackIndex:item.trackIndex,keyIndex:newIdx,pointer:inspTrack?.pointer??''};
2713
+ this.selectedKey=sel;
2714
+ this.selectedKeys=[sel];
2715
+ }
2716
+ const domLaneKeys=this.options.host.querySelectorAll(`.animation-key[data-source-track="${item.trackIndex}"]`).length;
2717
+ if(domLaneKeys!==afterKeys.length)keyCountChanged=true;
2718
+ }
2719
+ }
2720
+ });
2721
+ this.syncEffectiveInspection(true);
2722
+ this.renderEditorBar();
2723
+ if(keyCountChanged){
2724
+ this.renderTimeline();
2725
+ }else{
2726
+ this.syncTimelineKeysInPlace();
2727
+ this.syncKeyInspectorInPlace();
2728
+ }
2729
+ this.renderChannels();
2730
+ this.setEditorStatus(
2731
+ `Posed bone "${boneName}" (${mode}) at ${formatSeconds(playheadTime)} s (${this.builder.ops.length} pending op(s), preview active).`,
2732
+ false,
2733
+ );
2734
+ return {ok:true,ops:this.builder.ops};
2735
+ }catch(e){
2736
+ if(this.builder.text!==savedText&&gesture){
2737
+ this.builder.unwindUndoGroup(groupId);
2738
+ }
2739
+ const msg=e instanceof Error?e.message:String(e);
2740
+ this.setEditorStatus(msg,true);
2741
+ return {ok:false,error:msg};
2742
+ }
2743
+ }
2744
+
2745
+ private bindStageBoneDrag(btn:HTMLButtonElement,boneName:string){
2746
+ btn.addEventListener('pointerdown',e=>{
2747
+ if(!e.isPrimary||e.button!==0||this.isBusy||this.space)return;
2748
+ e.stopPropagation();
2749
+ const mode:'rotate'|'translate'=e.altKey?(this.poseMode==='rotate'?'translate':'rotate'):this.poseMode;
2750
+ const targetBone=this.resolveBoneForStageDrag(boneName,mode);
2751
+ const setup=this.inspection?.bones.find(b=>b.name===targetBone);
2752
+ const originWorld=this.boneWorldMatrix(targetBone);
2753
+ const parentWorld=setup?.parent?this.boneWorldMatrix(setup.parent):{x:0,y:0,a:1,b:0,c:0,d:1};
2754
+ const undoGroupId=this.builder?this.builder.beginUndoGroup():1;
2755
+ this.draggingStageBone={
2756
+ pointerId:e.pointerId,
2757
+ boneName:targetBone,
2758
+ mode,
2759
+ startX:e.clientX,
2760
+ startY:e.clientY,
2761
+ moved:false,
2762
+ undoGroupId,
2763
+ originWorld:{x:originWorld.x,y:originWorld.y},
2764
+ parentWorld,
2765
+ };
2766
+ btn.setPointerCapture?.(e.pointerId);
2767
+ });
2768
+
2769
+ btn.addEventListener('pointermove',e=>{
2770
+ const drag=this.draggingStageBone;
2771
+ if(!drag||drag.pointerId!==e.pointerId)return;
2772
+ if(!drag.moved&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<2)return;
2773
+ if(!drag.moved){
2774
+ drag.moved=true;
2775
+ this.suppressNextBoneClick=true;
2776
+ this.select({kind:'bone',name:drag.boneName});
2777
+ }
2778
+ const activeMode:'rotate'|'translate'=e.altKey?(this.poseMode==='rotate'?'translate':'rotate'):drag.mode;
2779
+ this.poseBoneOnStage(drag.boneName,activeMode,e.clientX,e.clientY,{
2780
+ undoGroupId:drag.undoGroupId,
2781
+ originWorld:drag.originWorld,
2782
+ parentWorld:drag.parentWorld,
2783
+ });
2784
+ });
2785
+
2786
+ const endBoneDrag=(e:PointerEvent)=>{
2787
+ const drag=this.draggingStageBone;
2788
+ if(!drag||drag.pointerId!==e.pointerId)return;
2789
+ this.draggingStageBone=null;
2790
+ if(btn.hasPointerCapture?.(e.pointerId))btn.releasePointerCapture(e.pointerId);
2791
+ if(drag.moved){
2792
+ e.preventDefault();
2793
+ setTimeout(()=>{this.suppressNextBoneClick=false;},0);
2794
+ }
2795
+ };
2796
+ btn.addEventListener('pointerup',endBoneDrag);
2797
+ btn.addEventListener('pointercancel',endBoneDrag);
2798
+ }
2799
+
124
2800
  capture(player:Pick<RigPlayer,'bone'>|null,frame:PosedFrame|undefined){
125
- this.frame=frame??null;this.bones.clear();for(const b of player&&frame?this.inspection?.bones??[]:[]){try{const p=player!.bone(b.name);if(p.active)this.bones.set(b.name,{x:p.x,y:p.y});}catch{/* unavailable bones have no stage handle */}}this.redraw();
2801
+ this.frame=frame??null;this.bones.clear();
2802
+ for(const b of player&&frame?this.inspection?.bones??[]:[]){
2803
+ try{
2804
+ const p=player!.bone(b.name) as {x:number;y:number;active:boolean;a?:number;b?:number;c?:number;d?:number};
2805
+ if(p.active){
2806
+ const hasMatrix=typeof p.a==='number'&&typeof p.b==='number'&&typeof p.c==='number'&&typeof p.d==='number';
2807
+ this.bones.set(b.name,{
2808
+ x:p.x,
2809
+ y:p.y,
2810
+ a:hasMatrix?p.a!:1,
2811
+ b:hasMatrix?p.b!:0,
2812
+ c:hasMatrix?p.c!:0,
2813
+ d:hasMatrix?p.d!:1,
2814
+ hasMatrix,
2815
+ });
2816
+ }
2817
+ }catch{/* unavailable bones have no stage handle */}
2818
+ }
2819
+ this.redraw();
126
2820
  }
2821
+
127
2822
  redraw(bonePoints=this.bonePoints){
128
2823
  this.bonePoints=bonePoints;
129
2824
  for(const [name,node]of this.boneButtons)if(!this.bones.has(name)){node.remove();this.boneButtons.delete(name);}
130
- const {stage}=this.options,selected=this.selection.value();stage.dataset.heldFrame=this.frame?'available':'unavailable';stage.dataset.selectedKind=selected?.kind??'';stage.dataset.selectedName=selected?.name??'';this.picks.hidden=!this.options.enabled();
131
- let order=0;for(const [name,p]of this.bones){let b=this.boneButtons.get(name);if(!b){b=button('',()=>this.select({kind:'bone',name}));b.className='animation-bone-pick';b.title=`Select bone ${name}`;b.setAttribute('aria-label',b.title);b.dataset.bone=name;this.boneButtons.set(name,b);this.picks.append(b);}
132
- b.style.zIndex=String(order++);const at=this.options.project(p.x,p.y);b.style.left=`${at.x}px`;b.style.top=`${at.y}px`;b.hidden=!bonePoints&&!(selected?.kind==='bone'&&selected.name===name);b.setAttribute('aria-pressed',String(selected?.kind==='bone'&&selected.name===name));
2825
+ const {stage}=this.options,selected=this.selection.value();
2826
+ stage.dataset.heldFrame=this.frame?'available':'unavailable';
2827
+ stage.dataset.selectedKind=selected?.kind??'';
2828
+ stage.dataset.selectedName=selected?.name??'';
2829
+ const enabled=this.options.enabled();
2830
+ this.picks.hidden=!enabled;
2831
+ const otherMode:'rotate'|'translate'=this.poseMode==='rotate'?'translate':'rotate';
2832
+ let order=0;
2833
+ for(const [name,p]of this.bones){
2834
+ let b=this.boneButtons.get(name);
2835
+ if(!b){
2836
+ b=button('',()=>{
2837
+ if(this.suppressNextBoneClick){
2838
+ this.suppressNextBoneClick=false;
2839
+ return;
2840
+ }
2841
+ const targetName=this.resolveBoneForStageClick(name);
2842
+ this.select({kind:'bone',name:targetName});
2843
+ });
2844
+ b.className='animation-bone-pick';
2845
+ b.title=`Select or drag bone ${name}`;
2846
+ b.setAttribute('aria-label',`Select bone ${name}`);
2847
+ b.dataset.bone=name;
2848
+ this.bindStageBoneDrag(b,name);
2849
+ this.boneButtons.set(name,b);
2850
+ this.picks.append(b);
2851
+ }
2852
+ const isSelected=selected?.kind==='bone'&&selected.name===name;
2853
+ const visible=enabled&&(bonePoints||isSelected);
2854
+ b.hidden=!bonePoints&&!isSelected;
2855
+ b.setAttribute('aria-pressed',String(isSelected));
2856
+ if(!visible){
2857
+ order++;
2858
+ continue;
2859
+ }
2860
+ const editableNow=this.isBoneEditableInMode(name,this.poseMode);
2861
+ const editableOther=this.isBoneEditableInMode(name,otherMode);
2862
+ b.dataset.poseEditable=editableNow?'true':editableOther?'other':'false';
2863
+ const zRank=isSelected&&editableNow
2864
+ ?500
2865
+ :editableNow
2866
+ ?400-Math.min(90,this.firstEditableTrackIndexForBone(name,this.poseMode))
2867
+ :isSelected||editableOther
2868
+ ?200+order
2869
+ :100+order;
2870
+ order++;
2871
+ b.style.zIndex=String(zRank);
2872
+ const at=this.options.project(p.x,p.y);
2873
+ b.style.left=`${at.x}px`;
2874
+ b.style.top=`${at.y}px`;
133
2875
  }
134
2876
  }
2877
+
135
2878
  dispose(){for(const dispose of this.disposers)dispose();this.picks.remove();}
136
2879
  }