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.
@@ -6,6 +6,7 @@ import {
6
6
  } from './animation-inspection.ts';
7
7
 
8
8
  export const MOTION_SPEC_VERSION = 'rigc-motion/1';
9
+ export const MAX_ANIMATION_OPS = 200;
9
10
 
10
11
  export type EasingTuple = readonly [number, number, number, number];
11
12
 
@@ -382,9 +383,11 @@ export interface AnimationEditGate {
382
383
  editable: boolean;
383
384
  code:
384
385
  | 'OK'
386
+ | 'ANIMATION_SOURCE_LOADING'
385
387
  | 'ANIMATION_IDLE_GOVERNED_BY_TURN_PAD'
386
388
  | 'ANIMATION_SOURCE_MISSING'
387
- | 'ANIMATION_NOT_IN_SOURCE';
389
+ | 'ANIMATION_NOT_IN_SOURCE'
390
+ | 'ANIMATION_COMPARE_READ_ONLY';
388
391
  reason: string | null;
389
392
  note: string | null;
390
393
  }
@@ -399,10 +402,115 @@ export interface TrackClassification {
399
402
  reason: string | null;
400
403
  }
401
404
 
405
+ export interface BoneConstraintInfo {
406
+ name: string;
407
+ kind: 'physics' | 'ik' | 'transform' | 'path' | 'slider';
408
+ }
409
+
402
410
  function isRecord(v: unknown): v is Record<string, unknown> {
403
411
  return typeof v === 'object' && v !== null && !Array.isArray(v);
404
412
  }
405
413
 
414
+ /**
415
+ * Inspect a compiled `rigc-compiled/3` model document to determine whether `boneName`
416
+ * is driven by a constraint (`physics`, `ik`, `transform`, `path`, or `slider`).
417
+ */
418
+ export function findBoneConstraint(
419
+ modelDocument: unknown,
420
+ boneName: string,
421
+ ): BoneConstraintInfo | null {
422
+ if (!isRecord(modelDocument) || !boneName) return null;
423
+ const animations = Array.isArray(modelDocument.animations) ? modelDocument.animations : [];
424
+ const checkConstraint = (
425
+ raw: unknown,
426
+ fallbackKind?: BoneConstraintInfo['kind'],
427
+ ): BoneConstraintInfo | null => {
428
+ if (!isRecord(raw) || typeof raw.name !== 'string') return null;
429
+ const rec = isRecord(raw.record) ? raw.record : raw;
430
+ const kind = (
431
+ typeof raw.kind === 'string'
432
+ ? raw.kind
433
+ : typeof raw.type === 'string'
434
+ ? raw.type
435
+ : typeof rec.kind === 'string'
436
+ ? rec.kind
437
+ : typeof rec.type === 'string'
438
+ ? rec.type
439
+ : fallbackKind
440
+ ) as BoneConstraintInfo['kind'] | undefined;
441
+ if (!kind) return null;
442
+ const boneField =
443
+ typeof rec.bone === 'string'
444
+ ? rec.bone
445
+ : typeof raw.bone === 'string'
446
+ ? raw.bone
447
+ : undefined;
448
+ const bonesField = Array.isArray(rec.bones)
449
+ ? rec.bones
450
+ : Array.isArray(raw.bones)
451
+ ? raw.bones
452
+ : undefined;
453
+ if (kind === 'physics' && boneField === boneName) {
454
+ return { name: raw.name, kind: 'physics' };
455
+ }
456
+ if (
457
+ (kind === 'ik' || kind === 'transform' || kind === 'path') &&
458
+ (boneField === boneName || (bonesField !== undefined && bonesField.includes(boneName)))
459
+ ) {
460
+ return { name: raw.name, kind };
461
+ }
462
+ if (kind === 'slider') {
463
+ if (boneField === boneName || (bonesField !== undefined && bonesField.includes(boneName))) {
464
+ return { name: raw.name, kind: 'slider' };
465
+ }
466
+ if (
467
+ isRecord(rec.timelines) &&
468
+ Array.isArray(rec.timelines.bones) &&
469
+ rec.timelines.bones.some((b) => isRecord(b) && b.name === boneName)
470
+ ) {
471
+ return { name: raw.name, kind: 'slider' };
472
+ }
473
+ const animName =
474
+ typeof rec.animation === 'string'
475
+ ? rec.animation
476
+ : typeof raw.animation === 'string'
477
+ ? raw.animation
478
+ : undefined;
479
+ if (animName) {
480
+ const sliderAnim = animations.find(
481
+ (a) => isRecord(a) && a.name === animName && Array.isArray(a.bones),
482
+ ) as { bones?: unknown[] } | undefined;
483
+ if (sliderAnim?.bones?.some((b) => isRecord(b) && b.name === boneName)) {
484
+ return { name: raw.name, kind: 'slider' };
485
+ }
486
+ }
487
+ }
488
+ return null;
489
+ };
490
+ if (Array.isArray(modelDocument.constraints)) {
491
+ for (const raw of modelDocument.constraints) {
492
+ const hit = checkConstraint(raw);
493
+ if (hit) return hit;
494
+ }
495
+ }
496
+ for (const [field, kind] of [
497
+ ['physics', 'physics'],
498
+ ['ik', 'ik'],
499
+ ['transform', 'transform'],
500
+ ['path', 'path'],
501
+ ['sliders', 'slider'],
502
+ ] as const) {
503
+ const list = modelDocument[field];
504
+ if (Array.isArray(list)) {
505
+ for (const raw of list) {
506
+ const hit = checkConstraint(raw, kind);
507
+ if (hit) return hit;
508
+ }
509
+ }
510
+ }
511
+ return null;
512
+ }
513
+
406
514
  /**
407
515
  * Evaluate whether an animation in a package may be edited through `animations_from`.
408
516
  */
@@ -1039,29 +1147,36 @@ export function applyAnimationOp(
1039
1147
  text: string,
1040
1148
  op: AnimationSourceOp,
1041
1149
  baseText?: string,
1150
+ fallbackEasings?: Readonly<Record<string, EasingTuple>>,
1042
1151
  ): AppliedAnimationOpsResult {
1043
1152
  const { doc, classification, keys } = resolveEditableTrack(text, op.animation, op.track);
1044
1153
  const channels = classification.channels;
1045
1154
  const keysPath = ['animations', op.animation, 'tracks', op.track, 'keys'] as const;
1046
1155
 
1156
+ const trackLabel = `animation "${op.animation}" track ${op.track} ("${classification.target}.${classification.property}")`;
1157
+
1047
1158
  if (op.op === 'set_key_time') {
1048
1159
  if (!Number.isInteger(op.key) || op.key < 0 || op.key >= keys.length) {
1049
- throw new Error(`ANIMATION_KEY_OUT_OF_RANGE: key index ${op.key} out of [0, ${keys.length - 1}]`);
1160
+ throw new Error(
1161
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${op.key} out of [0, ${keys.length - 1}]`,
1162
+ );
1050
1163
  }
1051
1164
  if (typeof op.time !== 'number' || !Number.isFinite(op.time) || op.time < 0) {
1052
- throw new Error(`ANIMATION_KEY_TIME_INVALID: key time must be a finite number >= 0, got ${String(op.time)}`);
1165
+ throw new Error(
1166
+ `ANIMATION_KEY_TIME_INVALID: ${trackLabel} key ${op.key} time must be a finite number >= 0, got ${String(op.time)}`,
1167
+ );
1053
1168
  }
1054
1169
  const nextTime = cleanMotionNumber(op.time);
1055
1170
  const prevKey = op.key > 0 ? keys[op.key - 1] : undefined;
1056
1171
  const nextKey = op.key + 1 < keys.length ? keys[op.key + 1] : undefined;
1057
1172
  if (prevKey && nextTime <= prevKey.t) {
1058
1173
  throw new Error(
1059
- `ANIMATION_KEY_ORDER: key ${op.key} time ${nextTime} must be > previous key ${op.key - 1} time ${prevKey.t}`,
1174
+ `ANIMATION_KEY_ORDER: ${trackLabel} key ${op.key} time ${nextTime} must be > previous key ${op.key - 1} time ${prevKey.t}`,
1060
1175
  );
1061
1176
  }
1062
1177
  if (nextKey && nextTime >= nextKey.t) {
1063
1178
  throw new Error(
1064
- `ANIMATION_KEY_ORDER: key ${op.key} time ${nextTime} must be < next key ${op.key + 1} time ${nextKey.t}`,
1179
+ `ANIMATION_KEY_ORDER: ${trackLabel} key ${op.key} time ${nextTime} must be < next key ${op.key + 1} time ${nextKey.t}`,
1065
1180
  );
1066
1181
  }
1067
1182
 
@@ -1217,7 +1332,10 @@ export function applyAnimationOp(
1217
1332
  if (op.ease === 'stepped') {
1218
1333
  throw new Error('ANIMATION_EASING_STEPPED_USE_CURVE: "stepped" is a curve mode; use curve: "stepped"');
1219
1334
  }
1220
- const easings = isRecord(doc.easings) ? doc.easings : {};
1335
+ const easings = {
1336
+ ...(fallbackEasings ?? {}),
1337
+ ...(isRecord(doc.easings) ? doc.easings : {}),
1338
+ };
1221
1339
  if (!Array.isArray(easings[op.ease])) {
1222
1340
  throw new Error(`ANIMATION_EASING_UNKNOWN: unknown easing "${op.ease}"`);
1223
1341
  }
@@ -1267,7 +1385,10 @@ export function applyAnimationOp(
1267
1385
  if (op.ease === 'stepped') {
1268
1386
  throw new Error('ANIMATION_EASING_STEPPED_USE_CURVE: "stepped" is a curve mode; use curve: "stepped"');
1269
1387
  }
1270
- const easings = isRecord(doc.easings) ? doc.easings : {};
1388
+ const easings = {
1389
+ ...(fallbackEasings ?? {}),
1390
+ ...(isRecord(doc.easings) ? doc.easings : {}),
1391
+ };
1271
1392
  if (!Array.isArray(easings[op.ease])) {
1272
1393
  throw new Error(`ANIMATION_EASING_UNKNOWN: unknown easing "${op.ease}"`);
1273
1394
  }
@@ -1337,10 +1458,14 @@ export function applyAnimationOp(
1337
1458
 
1338
1459
  if (op.op === 'delete_key') {
1339
1460
  if (!Number.isInteger(op.key) || op.key < 0 || op.key >= keys.length) {
1340
- throw new Error(`ANIMATION_KEY_OUT_OF_RANGE: key index ${op.key} out of [0, ${keys.length - 1}]`);
1461
+ throw new Error(
1462
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${op.key} out of [0, ${keys.length - 1}]`,
1463
+ );
1341
1464
  }
1342
1465
  if (keys.length <= 1) {
1343
- throw new Error('ANIMATION_TRACK_MIN_KEYS: cannot delete the only key on a track');
1466
+ throw new Error(
1467
+ `ANIMATION_TRACK_MIN_KEYS: ${trackLabel} cannot delete key ${op.key}; cannot delete the only key on a track (has ${keys.length})`,
1468
+ );
1344
1469
  }
1345
1470
 
1346
1471
  const keysArray = resolveArrayNode(text, keysPath);
@@ -1651,11 +1776,21 @@ function coalesceSetKeyValueOp(
1651
1776
  */
1652
1777
  export class AnimationOpBuilder {
1653
1778
  readonly baseText: string;
1779
+ readonly fallbackEasings?: Readonly<Record<string, EasingTuple>>;
1654
1780
  private currentText: string;
1655
- private readonly history: Array<{ op: AnimationSourceOp; textBefore: string }> = [];
1656
-
1657
- constructor(baseText: string) {
1781
+ private readonly history: Array<{
1782
+ op: AnimationSourceOp;
1783
+ textBefore: string;
1784
+ undoGroupId?: number;
1785
+ explicitGroup?: boolean;
1786
+ }> = [];
1787
+ private nextUndoGroupId = 1;
1788
+ private activeUndoGroupId: number | undefined = undefined;
1789
+ private explicitGroupDepth = 0;
1790
+
1791
+ constructor(baseText: string, fallbackEasings?: Readonly<Record<string, EasingTuple>>) {
1658
1792
  this.baseText = baseText;
1793
+ this.fallbackEasings = fallbackEasings;
1659
1794
  this.currentText = baseText;
1660
1795
  }
1661
1796
 
@@ -1671,10 +1806,120 @@ export class AnimationOpBuilder {
1671
1806
  return this.currentText !== this.baseText;
1672
1807
  }
1673
1808
 
1809
+ beginUndoGroup(): number {
1810
+ return this.nextUndoGroupId++;
1811
+ }
1812
+
1813
+ withUndoGroup<T>(groupId: number, fn: () => T): T {
1814
+ const prev = this.activeUndoGroupId;
1815
+ this.activeUndoGroupId = groupId;
1816
+ this.explicitGroupDepth++;
1817
+ try {
1818
+ return fn();
1819
+ } finally {
1820
+ this.explicitGroupDepth--;
1821
+ this.activeUndoGroupId = prev;
1822
+ }
1823
+ }
1824
+
1825
+ private withInternalUndoGroup<T>(groupId: number, fn: () => T): T {
1826
+ const prev = this.activeUndoGroupId;
1827
+ this.activeUndoGroupId = groupId;
1828
+ try {
1829
+ return fn();
1830
+ } finally {
1831
+ this.activeUndoGroupId = prev;
1832
+ }
1833
+ }
1834
+
1835
+ unwindUndoGroup(groupId: number): void {
1836
+ let earliestTextBefore: string | undefined;
1837
+ while (
1838
+ this.history.length > 0 &&
1839
+ this.history.at(-1)!.undoGroupId === groupId
1840
+ ) {
1841
+ earliestTextBefore = this.history.pop()!.textBefore;
1842
+ }
1843
+ if (earliestTextBefore !== undefined) {
1844
+ this.currentText = earliestTextBefore;
1845
+ }
1846
+ }
1847
+
1674
1848
  apply(op: AnimationSourceOp): AppliedAnimationOpsResult {
1675
1849
  const last = this.history.at(-1);
1850
+
1851
+ // Coalesce a set_key_value into a trailing insert_key on the same (animation, track)
1852
+ // only within the same explicit undo group (e.g. stage bone drag on an unkeyed frame).
1853
+ if (
1854
+ last !== undefined &&
1855
+ this.activeUndoGroupId !== undefined &&
1856
+ last.undoGroupId === this.activeUndoGroupId &&
1857
+ last.op.op === 'insert_key' &&
1858
+ op.op === 'set_key_value' &&
1859
+ last.op.animation === op.animation &&
1860
+ last.op.track === op.track
1861
+ ) {
1862
+ const { classification, keys } = resolveEditableTrack(
1863
+ this.currentText,
1864
+ op.animation,
1865
+ op.track,
1866
+ );
1867
+ const targetKey = keys[op.key];
1868
+ if (targetKey && targetKey.t === cleanMotionNumber(last.op.time)) {
1869
+ const channels = classification.channels;
1870
+ const nextValues = [...last.op.value];
1871
+ if (op.channel !== undefined) {
1872
+ if (
1873
+ !Number.isInteger(op.channel) ||
1874
+ op.channel < 0 ||
1875
+ op.channel >= channels ||
1876
+ typeof op.value !== 'number' ||
1877
+ !Number.isFinite(op.value)
1878
+ ) {
1879
+ throw new Error(
1880
+ `ANIMATION_VALUE_INVALID: expected finite number for channel ${String(op.channel)}`,
1881
+ );
1882
+ }
1883
+ nextValues[op.channel] = cleanMotionNumber(op.value);
1884
+ } else if (
1885
+ Array.isArray(op.value) &&
1886
+ op.value.length === channels &&
1887
+ op.value.every((n) => typeof n === 'number' && Number.isFinite(n))
1888
+ ) {
1889
+ for (let c = 0; c < channels; c++) {
1890
+ nextValues[c] = cleanMotionNumber(op.value[c]!);
1891
+ }
1892
+ } else {
1893
+ throw new Error(
1894
+ `ANIMATION_VALUE_INVALID: expected array of ${channels} finite number(s)`,
1895
+ );
1896
+ }
1897
+ const replayFrom = last.textBefore;
1898
+ const coalescedInsert: AnimationSourceOp = {
1899
+ ...last.op,
1900
+ value: nextValues,
1901
+ };
1902
+ const res = applyAnimationOp(
1903
+ replayFrom,
1904
+ coalescedInsert,
1905
+ this.baseText,
1906
+ this.fallbackEasings,
1907
+ );
1908
+ this.history.pop();
1909
+ this.history.push({
1910
+ op: coalescedInsert,
1911
+ textBefore: replayFrom,
1912
+ undoGroupId: this.activeUndoGroupId,
1913
+ explicitGroup: this.explicitGroupDepth > 0,
1914
+ });
1915
+ this.currentText = res.text;
1916
+ return res;
1917
+ }
1918
+ }
1919
+
1676
1920
  const sameKeyTarget =
1677
1921
  last !== undefined &&
1922
+ last.undoGroupId === this.activeUndoGroupId &&
1678
1923
  last.op.animation === op.animation &&
1679
1924
  last.op.track === op.track &&
1680
1925
  'key' in last.op &&
@@ -1684,47 +1929,270 @@ export class AnimationOpBuilder {
1684
1929
  if (
1685
1930
  sameKeyTarget &&
1686
1931
  ((op.op === 'set_key_time' && last.op.op === 'set_key_time') ||
1687
- (op.op === 'set_key_value' && last.op.op === 'set_key_value'))
1932
+ (op.op === 'set_key_value' && last.op.op === 'set_key_value') ||
1933
+ ((op.op === 'set_key_curve' || op.op === 'set_key_ease') &&
1934
+ (last.op.op === 'set_key_curve' || last.op.op === 'set_key_ease')))
1688
1935
  ) {
1689
1936
  const replayFrom = last.textBefore;
1690
1937
  const coalescedOp =
1691
1938
  op.op === 'set_key_value' && last.op.op === 'set_key_value'
1692
1939
  ? coalesceSetKeyValueOp(replayFrom, last.op, op)
1693
1940
  : op;
1694
- const res = applyAnimationOp(replayFrom, coalescedOp, this.baseText);
1941
+ const res = applyAnimationOp(replayFrom, coalescedOp, this.baseText, this.fallbackEasings);
1695
1942
  this.history.pop();
1696
- if (res.text === this.baseText) {
1697
- this.history.length = 0;
1698
- this.currentText = this.baseText;
1699
- return { text: this.baseText, changedSpans: [] };
1700
- }
1701
1943
  if (res.text === replayFrom) {
1702
1944
  this.currentText = replayFrom;
1703
1945
  return { text: replayFrom, changedSpans: [] };
1704
1946
  }
1705
- this.history.push({ op: coalescedOp, textBefore: replayFrom });
1947
+ this.history.push({
1948
+ op: coalescedOp,
1949
+ textBefore: replayFrom,
1950
+ undoGroupId: this.activeUndoGroupId,
1951
+ explicitGroup: this.explicitGroupDepth > 0,
1952
+ });
1706
1953
  this.currentText = res.text;
1707
1954
  return res;
1708
1955
  }
1709
1956
 
1710
- const res = applyAnimationOp(this.currentText, op, this.baseText);
1711
- if (res.text === this.baseText) {
1712
- this.history.length = 0;
1713
- this.currentText = this.baseText;
1714
- return { text: this.baseText, changedSpans: [] };
1715
- }
1957
+ const res = applyAnimationOp(this.currentText, op, this.baseText, this.fallbackEasings);
1716
1958
  if (res.text === this.currentText) {
1717
1959
  return { text: this.currentText, changedSpans: [] };
1718
1960
  }
1719
- this.history.push({ op, textBefore: this.currentText });
1961
+ if (this.history.length >= MAX_ANIMATION_OPS) {
1962
+ throw new Error(
1963
+ `ANIMATION_OPS_TOO_MANY: animation "${op.animation}" track ${op.track} operation "${op.op}" exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
1964
+ );
1965
+ }
1966
+ this.history.push({
1967
+ op,
1968
+ textBefore: this.currentText,
1969
+ undoGroupId: this.activeUndoGroupId,
1970
+ explicitGroup: this.explicitGroupDepth > 0,
1971
+ });
1720
1972
  this.currentText = res.text;
1721
1973
  return res;
1722
1974
  }
1723
1975
 
1976
+ /**
1977
+ * Move a selection of `(track, key)` pairs in `animation` by `deltaTime` seconds
1978
+ * atomically as a single undo group. When `deltaTime > 0`, keys on the same track are moved
1979
+ * from right to left so an earlier key does not collide with its not-yet-moved right neighbor;
1980
+ * when `deltaTime < 0`, from left to right. Refuses with `ANIMATION_OPS_TOO_MANY` (restoring
1981
+ * the builder's prior state) if the move would exceed `MAX_ANIMATION_OPS`.
1982
+ */
1983
+ moveSelection(
1984
+ animation: string,
1985
+ selections: ReadonlyArray<{ track: number; key: number }>,
1986
+ deltaTime: number,
1987
+ ): AppliedAnimationOpsResult {
1988
+ if (!Number.isFinite(deltaTime)) {
1989
+ throw new Error(`ANIMATION_KEY_TIME_INVALID: animation "${animation}" deltaTime must be finite, got ${String(deltaTime)}`);
1990
+ }
1991
+ if (selections.length === 0 || deltaTime === 0) {
1992
+ return { text: this.currentText, changedSpans: [] };
1993
+ }
1994
+ const byTrack = new Map<number, number[]>();
1995
+ for (const sel of selections) {
1996
+ let arr = byTrack.get(sel.track);
1997
+ if (!arr) {
1998
+ arr = [];
1999
+ byTrack.set(sel.track, arr);
2000
+ }
2001
+ if (!arr.includes(sel.key)) arr.push(sel.key);
2002
+ }
2003
+ const totalSelected = [...byTrack.values()].reduce((acc, a) => acc + a.length, 0);
2004
+ if (totalSelected > MAX_ANIMATION_OPS) {
2005
+ throw new Error(
2006
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection move of ${totalSelected} keys exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2007
+ );
2008
+ }
2009
+ const savedText = this.currentText;
2010
+ const savedHistory = this.history.map((h) => ({ ...h }));
2011
+ const changedSpans: { start: number; end: number }[] = [];
2012
+ try {
2013
+ const sortedTracks = [...byTrack.keys()].sort((a, b) => a - b);
2014
+ const targetTimes = new Map<string, number>();
2015
+ for (const track of sortedTracks) {
2016
+ const { classification, keys } = resolveEditableTrack(this.currentText, animation, track);
2017
+ for (const key of byTrack.get(track)!) {
2018
+ const k = keys[key];
2019
+ if (!k) {
2020
+ throw new Error(
2021
+ `ANIMATION_KEY_OUT_OF_RANGE: animation "${animation}" track ${track} ("${classification.target}.${classification.property}") key index ${key} out of [0, ${keys.length - 1}]`,
2022
+ );
2023
+ }
2024
+ targetTimes.set(`${track}:${key}`, cleanMotionNumber(k.t + deltaTime));
2025
+ }
2026
+ }
2027
+
2028
+ // Coalesce with a trailing batch of set_key_time ops on the exact same selection and undo context
2029
+ const last = this.history.at(-1);
2030
+ let suffixStart = this.history.length;
2031
+ let existingGroupId: number | undefined;
2032
+ const canTryCoalesce =
2033
+ last !== undefined &&
2034
+ last.undoGroupId !== undefined &&
2035
+ (this.activeUndoGroupId !== undefined
2036
+ ? last.undoGroupId === this.activeUndoGroupId
2037
+ : !last.explicitGroup);
2038
+ if (canTryCoalesce) {
2039
+ const candidateGroupId = last.undoGroupId!;
2040
+ const matchedTargets = new Set<string>();
2041
+ let candidateStart = this.history.length;
2042
+ let validBatch = true;
2043
+ while (
2044
+ candidateStart > 0 &&
2045
+ this.history[candidateStart - 1]!.undoGroupId === candidateGroupId
2046
+ ) {
2047
+ const prev = this.history[candidateStart - 1]!.op;
2048
+ const targetKey = `${prev.track}:${'key' in prev ? prev.key : -1}`;
2049
+ if (
2050
+ prev.op === 'set_key_time' &&
2051
+ prev.animation === animation &&
2052
+ targetTimes.has(targetKey) &&
2053
+ !matchedTargets.has(targetKey)
2054
+ ) {
2055
+ matchedTargets.add(targetKey);
2056
+ candidateStart--;
2057
+ } else {
2058
+ validBatch = false;
2059
+ break;
2060
+ }
2061
+ }
2062
+ if (validBatch && matchedTargets.size === targetTimes.size) {
2063
+ suffixStart = candidateStart;
2064
+ existingGroupId = candidateGroupId;
2065
+ }
2066
+ }
2067
+ if (suffixStart < this.history.length) {
2068
+ this.currentText = this.history[suffixStart]!.textBefore;
2069
+ this.history.length = suffixStart;
2070
+ }
2071
+ if (this.history.length + totalSelected > MAX_ANIMATION_OPS) {
2072
+ throw new Error(
2073
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection move of ${totalSelected} keys with ${this.history.length} pending op(s) exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2074
+ );
2075
+ }
2076
+
2077
+ const groupId = this.activeUndoGroupId ?? existingGroupId ?? this.beginUndoGroup();
2078
+ this.withInternalUndoGroup(groupId, () => {
2079
+ for (const track of sortedTracks) {
2080
+ const { keys } = resolveEditableTrack(this.currentText, animation, track);
2081
+ const keyIndices = [...byTrack.get(track)!].sort((a, b) => {
2082
+ const shiftA = targetTimes.get(`${track}:${a}`)! - keys[a]!.t;
2083
+ return shiftA >= 0 ? b - a : a - b;
2084
+ });
2085
+ for (const key of keyIndices) {
2086
+ const res = this.apply({
2087
+ op: 'set_key_time',
2088
+ animation,
2089
+ track,
2090
+ key,
2091
+ time: targetTimes.get(`${track}:${key}`)!,
2092
+ });
2093
+ changedSpans.push(...res.changedSpans);
2094
+ }
2095
+ }
2096
+ });
2097
+ return { text: this.currentText, changedSpans };
2098
+ } catch (err) {
2099
+ this.currentText = savedText;
2100
+ this.history.length = 0;
2101
+ this.history.push(...savedHistory);
2102
+ throw err;
2103
+ }
2104
+ }
2105
+
2106
+ /**
2107
+ * Delete a selection of `(track, key)` pairs in `animation` atomically as a single undo group.
2108
+ * Keys on the same track are deleted in descending index order so earlier indices remain stable.
2109
+ * Refuses with `ANIMATION_TRACK_MIN_KEYS` if any track would be left with `< 1` key, and
2110
+ * `ANIMATION_OPS_TOO_MANY` if the total pending ops would exceed `MAX_ANIMATION_OPS`.
2111
+ */
2112
+ deleteSelection(
2113
+ animation: string,
2114
+ selections: ReadonlyArray<{ track: number; key: number }>,
2115
+ ): AppliedAnimationOpsResult {
2116
+ if (selections.length === 0) {
2117
+ return { text: this.currentText, changedSpans: [] };
2118
+ }
2119
+ const byTrack = new Map<number, number[]>();
2120
+ for (const sel of selections) {
2121
+ let arr = byTrack.get(sel.track);
2122
+ if (!arr) {
2123
+ arr = [];
2124
+ byTrack.set(sel.track, arr);
2125
+ }
2126
+ if (!arr.includes(sel.key)) arr.push(sel.key);
2127
+ }
2128
+ const sortedTracks = [...byTrack.keys()].sort((a, b) => a - b);
2129
+ let totalSelected = 0;
2130
+ for (const track of sortedTracks) {
2131
+ const { classification, keys } = resolveEditableTrack(this.currentText, animation, track);
2132
+ const trackLabel = `animation "${animation}" track ${track} ("${classification.target}.${classification.property}")`;
2133
+ const keyIndices = [...byTrack.get(track)!].sort((a, b) => b - a);
2134
+ for (const k of keyIndices) {
2135
+ if (!Number.isInteger(k) || k < 0 || k >= keys.length) {
2136
+ throw new Error(
2137
+ `ANIMATION_KEY_OUT_OF_RANGE: ${trackLabel} key index ${k} out of [0, ${keys.length - 1}]`,
2138
+ );
2139
+ }
2140
+ }
2141
+ if (keys.length - keyIndices.length < 1) {
2142
+ throw new Error(
2143
+ `ANIMATION_TRACK_MIN_KEYS: ${trackLabel} cannot delete ${keyIndices.length} of ${keys.length} key(s); cannot delete the only key on a track`,
2144
+ );
2145
+ }
2146
+ byTrack.set(track, keyIndices);
2147
+ totalSelected += keyIndices.length;
2148
+ }
2149
+ if (this.history.length + totalSelected > MAX_ANIMATION_OPS) {
2150
+ throw new Error(
2151
+ `ANIMATION_OPS_TOO_MANY: animation "${animation}" selection delete of ${totalSelected} keys with ${this.history.length} pending op(s) exceeds MAX_ANIMATION_OPS (${MAX_ANIMATION_OPS})`,
2152
+ );
2153
+ }
2154
+
2155
+ const savedText = this.currentText;
2156
+ const savedHistory = this.history.map((h) => ({ ...h }));
2157
+ const changedSpans: { start: number; end: number }[] = [];
2158
+ try {
2159
+ const groupId = this.activeUndoGroupId ?? this.beginUndoGroup();
2160
+ this.withInternalUndoGroup(groupId, () => {
2161
+ for (const track of sortedTracks) {
2162
+ const keyIndices = byTrack.get(track)!;
2163
+ for (const key of keyIndices) {
2164
+ const res = this.apply({
2165
+ op: 'delete_key',
2166
+ animation,
2167
+ track,
2168
+ key,
2169
+ });
2170
+ changedSpans.push(...res.changedSpans);
2171
+ }
2172
+ }
2173
+ });
2174
+ return { text: this.currentText, changedSpans };
2175
+ } catch (err) {
2176
+ this.currentText = savedText;
2177
+ this.history.length = 0;
2178
+ this.history.push(...savedHistory);
2179
+ throw err;
2180
+ }
2181
+ }
2182
+
1724
2183
  undo(): boolean {
1725
2184
  const last = this.history.pop();
1726
2185
  if (!last) return false;
1727
- this.currentText = last.textBefore;
2186
+ let earliestTextBefore = last.textBefore;
2187
+ if (last.undoGroupId !== undefined) {
2188
+ while (
2189
+ this.history.length > 0 &&
2190
+ this.history.at(-1)!.undoGroupId === last.undoGroupId
2191
+ ) {
2192
+ earliestTextBefore = this.history.pop()!.textBefore;
2193
+ }
2194
+ }
2195
+ this.currentText = earliestTextBefore;
1728
2196
  return true;
1729
2197
  }
1730
2198
 
@@ -1739,10 +2207,21 @@ export class AnimationOpBuilder {
1739
2207
  // Pending-preview adapter into src/animation-inspection.ts (Correction 7)
1740
2208
  // ---------------------------------------------------------------------------
1741
2209
 
2210
+ const KEY_TIME_GRID = 360000;
2211
+
1742
2212
  function f32(n: number): number {
1743
2213
  return Math.fround(n);
1744
2214
  }
1745
2215
 
2216
+ /**
2217
+ * Match `@rig-c/core/src/compile.ts` `keyTime(n)`: snap times within 5e-7 of the
2218
+ * 1/360000s grid before Float32 rounding so preview keys match compiled keys.
2219
+ */
2220
+ export function compiledKeyTime(n: number): number {
2221
+ const grid = Math.round(n * KEY_TIME_GRID) / KEY_TIME_GRID;
2222
+ return f32(Math.abs(n - grid) <= 5e-7 ? grid : n);
2223
+ }
2224
+
1746
2225
  function resolveKeyCurveForInspection(
1747
2226
  key: { t: number; v: readonly number[]; ease?: string; curve?: readonly number[] | 'stepped' },
1748
2227
  nextKey: { t: number; v: readonly number[] } | undefined,
@@ -1750,7 +2229,7 @@ function resolveKeyCurveForInspection(
1750
2229
  ): number[] | 'stepped' | undefined {
1751
2230
  if (!nextKey) return undefined;
1752
2231
  if (key.curve !== undefined) {
1753
- return key.curve === 'stepped' ? 'stepped' : [...key.curve];
2232
+ return key.curve === 'stepped' ? 'stepped' : key.curve.map(f32);
1754
2233
  }
1755
2234
  if (key.ease === undefined) return undefined;
1756
2235
  if (key.ease === 'stepped') return 'stepped';
@@ -1766,10 +2245,10 @@ function resolveKeyCurveForInspection(
1766
2245
  const v1 = key.v[c]!;
1767
2246
  const dv = nextKey.v[c]! - v1;
1768
2247
  out.push(
1769
- cleanMotionNumber(key.t + dt * hx1),
1770
- cleanMotionNumber(v1 + dv * hy1),
1771
- cleanMotionNumber(key.t + dt * hx2),
1772
- cleanMotionNumber(v1 + dv * hy2),
2248
+ f32(key.t + dt * hx1),
2249
+ f32(v1 + dv * hy1),
2250
+ f32(key.t + dt * hx2),
2251
+ f32(v1 + dv * hy2),
1773
2252
  );
1774
2253
  }
1775
2254
  return out;
@@ -1799,9 +2278,9 @@ export function draftTrackToInspectionTrack(
1799
2278
  throw new Error(`ANIMATION_TRACK_READ_ONLY: unsupported bone property "${track.property}"`);
1800
2279
  }
1801
2280
  const storedKeys: StoredKey[] = track.keys.map((k, idx) => {
1802
- const entry: StoredKey = { time: k.t };
2281
+ const entry: StoredKey = { time: compiledKeyTime(k.t) };
1803
2282
  channelSpec.forEach((ch, c) => {
1804
- entry[ch.field] = k.v[c]!;
2283
+ entry[ch.field] = f32(k.v[c]!);
1805
2284
  });
1806
2285
  const curve = resolveKeyCurveForInspection(k, track.keys[idx + 1], easings);
1807
2286
  if (curve !== undefined) {
@@ -1826,6 +2305,7 @@ export function draftTrackToInspectionTrack(
1826
2305
  export function overlayDraftOnInspection(
1827
2306
  inspection: AnimationInspection,
1828
2307
  draftMotionText: string,
2308
+ fallbackEasings?: Readonly<Record<string, EasingTuple>>,
1829
2309
  ): AnimationInspection {
1830
2310
  const doc = JSON.parse(draftMotionText) as Record<string, unknown>;
1831
2311
  if (!isRecord(doc.animations)) return inspection;
@@ -1833,9 +2313,13 @@ export function overlayDraftOnInspection(
1833
2313
  if (!isRecord(anim) || !Array.isArray(anim.tracks)) return inspection;
1834
2314
  const rawTracks = anim.tracks as unknown[];
1835
2315
 
1836
- const easings = isRecord(doc.easings)
1837
- ? (doc.easings as Readonly<Record<string, EasingTuple>>)
1838
- : undefined;
2316
+ const easings: Readonly<Record<string, EasingTuple>> | undefined =
2317
+ isRecord(doc.easings) || fallbackEasings
2318
+ ? {
2319
+ ...(fallbackEasings ?? {}),
2320
+ ...(isRecord(doc.easings) ? (doc.easings as Readonly<Record<string, EasingTuple>>) : {}),
2321
+ }
2322
+ : undefined;
1839
2323
  const classifications = classifyAnimationTracks(doc, inspection.name);
1840
2324
  const replacementByKey = new Map<string, InspectionTrack>();
1841
2325