8000 fix(timeline): MATCH-snap on cam-track drag by johannboehme · Pull Request #35 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions frontend/src/editor/components/Timeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ import { BeatRuler } from "./timeline/BeatRuler";
import { BpmReadout } from "./BpmReadout";
import { SnapModeButtons } from "./SnapModeButtons";
import { snapTime, type SnapCtx, type SnapMode } from "../snap";
import {
buildClipMatchPositions,
candidateIdxNearestStart,
} from "../match-snap";
import {
effectiveBeatPhaseS,
effectiveBeatsPerBar,
Expand Down Expand Up @@ -94,11 +98,19 @@ type DragKind =
/** MATCH snap-mode pill-body drag. The whole cam track moves —
* every pill of `camId` shifts by the same arr-delta so the
* user can align the entire take against a candidate's
* master-time tick (visible as the match-marker). */
* master-time tick (visible as the match-marker). When MATCH
* is active, the drag locks to the nearest candidate-implied
* master-startS instead of free-dragging. */
kind: "cam-track-move";
camId: string;
grabArrT: number;
origStartsByPillId: Record<string, number>;
/** Cam's master-startS at drag-start (= -(syncOffsetMs +
* syncOverrideMs)/1000). Stable through any candidate-switch
* that happens mid-drag — without this freeze the candidate
* positions would shift under the user's pointer and middle
* candidates become unreachable. */
origMasterStartS: number;
}
| {
/** Drag a pill's LEFT edge — narrows the arr-window from the
Expand Down Expand Up @@ -212,6 +224,9 @@ export function Timeline({
const resetClipAlignment = useEditorStore((s) => s.resetClipAlignment);
const resetPillsForCam = useEditorStore((s) => s.resetPillsForCam);
const resetPill = useEditorStore((s) => s.resetPill);
const setSelectedCandidateIdx = useEditorStore(
(s) => s.setSelectedCandidateIdx,
);
const removeCutAt = useEditorStore((s) => s.removeCutAt);
const clearCuts = useEditorStore((s) => s.clearCuts);
const clearAllFx = useEditorStore((s) => s.clearAllFx);
Expand Down Expand Up @@ -1233,11 +1248,17 @@ export function Timeline({
origStartsByPillId[sib.id] = sib.arrStartS;
}
}
const camClip = clips.find((c) => c.id === p.camId);
const origMasterStartS =
camClip && isVideoClip(camClip)
? -(camClip.syncOffsetMs + camClip.syncOverrideMs) / 1000
: 0;
dragRef.current = {
kind: "cam-track-move",
camId: p.camId,
grabArrT: arrAtGrab,
origStartsByPillId,
origMasterStartS,
};
} else {
dragRef.current = {
Expand Down Expand Up @@ -1390,13 +1411,43 @@ export function Timeline({
}
setPillArrPlacement(drag.pillId, newArrStartS);
} else if (drag.kind === "cam-track-move") {
// Cam-track move (MATCH snap-mode body drag) — apply the same
// arr-delta to every pill of `camId` from its drag-start
// snapshot. Each pill keeps its own source-trim; only WHERE on
// the song each pill plays moves. Snapshot-based so the math
// doesn't cascade as we mutate the store mid-drag.
// Cam-track move — MATCH snap-mode body drag. The drag locks to
// the nearest candidate-implied master-startS: setSelectedCandidateIdx
// shifts the cam's syncOffsetMs to the candidate's value, and
// (post-pill-refactor) atomically slides every pill of this cam's
// source-time mapping by the same delta so the snap is visible in
// the rendered output. Shift bypasses to free-drag.
const arrAtPointer = viewStart + (x / canvasWidth) * visibleDur;
const deltaArrT = arrAtPointer - drag.grabArrT;
const camClip = clips.find((c) => c.id === drag.camId);
if (
snapMode === "match" &&
!e.shiftKey &&
camClip &&
isVideoClip(camClip) &&
camClip.candidates.length > 0
) {
// Drag-target master-startS, computed from the snapshot taken
// at drag-start so candidate-positions stay stable across mid-
// drag candidate switches (otherwise the math cascades and
// middle candidates become unreachable).
const targetStartS = drag.origMasterStartS + deltaArrT;
const positions = buildClipMatchPositions(camClip);
const nearestIdx = candidateIdxNearestStart(
positions,
targetStartS,
Infinity,
);
if (nearestIdx !== null && nearestIdx !== camClip.selectedCandidateIdx) {
setSelectedCandidateIdx(drag.camId, nearestIdx);
}
return;
}
// Non-MATCH (or shift-bypass): free-drag — apply the arr-delta to
// every pill of `camId` from its drag-start snapshot. Snapshot-
// based so the math doesn't cascade as we mutate the store mid-
// drag. Pills keep their own source-trim; only WHERE on the song
// each pill plays moves.
for (const [pillId, origStart] of Object.entries(
drag.origStartsByPillId,
)) {
Expand Down
73 changes: 73 additions & 0 deletions frontend/src/editor/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,79 @@ describe("useEditorStore", () => {
expect(c.syncOffsetMs).toBe(750);
});

test("setSelectedCandidateIdx shifts the cam's pill source-times by the offsetMs delta", () => {
// Pills are authoritative for source-time post-pill-refactor —
// changing syncOffsetMs alone is invisible unless we mirror the
// delta into pills. Without the shift the same arr-position
// would keep playing the OLD candidate's frames.
useEditorStore.getState().loadJob(baseJobMeta, {
clips: [
{
id: "cam-1",
filename: "a.mp4",
color: "#fff",
sourceDurationS: 10,
syncOffsetMs: 250,
candidates: cands,
},
],
// Synthetic single-take arrangement (mirrors what
// synthesizeJobLoadShape produces in production), needed so
// reconcilePills generates fresh pills that the storedPill
// can latch onto.
arrangementSegments: [{ in: 0, out: 60 }],
arrangement: [{ id: "__default__", chunkId: "__default_chunk__" }],
chunks: [
{
id: "__default_chunk__",
startMs: 0,
endMs: 60_000,
bpmOctaveShift: 0,
effectiveBpm: 0,
beatsPerBar: 4,
accepted: true,
trimMode: "free",
},
],
// Pre-existing user-edited pill at sourceIn=2, sourceOut=5.
storedPills: [
{
id: "cam-1::__default__",
camId: "cam-1",
arrStartS: 0,
arrEndS: 3,
sourceInS: 2,
sourceOutS: 5,
originalArrStartS: 0,
originalArrEndS: 3,
originalSourceInS: 2,
originalSourceOutS: 5,
fromArrangementItemId: "__default__",
userEdited: true,
},
],
});
// Switch to candidate idx=1 (offsetMs 750, delta from 250 = +500ms)
// → pills should shift source-times by +0.5s.
// Capture pre-snap originals (refreshed by reconcilePills from
// the current clip-state during loadJob — not the storedPill's
// values).
const before = useEditorStore.getState().pills[0];
const origInBefore = before.originalSourceInS;
const origOutBefore = before.originalSourceOutS;
// Switch to candidate idx=1 (offsetMs 750, delta from 250 = +500ms)
// → pills should shift source-times by +0.5s.
useEditorStore.getState().setSelectedCandidateIdx("cam-1", 1);
const p = useEditorStore.getState().pills[0];
expect(p.sourceInS).toBeCloseTo(2.5, 6);
expect(p.sourceOutS).toBeCloseTo(5.5, 6);
// Originals also shift so a per-pill RESET targets the post-snap
// baseline (= where the cam now belongs after the candidate
// switch).
expect(p.originalSourceInS).toBeCloseTo(origInBefore + 0.5, 6);
expect(p.originalSourceOutS).toBeCloseTo(origOutBefore + 0.5, 6);
});

test("loadJob without candidates leaves array empty and idx=0", () => {
useEditorStore.getState().loadJob(baseJobMeta, {
clips: [
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/editor/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1582,6 +1582,9 @@ export const useEditorStore = create<EditorState>()(
set({ jobMeta: { ...meta, barOffsetBeats: off } });
},
setSelectedCandidateIdx(camId, idx) {
const prev = get().clips.find((c) => c.id === camId);
if (!prev || !isVideoClip(prev)) return;
const prevOffsetMs = prev.syncOffsetMs;
set({
clips: mutateClip(get().clips, camId, (c) => {
if (!isVideoClip(c)) return c; // image clips have no candidates
Expand All @@ -1590,6 +1593,29 @@ export const useEditorStore = create<EditorState>()(
return { ...c, selectedCandidateIdx: clamped, syncOffsetMs: newOffset };
}),
});
// The candidate-switch shifts the cam's master-anchor — every
// pill of this cam needs its source-time mapping shifted by the
// same delta so the same arr-position plays the right source
// frames at the new alignment. Without this, pills (which are
// authoritative for source-time post-pill-refactor) keep playing
// the OLD candidate's frames and the snap is invisible. Mirrors
// what `setClipSyncOverride` does for syncOverrideMs nudges.
const next = get().clips.find((c) => c.id === camId);
if (!next || !isVideoClip(next)) return;
const deltaMs = next.syncOffsetMs - prevOffsetMs;
if (Math.abs(deltaMs) > 1e-6) {
const deltaS = deltaMs / 1000;
set({
pills: mutatePillsForCam(get().pills, camId, (p) => ({
...shiftPillSource(p, deltaS),
originalSourceInS: Math.max(0, p.originalSourceInS + deltaS),
originalSourceOutS: Math.max(
p.originalSourceInS + 0.05,
p.originalSourceOutS + deltaS,
),
})),
});
}
},

setSelectedClipId(id) {
Expand Down
Loading
0