commit 2655e4650ffc1a6b882edcb543f1fc4acb305ccd
parent 67a183914fe8940e9da2ff90151b535a8c915a05
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 21:22:46 -0500
Merge branch 'main' into lane/one-clock
Diffstat:
35 files changed, 2255 insertions(+), 193 deletions(-)
diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts
@@ -3,6 +3,7 @@ import { ensureWindowFile, projectCache, resolveClip, segmentFor, windowVersion,
import { takeToken } from "@/lib/report/takeEdit.mjs";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { cuesInWindow, readClipDetail, siblingsOf } from "@/lib/projects/report.mjs";
+import { gapWalls } from "umtool-report-to-video/gaps";
export const dynamic = "force-dynamic";
@@ -69,10 +70,18 @@ export async function GET(request: Request) {
muteFrom: clip.muteFrom ?? null,
// Seconds cut out of its middle (gaps.mjs).
gaps: Array.isArray(clip.gaps) ? clip.gaps : [],
+ // The seconds no gap may cover: each claim mark's or stamp's `at` (gaps.mjs gapWalls).
+ marks: gapWalls({ ...clip, type: "clip", muteFrom: null }).marks.map((m) => ({ id: m.id, at: m.at })),
// What the walk said that is not a verdict, and a deliberate repeat.
walkNote: typeof clip.walkNote === "string" ? clip.walkNote : null,
star: clip.star === true,
repeatOf: typeof clip.repeatOf === "string" ? clip.repeatOf : null,
+ // The rest of what the bench holds, so a page come back to (the back
+ // button, lane/clip-fixes) can take the clip as it is now, not as it was.
+ verdict: clip.verdict === "confirmed" || clip.verdict === "incorrect" || clip.verdict === "rejected" ? clip.verdict : null,
+ reason: typeof clip.reason === "string" ? clip.reason : null,
+ rejectNote: typeof clip.rejectNote === "string" ? clip.rejectNote : null,
+ onscreen: clip.onscreen ?? null,
},
view,
// `v`: the version of each window's bytes, for the media URLs -- a refetch
diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts
@@ -1,6 +1,6 @@
import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import {
- FETCH_MAX_PAD,
+ FETCH_MAX_WINDOW,
editorFetchSteps,
editorFullSourceSteps,
fetchSteps,
@@ -22,7 +22,8 @@ export const dynamic = "force-dynamic";
// and containing-window reuse then makes this generous fetch BE the build's
// cache rather than a second one.
-const MAX_PAD = FETCH_MAX_PAD;
+/** A fetched window, end to end, is at most this wide (the editor's cap). */
+const MAX_WINDOW = FETCH_MAX_WINDOW;
/** Same tolerance the build uses for "this file holds that window". */
const WIN_EPS = 0.02;
@@ -33,9 +34,13 @@ export async function POST(request: Request) {
// ONE EDGE AT A TIME. `pad` stays the symmetric shorthand; the bench sends
// the side it is extending and the side it already has, so a fetch never
// quietly re-downloads twenty seconds of lead-in nobody asked for.
- const side = (v: unknown, fallback: number) =>
- Math.max(0, Math.min(MAX_PAD, Number(v ?? fallback)));
- const pad = Math.max(1, Math.min(MAX_PAD, Number(body.pad ?? 20)));
+ // No cap per side: the WINDOW is capped, end to end, below -- an edge dragged
+ // far from where it was saved needs a pad far bigger than any fixed side cap.
+ const side = (v: unknown, fallback: number) => {
+ const n = Number(v ?? fallback);
+ return Number.isFinite(n) ? Math.max(0, n) : fallback;
+ };
+ const pad = Math.max(1, side(body.pad, 20));
const padBefore = side(body.padBefore, pad);
const padAfter = side(body.padAfter, pad);
@@ -107,6 +112,20 @@ export async function POST(request: Request) {
from: Math.max(0, Number(r.clip.start) - padBefore),
to: Number(r.clip.end) + padAfter,
};
+ // The editor fetches a window of at most MAX_WINDOW seconds (wider is the
+ // whole recording); say so here, with the numbers, rather than queue a job
+ // the editor refuses.
+ if (!wantFull && want.to - want.from > MAX_WINDOW + WIN_EPS) {
+ return Response.json(
+ {
+ error:
+ `a fetched window is at most ${MAX_WINDOW} s end to end (asked for ${Math.round(want.to - want.from)} s) — ` +
+ "fetch the whole source for more",
+ maxWindow: MAX_WINDOW,
+ },
+ { status: 400 },
+ );
+ }
const holds = windows.find((w) => w.from <= want.from + WIN_EPS && w.to >= want.to - WIN_EPS);
if (holds) {
// What is already there, PER SIDE, in the pads the bench speaks in.
@@ -115,15 +134,12 @@ export async function POST(request: Request) {
return Response.json(
{
error:
- `already cached to −${haveBefore} s / +${haveAfter} s — ask for more on one side` +
- (padBefore >= MAX_PAD || padAfter >= MAX_PAD
- ? ` (${MAX_PAD} s is the widest one side goes)`
- : ""),
+ `already cached to −${haveBefore} s / +${haveAfter} s — ask for more on one side`,
cachedBefore: haveBefore,
cachedAfter: haveAfter,
/** The narrower side, for a caller that speaks in one number. */
cachedPad: Math.min(haveBefore, haveAfter),
- maxPad: MAX_PAD,
+ maxWindow: MAX_WINDOW,
},
{ status: 409 },
);
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -33,9 +33,10 @@ import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenToo
import { attributionLine } from "umtool-report-to-video/attribution";
import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs";
// Gaps inside a clip: the rule (the writer's and the build's) and the pieces that play.
-import { gapSpan, gappedLength, validateGaps } from "umtool-report-to-video/gaps";
+import { gapSpan, gapWalls, gappedLength, validateGaps } from "umtool-report-to-video/gaps";
import { useGapEditor } from "./bench/useGapEditor";
import { BenchWaveBox, GapTools } from "./bench/BenchWave";
+import { CutEdges } from "./bench/CutEdges";
import { sourceWindowMedia } from "./bench/benchMedia";
import { useBenchPlayer } from "./bench/useBenchPlayer";
import { usePeaks } from "./bench/usePeaks";
@@ -142,6 +143,12 @@ type Clip = {
* not drafted like the edges; every playback here skips them.
*/
gaps: Span[];
+ /**
+ * The seconds no gap may cover (lane/clip-fixes): each claim mark's or
+ * stamp's `at` (`claims`, else `claim`; gaps.mjs gapWalls), read so the
+ * bench's check of a gap is the writer's whole rule, not most of it.
+ */
+ marks: { id: string | null; at: number }[];
/** "confirmed" / "incorrect" / "rejected", or null for "nobody has looked at this yet". */
verdict: "confirmed" | "incorrect" | "rejected" | null;
/** An editorial note from the walk -- not a correction (a fact error). Never rendered. */
@@ -212,6 +219,12 @@ const attribValue = (c: Clip, k: AttribKey): string =>
const emptyDraft = (c: Clip) =>
Object.fromEntries(ATTRIB.map(([k]) => [k, attribValue(c, k)])) as Record<AttribKey, string>;
+/** An entry's claim marks' and stamp's seconds (gapWalls), as the bench holds them. */
+const marksOf = (e: Record<string, unknown>): Clip["marks"] =>
+ gapWalls({ ...e, type: "clip", muteFrom: null })
+ .marks.filter((m) => m.kind !== "mute")
+ .map((m) => ({ id: m.id, at: m.at }));
+
/**
* A saved entry, back into the shape this component holds.
*
@@ -238,6 +251,7 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({
lockCut: !!e.lockCut,
muteFrom: e.muteFrom == null ? null : Number(e.muteFrom),
gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [],
+ marks: Array.isArray(e.marks) ? (e.marks as Clip["marks"]) : marksOf(e),
verdict: e.verdict === "confirmed" || e.verdict === "incorrect" || e.verdict === "rejected" ? e.verdict : null,
walkNote: (e.walkNote as string) ?? null,
star: e.star === true,
@@ -294,8 +308,8 @@ export type ClipBenchData = {
cues: Cue[];
token: string | null;
fetchPad: number;
- /** The widest pad `/api/report/fetch` will accept. */
- maxPad: number;
+ /** The widest window `/api/report/fetch` will ask for, end to end, in seconds (the editor's cap). */
+ maxWindow: number;
/** A /mix deep link for this clip's cached window, or null. Server-built. */
mixHref: string | null;
/** Every other clip in the cut from this same recording, by start. */
@@ -1285,25 +1299,140 @@ export default function ClipBench({
// -- and leaves an undo point (auto-before-gaps) -- and Undo here writes the
// list back as it was. The rule is checked here first, with the same
// sentences, so a refusal is said before anything is sent.
- const gapRefusal = useCallback(
- (gaps: Span[]) => {
- const errs = validateGaps({ type: "clip", id: clip.id, start: clip.start, end: clip.end, cutStart: clip.cutStart, cutEnd: clip.cutEnd, muteFrom: clip.muteFrom, gaps }, "gap");
+ //
+ // WHERE A GAP MAY GO (lane/clip-fixes): the cut when the clip has one, else
+ // the extent AS DRAFTED -- an edge dragged out over a wider fetch is where
+ // the operator is cutting, and the window patch rides along with the gap's
+ // write (as it does with a Confirm), so the writer checks the gap against
+ // the extent it will have. Before, the saved extent was a wall the drag
+ // stopped at with nothing on screen to say so.
+ const draftEntry = useMemo(
+ () => ({
+ type: "clip" as const,
+ id: clip.id,
+ start: windowMoved ? round2(sel.from) : clip.start,
+ end: windowMoved ? round2(sel.to) : clip.end,
+ cutStart: clip.cutStart,
+ cutEnd: clip.cutEnd,
+ muteFrom: windowMoved || muteMoved ? mute : clip.muteFrom,
+ // The marks too: the writer refuses a gap over one, so the check here does.
+ claims: (clip.marks ?? []).map((m) => (m.id ? { id: m.id, at: m.at } : { at: m.at })),
+ }),
+ [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom, clip.marks, windowMoved, muteMoved, sel.from, sel.to, mute],
+ );
+ const gapsSpan = gapSpan(draftEntry);
+ // Every wall a gap stops at, drawn (bench/GapsZoom.tsx GapWallsLayer).
+ const walls = useMemo(() => gapWalls({ ...draftEntry, gaps: clip.gaps ?? [] }), [draftEntry, clip.gaps]);
+ const gapRefusalFor = useCallback(
+ (gaps: Span[], over: Partial<typeof draftEntry> = {}) => {
+ const errs = validateGaps({ ...draftEntry, ...over, gaps }, "gap");
return errs.length ? errs[0].replace(/^gap\.gaps\[\d+\] /, "the gap ").replace(/^gap\.muteFrom/, "the mute mark").replace(/^gap: /, "") : null;
},
- [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom],
+ [draftEntry],
);
+ const gapRefusal = useCallback((gaps: Span[]) => gapRefusalFor(gaps), [gapRefusalFor]);
+ /** A cut narrower than the extent: the wall a gap (and the video) stops at. */
+ const hasCut = clip.cutStart != null && clip.cutEnd != null;
+ const cutNarrower = hasCut && (clip.cutStart! > sel.from + 0.05 || clip.cutEnd! < sel.to - 0.05);
// bench/useGapEditor.ts, writing through the window writer: `gapAdd` / `gapRemove`, Undo the whole list.
const gap = useGapEditor({
key: clip.id,
gaps: clip.gaps ?? [],
- span: gapSpan(clip),
+ span: gapsSpan,
refusal: gapRefusal,
- write: (op, _next) => save("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }),
- said: (next) => `the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`,
+ write: async (op, _next) => {
+ // A moved edge rides along: the gap was checked against the extent as drafted.
+ const win = windowMoved || muteMoved ? windowPatch() : null;
+ const ok = await save({
+ ...(win ?? {}),
+ ...("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }),
+ });
+ return ok;
+ },
+ said: (next) =>
+ `the cut plays ${gappedLength(gapsSpan.from, gapsSpan.to, next).toFixed(2)} s, one segment${windowMoved ? " (the window you moved was saved with it)" : ""}`,
setNote,
fmt: hms,
+ wall: (side, at) =>
+ hasCut
+ ? `stopped at the cut's ${side} (${hms(at)}) — gaps go inside the cut: drag its edge on the waveform, or Use the whole clip`
+ : side === "end"
+ ? `stopped at the clip's end (${hms(at)}) — drag the clip's end out first${atEndEdge ? ", past the cache: Fetch more" : ""}`
+ : `stopped at the clip's start (${hms(at)}) — drag the clip's start out first${atStartEdge ? ", past the cache: Fetch more" : ""}`,
});
+ // ---- the cut's edges, on the waveform ----------------------------------------
+ //
+ // Drawn and dragged there (bench/CutEdges.tsx), written on release through
+ // the window writer with an Undo -- as are Use the whole clip and Clear cut.
+ // A gap left outside the new cut is refused here first, with the writer's
+ // sentence; a moved extent rides along, as with a gap.
+ const [cutDraft, setCutDraft] = useState<Span | null>(null);
+ const [cutUndo, setCutUndo] = useState<{ cutStart: number | null; cutEnd: number | null; lockCut: boolean; what: string } | null>(null);
+ useEffect(() => {
+ setCutDraft(null);
+ setCutUndo(null);
+ }, [clip.id]);
+ const writeCut = useCallback(
+ async (next: Span | null, what: string) => {
+ const before = { cutStart: clip.cutStart, cutEnd: clip.cutEnd, lockCut: clip.lockCut };
+ const cutPatch = next ? { cutStart: round2(next.from), cutEnd: round2(next.to) } : { cutStart: "", cutEnd: "", lockCut: false };
+ const why = gapRefusalFor(clip.gaps ?? [], next ? { cutStart: round2(next.from), cutEnd: round2(next.to) } : { cutStart: null, cutEnd: null });
+ if (why) {
+ setCutDraft(null);
+ setNote(`the cut was not moved: ${why}`);
+ return false;
+ }
+ const win = windowMoved || muteMoved ? windowPatch() : null;
+ const ok = await save({ ...(win ?? {}), ...cutPatch });
+ setCutDraft(null);
+ if (ok) {
+ setCutUndo({ ...before, what });
+ setNote(`${what}${win ? " — the window you moved was saved with it" : ""}`);
+ }
+ return ok;
+ },
+ [clip.cutStart, clip.cutEnd, clip.lockCut, clip.gaps, gapRefusalFor, windowMoved, muteMoved, windowPatch, save],
+ );
+ const takeWholeClip = useCallback(
+ () => void writeCut(null, "the cut cleared — the whole clip plays, and gaps can go anywhere in it"),
+ [writeCut],
+ );
+ const undoCut = useCallback(async () => {
+ const u = cutUndo;
+ if (!u) return;
+ const ok = await save(
+ u.cutStart != null && u.cutEnd != null
+ ? { cutStart: u.cutStart, cutEnd: u.cutEnd, lockCut: u.lockCut }
+ : { cutStart: "", cutEnd: "", lockCut: false },
+ );
+ if (ok) {
+ setCutUndo(null);
+ setNote(`undone — ${u.what.split(" — ")[0]} is reversed`);
+ }
+ }, [cutUndo, save]);
+ const onCutDrag = useCallback(
+ (side: "start" | "end", t: number, done: boolean) => {
+ if (clip.cutStart == null || clip.cutEnd == null) return;
+ const cur = cutDraft ?? { from: clip.cutStart, to: clip.cutEnd };
+ // Inside the extent as drafted, and at least half a second (the writer's rule).
+ const next =
+ side === "start"
+ ? { from: Math.max(sel.from, Math.min(t, cur.to - 0.5)), to: cur.to }
+ : { from: cur.from, to: Math.min(sel.to, Math.max(t, cur.from + 0.5)) };
+ if (!done) {
+ setCutDraft(next);
+ return;
+ }
+ if (Math.abs(next.from - clip.cutStart) < 0.005 && Math.abs(next.to - clip.cutEnd) < 0.005) {
+ setCutDraft(null);
+ return;
+ }
+ void writeCut(next, `the cut moved to ${hms(next.from)}–${hms(next.to)}`);
+ },
+ [clip.cutStart, clip.cutEnd, cutDraft, sel.from, sel.to, writeCut],
+ );
+
// ---- the zoom ----------------------------------------------------------------
// What the waveform shows of the cached window (bench/GapsZoom.tsx). Fit -- the
// whole window, today's view -- on every clip's arrival.
@@ -1811,15 +1940,33 @@ export default function ClipBench({
const reachBefore = cached ? clip.start - cached.from : 0;
const reachAfter = cached ? cached.to - clip.end : 0;
const peekOutside = peek.some((c) => c.start < view.from - 0.02 || c.end > view.to + 0.02);
- const nextBefore = Math.min(data.maxPad, Math.round(reachBefore) + 20);
- const nextAfter = Math.min(data.maxPad, Math.round(reachAfter) + 20);
+ // THE NEXT ASK GOES ON FROM WHERE THE EDGE IS NOW -- the cached edge, or an
+ // unsaved drag out to it -- so every press reaches further. The pads are the
+ // fetch's, measured from the SAVED edges; the only cap is the WINDOW's, end
+ // to end (the editor's, data.maxWindow), never a fixed reach per side: a
+ // cap of 120 s from the saved edge was the wall a long drag stopped at
+ // (lane/clip-fixes). Twenty seconds a press close in, a minute once the
+ // edge is already far out.
+ const clipLen = clip.end - clip.start;
+ const stepFrom = (reach: number) => (reach < 40 ? 20 : 60);
+ /** The most one side may ask for with the other kept as it is. */
+ const capBefore = Math.max(0, Math.floor(data.maxWindow - clipLen - reachAfter));
+ const capAfter = Math.max(0, Math.floor(data.maxWindow - clipLen - reachBefore));
+ const edgeBefore = Math.max(reachBefore, clip.start - sel.from);
+ const edgeAfter = Math.max(reachAfter, sel.to - clip.end);
+ const nextBefore = Math.min(capBefore, Math.round(edgeBefore) + stepFrom(edgeBefore));
+ const nextAfter = Math.min(capAfter, Math.round(edgeAfter) + stepFrom(edgeAfter));
// A side stops being worth offering for two different reasons, and they are
- // different sentences: the pad cap, and the end of the recording itself.
+ // different sentences: the window cap, and the end of the recording itself.
const atStartOfSource = !!cached && cached.from <= 0.02;
const atEndOfSource =
!!cached && sourceDuration != null && cached.to >= sourceDuration - 0.02;
- const beforeMaxed = reachBefore >= data.maxPad - 0.5 || atStartOfSource;
- const afterMaxed = reachAfter >= data.maxPad - 0.5 || atEndOfSource;
+ const beforeAtCap = nextBefore <= reachBefore + 0.5;
+ const afterAtCap = nextAfter <= reachAfter + 0.5;
+ const beforeMaxed = beforeAtCap || atStartOfSource;
+ const afterMaxed = afterAtCap || atEndOfSource;
+ /** What a side at the window cap says: the limit, and the next step. */
+ const capSentence = `a fetched window is at most ${Math.round(data.maxWindow / 60)} min end to end — Fetch whole source for more`;
const atMaxPad = beforeMaxed && afterMaxed;
/** Keep the side that is not being extended exactly where it is. */
const keepBefore = round2(reachBefore);
@@ -1846,8 +1993,8 @@ export default function ClipBench({
const padsForCue = (c: Cue) => {
const after = c.end > view.to;
return {
- padBefore: after ? keepBefore : Math.min(data.maxPad, Math.ceil(clip.start - (c.start - 2))),
- padAfter: after ? Math.min(data.maxPad, Math.ceil(c.end + 2 - clip.end)) : keepAfter,
+ padBefore: after ? keepBefore : Math.min(capBefore, Math.ceil(clip.start - (c.start - 2))),
+ padAfter: after ? Math.min(capAfter, Math.ceil(c.end + 2 - clip.end)) : keepAfter,
};
};
const padLabelForCue = (c: Cue) =>
@@ -1871,6 +2018,80 @@ export default function ClipBench({
// otherwise blank the line the composition was built with.
const osTexts: DeckTexts = osAuto ? { [clip.id]: osShown } : {};
const osChanged = !sameOs(os, osDraftOf(clip.onscreen));
+
+ // ---- coming back to the page ------------------------------------------------
+ //
+ // The back button restores this page as it was shown (the browser's page
+ // cache: pageshow, persisted; or Next's router cache, which remounts it with
+ // the payload it had then), and a hidden tab comes back to whatever happened
+ // meanwhile -- a window fetched, the clip saved from another tab. Operator,
+ // 6 Nov: "I just had to refresh. Maybe address that so it updates if you
+ // click the back button." So: read the clip's state again on pageshow
+ // (persisted), on visibilitychange -> visible and once on mount, through the
+ // same route a fetch reads -- never while something is in flight or a gap or
+ // cut edge is being dragged, nor over anything unsaved (an edge, the mark, a
+ // field): those keep the token they were drafted against, so the writer's
+ // stale check still guards them.
+ const returnState = useRef({ busy: false, clean: true });
+ returnState.current = {
+ busy: !!busy || !!gap.sel || gap.pick || cutDraft != null,
+ clean: !dirty && !muteMoved && !osChanged && ATTRIB.every(([k]) => draft[k] === attribValue(clip, k)),
+ };
+ const windowsRef = useRef(windows);
+ windowsRef.current = windows;
+ const clipRef = useRef(clip);
+ clipRef.current = clip;
+ const resync = useCallback(async () => {
+ const ok = () => !returnState.current.busy && returnState.current.clean;
+ if (!ok()) return;
+ const r = await fetch(
+ `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`,
+ { cache: "no-store" },
+ ).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as ClipBenchData & { clip: Record<string, unknown> };
+ if (!ok()) return;
+ const wk = (ws: Win[]) => ws.map((w) => `${w.name}|${w.from}|${w.to}|${w.v ?? ""}`).join(",");
+ if (wk(j.windows) !== wk(windowsRef.current)) {
+ setWindows(j.windows);
+ setCues(j.cues);
+ if (j.windows[0]) setView({ from: j.windows[0].from, to: j.windows[0].to });
+ }
+ setProposed(j.proposed);
+ setSegment(j.segment);
+ setSegmentMtime(j.segmentMtime);
+ if (j.token !== token.current) {
+ token.current = j.token;
+ const next = fromEntry(clipRef.current, j.clip);
+ setClip(next);
+ setSel({ from: next.start, to: next.end });
+ setDirty(false);
+ setMute(next.muteFrom);
+ muteRef.current = next.muteFrom;
+ setDraft(emptyDraft(next));
+ setOs(osDraftOf(next.onscreen));
+ }
+ }, [data.project, clip.id, tq]);
+ const resyncRef = useRef(resync);
+ resyncRef.current = resync;
+ useEffect(() => {
+ const again = () => void resyncRef.current();
+ const onShow = (e: PageTransitionEvent) => {
+ if (e.persisted) again();
+ };
+ const onVis = () => {
+ if (document.visibilityState === "visible") again();
+ };
+ window.addEventListener("pageshow", onShow);
+ document.addEventListener("visibilitychange", onVis);
+ // Once on mount: Next's router restores a page gone back to from its own
+ // cache, with no pageshow -- and a fresh load pays one small request.
+ again();
+ return () => {
+ window.removeEventListener("pageshow", onShow);
+ document.removeEventListener("visibilitychange", onVis);
+ };
+ }, [clip.id]);
const osOver = osShown.title.length > osMax;
// The strip follows the player when the player is inside what the cut
// plays, mapped onto the cut's clock; anywhere else it holds mid-segment.
@@ -2337,8 +2558,8 @@ export default function ClipBench({
onFetch={(edge, t) =>
void fetchMore(
edge === "end"
- ? { padBefore: keepBefore, padAfter: Math.min(data.maxPad, Math.ceil(t + 2 - clip.end)) }
- : { padBefore: Math.min(data.maxPad, Math.ceil(clip.start - (t - 2))), padAfter: keepAfter },
+ ? { padBefore: keepBefore, padAfter: Math.min(capAfter, Math.ceil(t + 2 - clip.end)) }
+ : { padBefore: Math.min(capBefore, Math.ceil(clip.start - (t - 2))), padAfter: keepAfter },
)
}
/>
@@ -2893,11 +3114,23 @@ export default function ClipBench({
data-cut-clear=""
className={buttonVariants({ size: "sm" })}
disabled={!!busy}
- onClick={() => void save({ cutStart: "", cutEnd: "", lockCut: false })}
+ onClick={takeWholeClip}
>
Clear cut
</button>
)}
+ {cutUndo && (
+ <button
+ type="button"
+ data-cut-undo=""
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ disabled={!!busy}
+ title={`undo: ${cutUndo.what}`}
+ onClick={() => void undoCut()}
+ >
+ Undo cut
+ </button>
+ )}
</span>
{/* ---- the MUTE MARK ----
Beside the cut because it is the same kind of decision -- what
@@ -2966,7 +3199,35 @@ export default function ClipBench({
{/* ---- the instrument ----
On a phone the edge strip is the instrument; this one is still
there, folded under Window, for the mute mark. */}
- <div className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}>
+ <div data-bench-sel={`${sel.from.toFixed(2)}-${sel.to.toFixed(2)}`} className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}>
+ {/* A cut narrower than the clip: the wall a gap -- and the video -- stops
+ at, said above the waveform it is drawn on, with the way out. */}
+ {cutNarrower && (
+ <div data-cut-limits={`${clip.cutStart}-${clip.cutEnd}`} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-good)] px-2 py-1 text-[12px]">
+ <span className="text-[var(--color-text)]">
+ The video plays only the cut{" "}
+ <span className="num">
+ {hms(clip.cutStart!)}–{hms(clip.cutEnd!)}
+ </span>
+ , and gaps go inside it{" "}
+ <span className="text-[var(--color-dim)]">
+ (the clip is {hms(sel.from)}–{hms(sel.to)}
+ {clip.lockCut ? "; the cut is pinned" : ""})
+ </span>
+ </span>
+ <button
+ type="button"
+ data-cut-use-whole=""
+ className={buttonVariants({ size: "sm" })}
+ disabled={!!busy}
+ title="clear the cut: the whole clip plays, and gaps can go anywhere in it (Undo puts the cut back)"
+ onClick={takeWholeClip}
+ >
+ Use the whole clip
+ </button>
+ <span className="text-[var(--color-dim)]">or drag the cut's edges (the green tabs) on the waveform</span>
+ </div>
+ )}
{/* Zoomed: round ticks over what is shown. */}
{zoom.zoomed && <ZoomRuler vis={zoom.vis} />}
<BenchWaveBox
@@ -2983,6 +3244,7 @@ export default function ClipBench({
words={nearWords?.words ?? null}
busy={!!busy}
held={mutePick}
+ walls={walls}
>
{/* The mute mark over the waveform: a line where the sound stops
and a hatch over what is silent to the end of the selection.
@@ -3009,6 +3271,17 @@ export default function ClipBench({
</div>
</>
)}
+ {/* The cut, when the clip has one: its edges, dragged here (bench/CutEdges.tsx). */}
+ {hasCut && (
+ <CutEdges
+ vis={zoom.vis}
+ cut={cutDraft ?? { from: clip.cutStart!, to: clip.cutEnd! }}
+ extent={sel}
+ busy={!!busy}
+ fmt={hms}
+ onDrag={onCutDrag}
+ />
+ )}
{/* Where the render will actually cut: each edge snapped to its silence, faint. */}
<RenderGhosts edges={renderEdges} view={zoom.vis} />
{/* Armed: the next click places the mark rather than an edge. */}
@@ -3029,7 +3302,7 @@ export default function ClipBench({
{/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */}
<div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]">
{/* ---- GAPS inside the clip (bench/BenchWave.tsx GapTools) ---- */}
- <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapSpan(clip)} sel={sel} busy={!!busy} fmt={hms} play={play} />
+ <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapsSpan} sel={sel} busy={!!busy} fmt={hms} play={play} />
<TightenButtons tools={edgeTools} busy={!!busy} />
<span className="micro max-md:hidden">
<kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "}
@@ -3059,7 +3332,7 @@ export default function ClipBench({
<span data-fetch-before-maxed="" className="text-[var(--color-dim)]">
{atStartOfSource
? "the recording starts here"
- : `−${data.maxPad} s is the widest one side goes`}
+ : capSentence}
</span>
) : (
<button
@@ -3076,7 +3349,7 @@ export default function ClipBench({
<span data-fetch-after-maxed="" className="text-[var(--color-dim)]">
{atEndOfSource
? "the recording ends here"
- : `+${data.maxPad} s is the widest one side goes`}
+ : capSentence}
</span>
) : (
<button
diff --git a/umtool/components/projects/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx
@@ -4,7 +4,7 @@ import { useRef } from "react";
import Waveform, { type Peaks } from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { GAP_LIMITS, gappedLength } from "umtool-report-to-video/gaps";
-import { GapLayer, type WaveZoom } from "./GapsZoom";
+import { GapLayer, type GapWallsView, type WaveZoom } from "./GapsZoom";
import type { Span } from "./benchMedia";
import type { GapEditor } from "./useGapEditor";
@@ -34,6 +34,7 @@ export function BenchWaveBox({
words,
busy,
held = false,
+ walls = null,
children,
}: {
zoom: WaveZoom;
@@ -51,6 +52,8 @@ export function BenchWaveBox({
busy: boolean;
/** Another pick is armed (the mute mark's): Alt + drag and the gap pick stand down. */
held?: boolean;
+ /** Where a gap cannot go, and why (gaps.mjs gapWalls), drawn on the waveform. */
+ walls?: GapWallsView | null;
children?: React.ReactNode;
}) {
const altDrag = useRef<{ id: number; at: number } | null>(null);
@@ -109,6 +112,8 @@ export function BenchWaveBox({
vis={zoom.vis}
gaps={gaps}
selection={gap.sel}
+ live={gap.live}
+ walls={walls}
picking={gap.pick && !held}
silences={silences}
words={words}
diff --git a/umtool/components/projects/bench/CutEdges.tsx b/umtool/components/projects/bench/CutEdges.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import { useRef } from "react";
+import type { Span } from "./benchMedia";
+
+// ---------------------------------------------------------------------------
+// THE CUT ON THE WAVEFORM (lane/clip-fixes). A clip's cut (`cutStart`–`cutEnd`)
+// is what the video plays, inside the extent; gaps lie inside it. It used to be
+// drawn only on the rail, so a cut narrower than the extent -- a locked clause
+// cut kept from an earlier pass, under an extent since widened -- was a wall a
+// gap drag stopped at with nothing on the waveform to say why (operator, 6 Nov:
+// "I can't add gaps beyond like 9:21"). Here: the seconds of the extent outside
+// the cut shaded, each cut edge a line in the cut's colour, and a tab on it
+// that drags the edge (written on release, by the caller, with an Undo). The
+// line itself never takes a pointer: the waveform's own drag goes on under it.
+// ---------------------------------------------------------------------------
+
+export function CutEdges({
+ vis,
+ cut,
+ extent,
+ busy,
+ fmt,
+ onDrag,
+}: {
+ /** What the waveform shows. */
+ vis: Span;
+ /** The cut, as saved or as being dragged. */
+ cut: Span;
+ /** The extent the cut lies in (the selection as drafted). */
+ extent: Span;
+ busy: boolean;
+ fmt: (t: number) => string;
+ /** An edge dragged to `t`; `done` on release. */
+ onDrag: (side: "start" | "end", t: number, done: boolean) => void;
+}) {
+ const span = Math.max(1e-6, vis.to - vis.from);
+ const pct = (t: number) => `${((Math.min(vis.to, Math.max(vis.from, t)) - vis.from) / span) * 100}%`;
+ const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`;
+ const drag = useRef<{ id: number; side: "start" | "end" } | null>(null);
+ const tAt = (el: HTMLElement, clientX: number) => {
+ const box = (el.closest("[data-wave-box]") as HTMLElement | null) ?? el;
+ const r = box.getBoundingClientRect();
+ return vis.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * span;
+ };
+ const outside: Array<{ side: "start" | "end"; from: number; to: number }> = [];
+ if (cut.from > extent.from + 0.01) outside.push({ side: "start", from: extent.from, to: cut.from });
+ if (cut.to < extent.to - 0.01) outside.push({ side: "end", from: cut.to, to: extent.to });
+ const inView = (s: { from: number; to: number }) => s.to > vis.from && s.from < vis.to;
+ return (
+ <>
+ {outside.filter(inView).map((o) => (
+ <div
+ key={`out-${o.side}`}
+ data-wave-outside-cut={o.side}
+ title={`${fmt(o.from)}–${fmt(o.to)} is in the clip but not in its cut: the video does not play it, and no gap can go here`}
+ className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--color-good)_16%,transparent)_0_2px,transparent_2px_8px)]"
+ style={{ left: pct(o.from), width: width(o.from, o.to) }}
+ />
+ ))}
+ {(["start", "end"] as const).map((side) => {
+ const t = side === "start" ? cut.from : cut.to;
+ if (t < vis.from || t > vis.to) return null;
+ return (
+ <div
+ key={side}
+ data-wave-cut-edge={side}
+ data-wave-cut-at={t.toFixed(2)}
+ className="pointer-events-none absolute top-0 z-[4] h-full border-l-2 border-[var(--color-good)]"
+ style={{ left: pct(t) }}
+ >
+ <button
+ type="button"
+ data-wave-cut-grip={side}
+ disabled={busy}
+ title={`the cut's ${side}, ${fmt(t)}: the video plays from the cut's start to its end, and gaps go inside it — drag to move it`}
+ className={
+ side === "start"
+ ? "pointer-events-auto absolute left-0 top-4 cursor-ew-resize touch-none select-none whitespace-nowrap rounded-r bg-[var(--color-good)] px-1 font-mono text-[9px] font-semibold leading-[14px] text-[var(--color-ground)] disabled:cursor-default"
+ : "pointer-events-auto absolute right-0.5 top-4 cursor-ew-resize touch-none select-none whitespace-nowrap rounded-l bg-[var(--color-good)] px-1 font-mono text-[9px] font-semibold leading-[14px] text-[var(--color-ground)] disabled:cursor-default"
+ }
+ onPointerDown={(e) => {
+ if (busy) return;
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ drag.current = { id: e.pointerId, side };
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d || d.id !== e.pointerId) return;
+ e.stopPropagation();
+ onDrag(d.side, tAt(e.currentTarget, e.clientX), false);
+ }}
+ onPointerUp={(e) => {
+ const d = drag.current;
+ if (!d || d.id !== e.pointerId) return;
+ e.stopPropagation();
+ drag.current = null;
+ onDrag(d.side, tAt(e.currentTarget, e.clientX), true);
+ }}
+ onPointerCancel={() => {
+ drag.current = null;
+ }}
+ >
+ {side === "start" ? "cut ▸" : "◂ cut"}
+ </button>
+ </div>
+ );
+ })}
+ </>
+ );
+}
diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx
@@ -181,6 +181,15 @@ export function ZoomRuler({ vis }: { vis: Span }) {
* between words. `onRemove` on a gap's click; while `picking` (or with Alt
* held over the waveform, the caller's capture handler) a drag selects a span.
*/
+/** What GapLayer draws of the walls: gapWalls's shape, the zones' kinds open (a reel adds its master's gaps). */
+export type GapWallsView = {
+ span: Span;
+ /** What the span is called in a sentence: "cut", "clip", "beat". */
+ whose: string;
+ zones: Array<{ from: number; to: number; kind: string; why: string }>;
+ marks: Array<{ at: number; kind: string; why: string }>;
+};
+
export function GapLayer({
vis,
gaps,
@@ -191,10 +200,22 @@ export function GapLayer({
busy,
onRemove,
onSelect,
+ live = null,
+ walls = null,
}: {
vis: Span;
gaps: Span[];
selection: Span | null;
+ /** What the selection would do, checked on every move (useGapEditor's GapLive). */
+ live?: { why: string | null; wall: string | null; merged: { from: number; to: number } | null; short: boolean } | null;
+ /**
+ * Where a gap cannot go, and why (gaps.mjs gapWalls, or a reel beat's own):
+ * drawn so no wall a gap drag stops at is invisible -- outside the span and
+ * the keep bands shaded (a strip along the foot always, the full height
+ * while a gap is being picked), each mark a gap can't cover ticked, every
+ * one with its sentence on hover.
+ */
+ walls?: GapWallsView | null;
picking: boolean;
silences: Span[] | null;
/** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */
@@ -258,6 +279,7 @@ export function GapLayer({
{quiet.map((t) => (
<div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} />
))}
+ {walls && <GapWallsLayer walls={walls} vis={vis} pct={pct} width={width} full={picking || !!selection} />}
{gaps.filter(inView).map((g) => (
<button
key={`gap-${g.from}`}
@@ -276,11 +298,37 @@ export function GapLayer({
{selection && inView(selection) && (
<div
data-gap-selection={`${selection.from.toFixed(2)}-${selection.to.toFixed(2)}`}
+ data-gap-selection-state={live?.short ? "short" : live?.why ? "refused" : live?.merged ? "merge" : "ok"}
aria-hidden
- className="pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-dashed border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_14%,transparent)]"
+ className={
+ live?.why && !live.short
+ ? "pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-solid border-[var(--color-bad)] bg-[color-mix(in_srgb,var(--color-bad)_30%,transparent)]"
+ : "pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-dashed border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_14%,transparent)]"
+ }
style={{ left: pct(selection.from), width: width(selection.from, selection.to) }}
/>
)}
+ {/* What the selection would do, said while it is dragged: the writer's
+ refusal, the wall it stopped at, the gap it would merge into. */}
+ {selection && live && (live.why || live.wall || live.merged) && (
+ <div
+ data-gap-selection-why={live.short ? "short" : live.why ? "refused" : live.wall ? "wall" : "merge"}
+ role="status"
+ className={
+ live.why && !live.short
+ ? "pointer-events-none absolute inset-x-1 bottom-1 z-[9] line-clamp-2 rounded bg-[var(--color-panel-2)] px-1.5 py-0.5 text-[11px] leading-tight text-[var(--color-bad)] shadow"
+ : "pointer-events-none absolute inset-x-1 bottom-1 z-[9] line-clamp-2 rounded bg-[var(--color-panel-2)] px-1.5 py-0.5 text-[11px] leading-tight text-[var(--color-dim)] shadow"
+ }
+ >
+ {[
+ live.why ? (live.short ? live.why : `can't cut: ${live.why}`) : null,
+ live.merged ? `touches a gap — cutting makes one gap ${live.merged.from.toFixed(2)}–${live.merged.to.toFixed(2)}` : null,
+ live.wall,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </div>
+ )}
{picking && (
<div
data-gap-pick-layer=""
@@ -468,3 +516,84 @@ export function ZoomOverview({
</div>
);
}
+
+
+/** The walls (GapLayer's `walls`): no-cut zones and the marks a gap can't cover. */
+function GapWallsLayer({
+ walls,
+ vis,
+ pct,
+ width,
+ full,
+}: {
+ walls: GapWallsView;
+ vis: Span;
+ pct: (t: number) => string;
+ width: (a: number, b: number) => string;
+ /** A gap is being picked: shade the full height, not just the foot. */
+ full: boolean;
+}) {
+ const inView = (a: number, b: number) => b > vis.from && a < vis.to;
+ const zones: Array<{ from: number; to: number; kind: string; why: string }> = [];
+ if (walls.span.from > vis.from) zones.push({ from: vis.from, to: walls.span.from, kind: "outside", why: `before the ${walls.whose}'s start: a gap goes inside the ${walls.whose}` });
+ if (walls.span.to < vis.to) zones.push({ from: walls.span.to, to: vis.to, kind: "outside", why: `after the ${walls.whose}'s end: a gap goes inside the ${walls.whose}` });
+ zones.push(...walls.zones.filter((z) => z.to > z.from));
+ return (
+ <>
+ {zones
+ .filter((z) => inView(z.from, z.to))
+ .map((z, k) => (
+ <div
+ key={`nocut-${k}-${z.from}`}
+ data-gap-nocut={z.kind}
+ data-gap-nocut-at={`${z.from.toFixed(2)}-${z.to.toFixed(2)}`}
+ title={`no gap here — ${z.why}`}
+ className={
+ full
+ ? "pointer-events-none absolute bottom-0 z-[3] h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-bad)_20%,transparent)_0_2px,transparent_2px_6px)]"
+ : "absolute bottom-0 z-[3] h-1.5 [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-bad)_55%,transparent)_0_2px,transparent_2px_5px)]"
+ }
+ style={{ left: pct(z.from), width: width(z.from, z.to) }}
+ />
+ ))}
+ {/* The cut's own edges, labelled: where the span of gaps starts and ends. */}
+ {(["start", "end"] as const).map((side) => {
+ const t = side === "start" ? walls.span.from : walls.span.to;
+ if (!(t >= vis.from && t <= vis.to)) return null;
+ return (
+ <div
+ key={`edge-${side}`}
+ data-gap-span-edge={side}
+ aria-hidden
+ className={
+ side === "start"
+ ? "pointer-events-none absolute bottom-1.5 z-[3] translate-x-0.5 whitespace-nowrap font-mono text-[9px] leading-none text-[var(--color-bad)]"
+ : "pointer-events-none absolute bottom-1.5 z-[3] -translate-x-full whitespace-nowrap pr-0.5 font-mono text-[9px] leading-none text-[var(--color-bad)]"
+ }
+ style={{ left: pct(t) }}
+ >
+ {side === "start" ? `${walls.whose} ▸` : `◂ ${walls.whose}`}
+ </div>
+ );
+ })}
+ {walls.marks
+ .filter((m) => m.at >= vis.from && m.at <= vis.to)
+ .map((m) => (
+ <div
+ key={`mark-${m.kind}-${m.at}`}
+ data-gap-wall-mark={m.at}
+ data-gap-wall-mark-kind={m.kind}
+ className="pointer-events-none absolute top-0 z-[6] h-full border-l border-dashed border-[var(--color-bad)]"
+ style={{ left: pct(m.at) }}
+ >
+ <span
+ title={`a gap can't cover this — ${m.why}`}
+ className="pointer-events-auto absolute bottom-1.5 -translate-x-1/2 cursor-help rounded-sm bg-[var(--color-bad)] px-0.5 font-mono text-[9px] leading-[11px] text-[var(--color-ground)]"
+ >
+ {m.kind === "mute" ? "mute" : m.kind === "stamp" ? "stamp" : "mark"}
+ </span>
+ </div>
+ ))}
+ </>
+ );
+}
diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts
@@ -18,6 +18,16 @@ import type { Span } from "./benchMedia";
export type GapOp = { add: Span } | { remove: Span } | { set: Span[] };
+/**
+ * What the span being dragged for a gap would do, said WHILE it is dragged
+ * (lane/clip-fixes, operator 6 Nov: "the gap tool gets blocked at random
+ * invisible walls"): the writer's refusal (`why`, the same sentence the
+ * writer would answer with), the wall the drag stopped at (`wall`), the
+ * neighbour a touching span merges into (`merged`, the gap it would make), and
+ * `short` under the shortest gap.
+ */
+export type GapLive = { why: string | null; wall: string | null; merged: Span | null; short: boolean };
+
const r2 = (n: number) => Number(n.toFixed(2));
export function useGapEditor({
@@ -29,6 +39,7 @@ export function useGapEditor({
said,
setNote,
fmt,
+ wall,
}: {
/** What the gaps belong to: another one starts with nothing selected and nothing to undo. */
key: string;
@@ -44,15 +55,22 @@ export function useGapEditor({
said: (next: Span[]) => string;
setNote: (s: string | null) => void;
fmt: (t: number) => string;
+ /** The sentence for a drag stopped at `span`'s edge (the clip's cut, a beat's end); a plain one without. */
+ wall?: (side: "start" | "end", at: number) => string;
}) {
- const [sel, setSel] = useState<Span | null>(null);
+ const [sel, setSelState] = useState<Span | null>(null);
+ const [live, setLive] = useState<GapLive | null>(null);
+ const setSel = useCallback((s: Span | null | ((p: Span | null) => Span | null)) => {
+ setSelState(s);
+ if (s === null) setLive(null);
+ }, []);
const [pick, setPick] = useState(false);
const [undo, setUndo] = useState<{ gaps: Span[]; what: string } | null>(null);
useEffect(() => {
setSel(null);
setPick(false);
setUndo(null);
- }, [key]);
+ }, [key, setSel]);
const run = useCallback(
async (op: GapOp, next: Span[], what: string) => {
@@ -83,12 +101,19 @@ export function useGapEditor({
setNote(e instanceof Error ? e.message : String(e));
return;
}
- const ok = await run({ add: g }, next, `cut ${fmt(g.from)}–${fmt(g.to)} out`);
+ // A span touching a gap GROWS it (editGaps): say which one it became.
+ const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6);
+ const merged = grown && (Math.abs(grown.from - g.from) > 0.005 || Math.abs(grown.to - g.to) > 0.005) ? grown : null;
+ const ok = await run(
+ { add: g },
+ next,
+ merged ? `cut ${fmt(g.from)}–${fmt(g.to)} out, merged with the gap beside it into ${fmt(merged.from)}–${fmt(merged.to)}` : `cut ${fmt(g.from)}–${fmt(g.to)} out`,
+ );
if (ok) {
setSel(null);
setPick(false);
}
- }, [sel, gaps, run, setNote, fmt]);
+ }, [sel, gaps, run, setNote, fmt, setSel]);
const remove = useCallback(
(g: Span) => {
@@ -121,28 +146,58 @@ export function useGapEditor({
});
}, [undo, write, setNote]);
- /** A span dragged for a gap: kept inside the span; under the shortest gap on release, dropped and said. */
+ /**
+ * A span dragged for a gap: kept inside the span, and checked on EVERY move
+ * with the writer's own rule (`refusal`, the full validateGaps), so a wall is
+ * said while the span is being dragged into it, not after release. Under the
+ * shortest gap on release, dropped and said.
+ */
const select = useCallback(
(s: Span, done: boolean) => {
const from = Math.max(span.from, s.from);
const to = Math.min(span.to, s.to);
+ // The clamp biting: the drag went past where a gap may go.
+ const side = s.from < span.from - 0.01 ? "start" : s.to > span.to + 0.01 ? "end" : null;
+ const at = side === "start" ? span.from : span.to;
+ const wallSaid = side ? (wall ? wall(side, at) : `stopped at the ${side} of where a gap may go (${fmt(at)})`) : null;
+ const short = to - from < GAP_LIMITS.min;
+ let why: string | null = null;
+ let merged: Span | null = null;
+ if (!short) {
+ const g = { from: r2(from), to: r2(to) };
+ try {
+ const next = editGaps(gaps, { add: g });
+ why = refusal(next);
+ const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6);
+ if (grown && (Math.abs(grown.from - g.from) > 0.005 || Math.abs(grown.to - g.to) > 0.005)) merged = grown;
+ } catch (e) {
+ why = e instanceof Error ? e.message : String(e);
+ }
+ }
if (!done) {
- setSel(to > from ? { from, to } : null);
+ setSelState(to > from ? { from, to } : null);
+ setLive(to > from ? { why: short ? `a gap is at least ${GAP_LIMITS.min} s` : why, wall: wallSaid, merged, short } : null);
return;
}
- if (to - from < GAP_LIMITS.min) {
+ if (short) {
setSel(null);
- if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`);
+ if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span${wallSaid ? `; ${wallSaid}` : ""}`);
+ else if (wallSaid) setNote(wallSaid);
return;
}
- setSel({ from, to });
- const why = refusal(editGaps(gaps, { add: { from: r2(from), to: r2(to) } }));
- setNote(why ? `this span cannot be cut: ${why}` : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`);
+ setSelState({ from, to });
+ setLive({ why, wall: wallSaid, merged, short });
+ const head = why
+ ? `this span cannot be cut: ${why}`
+ : merged
+ ? `${(to - from).toFixed(2)} s selected — it touches a gap, so Cut gap (g) makes them one: ${fmt(merged.from)}–${fmt(merged.to)}`
+ : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`;
+ setNote(wallSaid ? `${head} · ${wallSaid}` : head);
},
- [span.from, span.to, gaps, refusal, setNote],
+ [span.from, span.to, gaps, refusal, setNote, fmt, wall, setSel],
);
- return { sel, setSel, pick, setPick, undo, cut, remove, removeAt, undoLast, select };
+ return { sel, setSel, live, pick, setPick, undo, cut, remove, removeAt, undoLast, select };
}
export type GapEditor = ReturnType<typeof useGapEditor>;
diff --git a/umtool/components/projects/reel/ReelBench.tsx b/umtool/components/projects/reel/ReelBench.tsx
@@ -12,7 +12,7 @@ import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs";
import { fileSpans } from "@/lib/report/fileMedia.mjs";
import type { ReelBenchData } from "@/lib/report/reelBenchData";
import { cn } from "@/lib/utils";
-import { beatGapsOf, editGaps } from "umtool-report-to-video/gaps";
+import { beatGapsOf, editGaps, gapWalls } from "umtool-report-to-video/gaps";
import { BenchWaveBox, GapTools } from "../bench/BenchWave";
import { renderedFileMedia, type Span } from "../bench/benchMedia";
import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom } from "../bench/GapsZoom";
@@ -385,6 +385,14 @@ function BeatEditor({
const fmt = isClip ? sourceClock : clock;
const kept = sel.to - sel.from - gaps.reduce((s, g) => s + Math.max(0, Math.min(g.to, sel.to) - Math.max(g.from, sel.from)), 0);
const masterGaps = isClip ? m.map.gaps.filter((g) => g.to > span.from && g.from < span.to) : [];
+ // Where a gap cannot go in the beat, drawn as on the clip bench (lane/clip-fixes): the beat's
+ // edges and the keep bands, the clip rule's (gaps.mjs gapWalls), said as the beat's. The
+ // master's own gaps are drawn below, each with its title.
+ const walls = useMemo(() => {
+ if (!isClip) return null;
+ const w = gapWalls({ type: "clip", id: row.id ?? "beat", start: saved.from, end: saved.to, gaps });
+ return { ...w, whose: "beat", zones: w.zones.map((z) => ({ ...z, why: z.why.replace("the clip's", "the beat's") })) };
+ }, [isClip, row.id, saved.from, saved.to, gaps]);
const confirmedCount = (view.rows ?? []).filter((x) => x.verdict === "confirmed").length;
return (
@@ -449,13 +457,14 @@ function BeatEditor({
words={nearWords?.words ?? null}
busy={busy}
held={!isClip}
+ walls={walls}
>
{/* What the master already left out of the clip (its render's gaps): nothing plays there. */}
{masterGaps.map((g) => (
<div
key={`mg-${g.from}`}
data-reel-master-gap={`${g.from}-${g.to}`}
- title={`${sourceClock(g.from)}–${sourceClock(g.to)}: cut out of ${row.id} in the master (the clip's own gap) — edit it on the clip's walk`}
+ title={`${sourceClock(g.from)}–${sourceClock(g.to)}: cut out of ${row.id} in the master (the clip's own gap) — nothing plays here, so no beat gap can lie wholly inside it; edit it on the clip's walk`}
className="pointer-events-none absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-dim)_25%,transparent)]"
style={{ left: zpct(g.from), width: `calc(${zpct(g.to)} - ${zpct(g.from)})` }}
/>
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -953,6 +953,31 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, attempt]);
+ // COMING BACK TO THE PAGE (lane/clip-fixes; operator, 6 Nov: "I just had to
+ // refresh"): the back button restores this page from the browser's cache
+ // (pageshow, persisted) or a hidden tab comes back, and what is on disk may
+ // have changed meanwhile (a window fetched on the bench). Look again -- the
+ // same file at the same clock keeps playing (settle), so it costs a request.
+ useEffect(() => {
+ const again = () => {
+ const m = media.current;
+ if (m && !m.paused) return;
+ setAttempt((a) => a + 1);
+ };
+ const onShow = (e: PageTransitionEvent) => {
+ if (e.persisted) again();
+ };
+ const onVis = () => {
+ if (document.visibilityState === "visible") again();
+ };
+ window.addEventListener("pageshow", onShow);
+ document.addEventListener("visibilitychange", onVis);
+ return () => {
+ window.removeEventListener("pageshow", onShow);
+ document.removeEventListener("visibilitychange", onVis);
+ };
+ }, []);
+
// Another clip on the same file: go to its cut, paused.
useEffect(() => {
const m = media.current;
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -117,8 +117,24 @@ bench said *"fetched"* over a cache that had not moved. So the button computes
its pad from what is on disk right now and **says the number** ("fetch to
±40 s"), the route refuses a window it can already serve (*"already cached to
±N s"*) rather than running a job to prove it, and a job that did run still has
-to produce a wider file before the bench claims anything arrived. At
-`FETCH_MAX_PAD` it says so instead of offering a press that cannot help.
+to produce a wider file before the bench claims anything arrived. **Each press
+goes on from where the edge is now** — the cache's edge, or an unsaved drag out
+to it — twenty seconds further close in, a minute once the edge is 40 s out.
+There is no cap per side (it was 120 s from the SAVED edge, and a long clip's
+drag stopped dead there); the only cap is the window's, end to end:
+`FETCH_MAX_WINDOW`, the editor's 900 s. At it the side says so — "a fetched
+window is at most 15 min end to end — Fetch whole source for more" — and the
+route refuses a wider ask with the same next step.
+
+**A cut narrower than the clip is drawn on the waveform** — its edges in the
+cut's green with a `cut ▸` / `◂ cut` tab each, the clip's seconds outside it
+hatched — and said above it: *The video plays only the cut …, and gaps go
+inside it*. A gap dragged past it stops at it and says so while it is dragged.
+The tabs drag the cut's edges (written on release, inside the extent as
+drafted, a moved extent saved with it); **Use the whole clip** (and Clear cut)
+clears it; **Undo cut** puts back what either did. A gap's span is the cut,
+else the extent as DRAFTED: an edge dragged out over a wider fetch can be cut
+into at once, and the moved window is saved with the gap.
**One edge at a time.** Extending a window is nearly always one-sided — you
want the sentence that follows, not another twenty seconds of the lead-in you
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -181,7 +181,7 @@ making two clips (a crossfade, a second rail pip, a second subtitle card). `gaps
seconds (`report-to-video/gaps.mjs` is the rule and both clocks).
- **The rule** (the writer's, the build's validators' and `umtool check`'s `clip-gap-invalid`, blocking): each gap
- inside the clip's cut (`cutStart`–`cutEnd`, else its extent), at least 0.2 s, at most 12 of them, in order, apart,
+ inside the clip's cut (`cutStart`–`cutEnd`, else its extent), at least 0.2 s, at most 40 of them, in order, apart,
and at least 0.5 s of material before the first, between any two and after the last. A window, cut or mark save that
would leave a gap outside the cut is refused, as the mute mark's is. **A `muteFrom` or a claim mark's `at` strictly
inside a gap is refused** (on its edge is fine: it lands at the join) — it names a second the cut never plays, and
@@ -500,6 +500,7 @@ the one it always was.
| `scopes` | the ledger's tracks the instruments see (`["weight","regime"]`); a row of any other track is ignored entirely. Default: every track |
| `scale` | `{min, max}` in the ledger's unit: the dial's face. Default: the schema's `yMin`..`yMax` |
| `asOf` | the day the live countdowns and the promise clock count to (YYYY-MM-DD). Default: the day it is built |
+| `ghosts` | the dial's CLAIM GHOSTS: `true`, `{opacity, tolerance, ramp, pulse}`, or `false`/absent (off). A faint tick on the rim for every weight he has claimed, coloured and thickened by how often (Modules, [Scale dial](#scale-dial)) |
**The odometer** (ruled 5 Nov 2026, "go by his words"): only real-time loss claims count -- a `delta` below zero with
no `asOf` and not `retro`; a run's figure is its HIGHEST claim (his figure, over any app's he cites); a row's `run`
@@ -511,7 +512,12 @@ do, `due` when he gave a day) is checked by his later `promise_check` rows namin
another party's `promise_claim` rows (`speaker`, e.g. `madamsavvy`; `paidOn`; a `citeUrl`), and ended by a
`promise_outcome` (`outcome`: `kept` · `refunded` · `withdrawn`); `kept: true` on the promise or a check, or an
outcome `kept`, keeps it. A row with a `speaker` is someone else's: it moves none of his numbers (current, lost, net,
-goals, diet, the totals) and only feeds the promises (`state.promises[].claims`, `.outcome`).
+goals, diet, the totals) and only feeds the promises (`state.promises[].claims`, `.outcome`). A row whose
+`scopeConfidence` is `unresolved` (not a usable claim: a joke, a line that is not his) counts in NO tally -- goals set,
+the goal and the goal board, diets, pledges, promises, the odometer, "under 300" -- pinned or not (pinned, it is
+still on screen, and a reading still reads); the scoreboard's tallies skip another speaker's rows the same way. A
+qualified reading (`>300`, `<300`, `≈390`, a range) that agrees with the specific weight in force does not replace
+it -- not on the dial, not in the panel's WEIGHT cell (`boundAgrees`); one that contradicts it does.
Rows are written through `umtool ledger` only; `umtool measure` prints the slice:
@@ -1275,7 +1281,7 @@ Its cut is `takes/<t>/out/<slug>.<name>.mp4` (the trailer reel: `<slug>.trailer.
| a reel's title, the take it is cut from | **title** | `trailer-beats <p> --reel R title <text>\|none` · `take <t>\|none` | `{op: "settings", title?, take?}` |
| play the reel from a take's master: the crossfades, the clock against the limit, the strip of beats; `M` a note on the beat on screen (anchor `reel`), `E` walk it, `N`/`P` beats, `[`/`]` notes | **Play the reel** → `/projects/<p>/trailer/play?reel=&take=` (the take picker) | `umtool notes <p>` reads the notes | `GET /api/report/reel?project&reel&take` · the master: `GET /api/report/reel/media?project&take&what=master` |
| walk a beat: the reel's own editor on the clip bench's parts -- the master's waveform (its envelope, on the clip's source clock) with the zoom (`z`/`Z`/`f`/`F`, Ctrl/⌘ + wheel; ruler, overview, close-in pauses and words), the handles and nudges (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead) held to what the master rendered of the clip (said when a handle hits it), exact playback (`Space`, `-`/`=` speed), tighten to the sentence and snap an edge to a pause; saved in the clip's source seconds (`Enter`), `R` puts back, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to> [--take <t>]` | `{op: "set", index, patch: {start, end}, take?}` · the master: `GET /api/report/file?project&path&v` · its envelope `GET /api/report/peaks?project&path&from&to` · its sound `GET /api/report/audio?project&path&from&to` |
-| a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 12); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` |
+| a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 40); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` |
| a beat's verdict: `confirmed` (Y, and on to the next) or `note` (a note left on it) | the walk's **Confirm (Y)** · **Note (M)** · **Clear verdict** | `trailer-beats <p> --reel R verdict <n> confirmed\|note\|clear` | `{op: "set", index, patch: {verdict}}` |
| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path; its record names the take's build, the master's mtime and the reel's version, so the Cut panel says when the master was re-rendered or the reel edited since | the Trailer page's **Cut the trailer**; its **Options**: close on the master's last S s (`--finale`), a file name (`--out`, a name only), a dry run | `umtool trailer <p> --reel <name> [--take <t>] [--finale S] [--out NAME] [--dry-run]` | `POST /api/report/reel {project, reel, take, finale?, out?, dryRun?}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` |
@@ -1553,7 +1559,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr
| [Moving start](#moving-start) `peak` | The starting weight as he retells it: a tick per telling on a small scale, a count per repeat, the drift bracketed. (a page over the whole cut) | `render.chrome.deck.peak` |
| [Goal stack](#goal-stack) `goals` | Each goal he names as a sticky note on a pile -- a repeat merged with its count, a deadline counted down to the render date. (a page over the whole cut) | `render.chrome.deck.goals` |
| [Thread rail](#thread-rail) `threads` | A card per thread beside the footage, lit as its clips play. (a page over the whole cut) | `render.chrome.threads` |
-| [Scale dial](#scale-dial) `dial` | A bathroom-scale face: the needle swings to each weight he states, his remembered weights as ghosts, his goal on the bezel. (a page over the whole cut) | `render.chrome.deck.dial` |
+| [Scale dial](#scale-dial) `dial` | A bathroom-scale face: the needle swings to each weight he states, his remembered weights as ghosts, every goal in force on the bezel (the closest headlined), and -- with deck.measure.ghosts -- a faint tick for every weight he has claimed. (a page over the whole cut) | `render.chrome.deck.dial` |
| [Lost odometer](#lost-odometer) `odometer` | Rolling digits of the pounds he says he has lost (only ever up), NET beside them. (a page over the whole cut) | `render.chrome.deck.odometer` |
| [Weight trail](#weight-trail) `trail` | His stated weights by date, drawn up to the playhead, the 300 lb line and the times he says he is under it. (a page over the whole cut) | `render.chrome.deck.trail` |
| [Flips](#flips) `flips` | Pairs of what was said then and now, in the side panel. (a page over the whole cut) | `render.chrome.flips` |
@@ -1844,7 +1850,7 @@ A sticky note per goal on a pile in a corner of the footage box, read off the sc
|---|---|---|
| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
| `deck.goals.position`, `.x`/`.y`, `.scale` | `top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1 | `umtool look <p> deck.goals.position=bottom-left` |
-| `deck.goals.position=shelf` | its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- the headline goal in front when the measure state names one (`goals.headline`: the closest goal in force) with "+N more" for the others in force, else the newest; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial | `umtool look <p> deck.shelf.items='["diet","goals"]' deck.goals.position=shelf` |
+| `deck.goals.position=shelf` | its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs `goalsAt(goalBoard(schedule.measure), t)`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with "+N more" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial | `umtool look <p> deck.shelf.items='["diet","goals"]' deck.goals.position=shelf` |
| `deck.goals.max`, `.color`, `.countdown` | 1–8 notes · #hex paper · bool · default 4, the palette's amber, `true` | `umtool look <p> deck.goals.max=6` |
| `deck.goals.hold`, `.finale` | 0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide` | `umtool look <p> deck.goals.hold=0` |
| `deck.goals.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.goals.onPosts=hide` |
@@ -1861,13 +1867,16 @@ A card per thread in the side panel beside the footage, lit as its clips play; a
### Scale dial
-A bathroom-scale face at the top of the instruments' column (the right of the frame; the clip moves to the left -- `instrumentsGeometry`, 1248×702 footage beside a 600 px column at 1920×1080). It reads the schedule's `measure` (the measure ledger's slice): the red needle swings to each STATED weight at its event's `t` (the spoken word) with a spring (`back.out`, 0.9 s) and rests there -- a frame at rest is reused, not captured again; a qualifier draws a wedge in pounds (≈ 3 under to 1 over, `>` 10 up, `<` 10 down); every REMEMBERED weight is a grey tick, the latest a long ghost needle with its as-of date; the latest goal is an amber tick on the bezel and its words under the digits. It comes and goes with the deck (a card, the finale). With any instrument on, the posts stay in the footage box (`posts.shift` does not apply), and the side panel (`threads`, `flips`) and the posts feed are refused.
+A bathroom-scale face at the top of the instruments' column (the right of the frame; the clip moves to the left -- `instrumentsGeometry`, 1248×702 footage beside a 600 px column at 1920×1080). It reads the schedule's `measure` (the measure ledger's slice): the red needle swings to each STATED weight at its event's `t` (the spoken word) with a spring (`back.out`, 0.9 s) and rests there -- a frame at rest is reused, not captured again; a BOUND that agrees with the specific weight in force (">300" while he is at 342, "≈390" at 388, "330-340" at 337) is no new figure and moves neither the needle nor the number (measure-totals.mjs `boundAgrees`; it still leaves its claim ghost), while one that contradicts it (">300" at 291) moves them as any reading does; a qualifier draws a wedge in pounds (≈ 3 under to 1 over, `>` 10 up, `<` 10 down); every REMEMBERED weight is a grey tick, the latest a long ghost needle with its as-of date. GOALS (measure-goals.mjs `goalBoard`): every goal in force at the playhead is a mark on the bezel at its weight -- in force from the moment the cut shows it until he meets it in time, a newer goal of the same HORIZON replaces it (the same deadline day, the same deadline words, or both undated), or the record's date passes its day. The HEADLINE is the CLOSEST of them -- the least still to lose from his latest stated weight (a range to its top), ties to the soonest deadline -- the full amber tick, its words under the digits (`GOAL 320 · BY APR 2026`); the others a thin amber tick, no words; a range an amber band too. A goal whose day passes with his latest weight over it is MISSED: struck in the needle's red with a red flash, the line under the digits `MISSED 320 · BY APR 2026` for 6 s (`MISS_HOLD`), then gone; a day passing with his weight under it (a reading after the day) leaves quietly. A goal's day: the ledger's `due`, else his `deadline` words read ("by Christmas", "by the end of 2026"), else the row's `asOf`. Any page that shows a goal reads the same board: `goalBoard(schedule.measure)` -> `[{ t, active, headline, missed, cur }]`, `goalsAt(board, t)`. It comes and goes with the deck (a card, the finale). With any instrument on, the posts stay in the footage box (`posts.shift` does not apply), and the side panel (`threads`, `flips`) and the posts feed are refused.
| Knob | Range · default | From a terminal |
|---|---|---|
| `deck.dial` | `true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off | `umtool look <p> deck.dial=false` |
| `deck.dial.mark` | a weight, or `null` · default `300` (its tick and label in the accent) | `umtool look <p> deck.dial.mark=300` |
-| `deck.dial.ghosts`, `.goal` | bool · default `true` each | `umtool look <p> deck.dial.ghosts=false` |
+| `deck.dial.ghosts`, `.goal` | bool · default `true` each (`.goal`: every goal in force, the closest headlined) | `umtool look <p> deck.dial.ghosts=false` |
+| `deck.measure.ghosts` | `true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t | `umtool look <p> deck.measure.ghosts=true` |
+| `deck.measure.ghosts.opacity`, `.tolerance` | 0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5` | `umtool look <p> deck.measure.ghosts='{"tolerance":1}'` |
+| `deck.measure.ghosts.ramp`, `.pulse` | 2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true` | `umtool look <p> deck.measure.ghosts='{"ramp":["#98a29b","#e8a33f","#f37e47"],"pulse":false}'` |
| `deck.dial.needle` | a #hex · default `#ff5a4e` | `umtool look <p> deck.dial.needle='"#ff5a4e"'` |
| `deck.dial.label` | words over the digits, ≤ 40 · default `HE SAYS HE WEIGHS` | `umtool look <p> deck.dial.label='"…"'` |
| `deck.dial.finale` | bool · default `true`: the dial and the odometer large in the finale (module `dial-finale`) | `umtool look <p> deck.dial.finale=false` |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -183,7 +183,7 @@ the verdict". Play the cut skips it like a fact error; a take does not refuse it
`gaps: [{from, to}]` (source seconds) takes seconds out of the middle of a clip, which then renders as ONE segment of
jump cuts — one header, one pip, one subtitle card — rather than as two clips with a crossfade. Each gap lies inside
-the CUT (the extent when there is none), at least 0.2 s, at most 12, apart, with 0.5 s kept at the edges and between
+the CUT (the extent when there is none), at least 0.2 s, at most 40, apart, with 0.5 s kept at the edges and between
them; a mute mark or claim mark inside one is refused. `umtool check` reports a malformed gap as `clip-gap-invalid`,
**blocking**, as it does `clip-cut-outside`. The build trims the kept pieces on the frame grid and joins them with a
25 ms sound fade at each join; the cut record names the gaps, and every source-to-cut mapping reads it. Written by the
diff --git a/umtool/e2e/clip-bench.spec.ts b/umtool/e2e/clip-bench.spec.ts
@@ -1601,3 +1601,129 @@ test("the last attribution field is on screen at a laptop's 1366×768", async ({
await expect(page.locator("[data-reject-menu]")).toBeInViewport();
expect(await reachable()).toBeLessThanOrEqual(0);
});
+
+
+// ---------------------------------------------------------------------------
+// Fetch more goes on from where the edge is NOW (lane/clip-fixes; operator,
+// 6 Nov: "I try to drag a clip and it just doesn't expand beyond a certain
+// point"). The pads were capped at 120 s per side measured from the clip's
+// SAVED edges, so an edge dragged (unsaved) to the cache's edge could never be
+// given more than 120 s past where it was last saved. Now the only cap is the
+// window's, end to end (the editor's 900 s). reach-fixture: r01 reachvid
+// 300-306 on a recording 1000 s long, fetched through the editor stub.
+// ---------------------------------------------------------------------------
+
+const REACH = "reports/reach-fixture";
+const REACH_MANIFEST = path.join(FIXTURE, "reports", "reach-fixture", "video.manifest.json");
+const reachClip = () =>
+ (JSON.parse(readFileSync(REACH_MANIFEST, "utf8")) as { timeline: { id: string; start: number; end: number }[] }).timeline.find((e) => e.id === "r01")!;
+const reachWindows = async (request: import("@playwright/test").APIRequestContext) =>
+ ((await (await request.get(`/api/report/clip?project=${encodeURIComponent(REACH)}&clip=r01`)).json()) as { windows: { from: number; to: number }[] }).windows;
+const waitJob = async (request: import("@playwright/test").APIRequestContext, id: string) =>
+ expect
+ .poll(async () => ((await (await request.get(`/api/report/fetch?job=${id}`)).json()) as { job: { state: string } | null }).job?.state ?? "gone", { timeout: 120_000 })
+ .not.toBe("running");
+/** The end handle dragged out past the waveform's right end: it stops at the cache's edge -- a drag, never a fetch. */
+const endToCacheEdge = async (page: import("@playwright/test").Page) => {
+ const canvas = page.locator("[data-wave-box] [data-testid=waveform]");
+ await canvas.scrollIntoViewIfNeeded();
+ const b = (await canvas.boundingBox())!;
+ const y = b.y + b.height / 2;
+ await page.mouse.move(b.x + b.width - 4, y);
+ await page.mouse.down();
+ await page.mouse.move(b.x + b.width + 60, y, { steps: 3 });
+ await page.mouse.up();
+};
+const selOf = async (page: import("@playwright/test").Page) =>
+ ((await page.locator("[data-bench-sel]").getAttribute("data-bench-sel")) ?? "").split("-").map(Number);
+
+test("fetch more goes on from the edge as dragged, past 120 s from the saved edge, without saving", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ // A window 100 s past the clip's end, as a long clip's first widening leaves it.
+ const seed = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter: 100 } });
+ expect(seed.status(), await seed.text()).toBe(202);
+ await waitJob(request, ((await seed.json()) as { job: { id: string } }).job.id);
+ expect((await reachWindows(request))[0].to).toBeCloseTo(406, 1);
+
+ const posts: { padBefore: number; padAfter: number }[] = [];
+ page.on("request", (r) => {
+ if (r.method() === "POST" && r.url().endsWith("/api/report/fetch")) posts.push(r.postDataJSON());
+ });
+ await page.goto(urls.clipBenchHref(REACH, "r01"));
+ await expect(page.locator("[data-bench=r01]")).toBeVisible();
+
+ for (const [edge, ask] of [
+ [406, 160],
+ [466, 220],
+ ] as const) {
+ await endToCacheEdge(page);
+ await expect.poll(async () => (await selOf(page))[1]).toBeCloseTo(edge, 0);
+ // From the edge as it is now (100 s, then 160 s out), a minute further: never capped at 120.
+ const after = page.locator("[data-fetch-after]");
+ await expect(after).toHaveAttribute("data-fetch-after", String(ask));
+ await after.click();
+ await expect(page.locator("[data-bench-note]")).toContainText("fetched later", { timeout: 60_000 });
+ }
+ // The edge drags on into what arrived: 220 s past the saved end, and nothing saved.
+ await endToCacheEdge(page);
+ await expect.poll(async () => (await selOf(page))[1]).toBeGreaterThan(306 + 120);
+ expect(reachClip().end).toBe(306);
+ // Two presses, two fetches -- the drags downloaded nothing -- each keeping the before side as cached.
+ expect(posts.map((p) => [p.padBefore, p.padAfter])).toEqual([
+ [3, 160],
+ [3, 220],
+ ]);
+});
+
+test("a window wider than the editor's 900 s is refused with the next step, not clamped", async ({ request }) => {
+ const r = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter: 950 } });
+ expect(r.status()).toBe(400);
+ const j = (await r.json()) as { error: string; maxWindow: number };
+ expect(j.maxWindow).toBe(900);
+ expect(j.error).toContain("at most 900 s end to end");
+ expect(j.error).toContain("whole source");
+});
+
+// ---------------------------------------------------------------------------
+// Coming back to the bench (lane/clip-fixes; operator, 6 Nov: "I just had to
+// refresh. Maybe address that so it updates if you click the back button").
+// The back button restores the page as it was shown -- Next's router cache, or
+// the browser's page cache (pageshow, persisted) -- so a window fetched
+// meanwhile did not show. The bench reads its state again on mount, on
+// pageshow (persisted) and when the tab comes back; it never fetches to do so.
+// ---------------------------------------------------------------------------
+
+test("back to the bench shows the window fetched meanwhile, and so does a page restored from the page cache -- without a fetch", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ const visTo = async () => Number(((await page.locator("[data-wave-box]").getAttribute("data-wave-vis")) ?? "").split("-")[1]);
+ const widen = async (padAfter: number) => {
+ const r = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter } });
+ expect(r.status(), await r.text()).toBe(202);
+ await waitJob(request, ((await r.json()) as { job: { id: string } }).job.id);
+ return (await reachWindows(request))[0].to;
+ };
+ const before = (await reachWindows(request))[0]?.to ?? (await widen(30));
+ const fetches: string[] = [];
+ page.on("request", (r) => {
+ if (r.method() === "POST" && r.url().endsWith("/api/report/fetch")) fetches.push(r.url());
+ });
+ await page.goto(urls.clipBenchHref(REACH, "r01"));
+ await expect.poll(visTo).toBeCloseTo(before, 1);
+
+ // Away through the app's own link (a client navigation), a wider window
+ // fetched meanwhile (another tab, a CLI), and back.
+ await page.locator("[data-bench-back]").click();
+ await expect(page.locator("[data-bench=r01]")).toHaveCount(0);
+ const wider = await widen(Math.round(before - 306) + 30);
+ expect(wider).toBeGreaterThan(before + 1);
+ await page.goBack();
+ await expect(page.locator("[data-bench=r01]")).toBeVisible();
+ await expect.poll(visTo, { timeout: 15_000 }).toBeCloseTo(wider, 1);
+
+ // A page the browser restored from its page cache says so with pageshow (persisted).
+ const widest = await widen(Math.round(wider - 306) + 30);
+ await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })));
+ await expect.poll(visTo, { timeout: 15_000 }).toBeCloseTo(widest, 1);
+ // The bench fetched nothing to show any of it.
+ expect(fetches).toEqual([]);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -821,6 +821,14 @@ CUES.tightvid = CUES.vid1.map((r) => [...r]);
// The clip-export spec's Export ▾ source (clip-export.spec.ts): a recording nothing else fetches, so
// its full-exchange fetch (through the editor stub) moves no other spec's cache.
CUES.exportvid = CUES.vid1.map((r) => [...r]);
+// The clip bench's long reach (clip-bench.spec.ts, "fetch more goes on from the edge"): a
+// recording a thousand seconds long, so a window can be fetched far past any clip on it --
+// a fetch more is measured from where the edge is NOW, and a window may be 900 s end to end.
+CUES.reachvid = [
+ [0, 3, "The start of a long recording."],
+ [300, 306, "The clip sits here, five minutes in."],
+ [996, 1000, "And the recording ends here."],
+];
for (const [vid, rows] of Object.entries(CUES)) {
const dir = path.join(CHANNELS, "testchan", "data", vid);
mkdirSync(dir, { recursive: true });
@@ -1950,6 +1958,14 @@ makeMediaScenesFixture({ reports, deckManifest });
mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4"));
}
+// Fetch more from where the edge is now (clip-bench.spec.ts): one clip, r01 reachvid 300-306, on a
+// recording a thousand seconds long; nothing cached -- the spec fetches through the editor stub.
+writeProject(
+ "reach-fixture",
+ manifest("reach-fixture", "The Reach Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "r01", video: "reachvid", start: 300, end: 306, cite: 300, section: 0, quote: "the clip sits here" },
+ ]),
+);
// Tighten to the sentence, snap an edge to its pause, and the batch's proposals (tighten.spec.ts),
// which WRITES (the spec puts the manifest back before each test): its own project on tightvid
// (vid1's cues; sentences 0-3, 3-9, 9-12), the tone window cached as tightvid_0.00-9.00.mp4, and
diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts
@@ -317,3 +317,167 @@ test("Play the cut on a take plays a gapped clip's kept pieces only", async ({ p
expect(got.clips.find((c: { id: string }) => c.id === "g01")).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 });
await playsJumpCut(page, "gapped");
});
+
+// ---------------------------------------------------------------------------
+// A cut narrower than the clip (lane/clip-fixes; operator, 6 Nov: "I can't add
+// gaps beyond like 9:21"): an extent widened over a cut kept from an earlier
+// pass. Gaps lie inside the cut, so every gap stopped at the cut's end with
+// nothing on the waveform to say why. Now the cut is drawn there, said above
+// it, its edges drag, and Use the whole clip clears it -- each with an Undo.
+// ---------------------------------------------------------------------------
+
+const cutOf = () => {
+ const e = (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; cutStart?: number; cutEnd?: number }[] }).timeline.find((x) => x.id === "g01")!;
+ return { cutStart: e.cutStart ?? null, cutEnd: e.cutEnd ?? null };
+};
+const SHOTS = process.env.E2E_CLIP_FIXES_SHOTS ?? null;
+const shot = async (page: Page, name: string) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ await page.locator("[data-wave-box]").screenshot({ path: path.join(SHOTS, `${name}.png`) });
+};
+
+test("a cut narrower than the clip: drawn on the waveform, said, a gap stops at it with the reason, its edge drags, Use the whole clip", async ({ page, request }) => {
+ expect((await putWindow(request, { cutStart: 1, cutEnd: 4 })).ok()).toBeTruthy();
+ try {
+ await openBench(page);
+ await expect(page.locator("[data-cut-limits]")).toContainText("The video plays only the cut");
+ await expect(page.locator("[data-cut-limits]")).toContainText("gaps go inside it");
+ await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(2);
+ await expect(page.locator("[data-wave-outside-cut]")).toHaveCount(2);
+ await shot(page, "cut-narrower");
+
+ // Alt + drag from inside the cut out past its end: the span stops at the cut's
+ // end, and -- BEFORE release -- turns red and says why, the clamp included.
+ await page.keyboard.down("Alt");
+ const y = await midY(page);
+ await page.mouse.move(await xAt(page, 2.5), y);
+ await page.mouse.down();
+ await page.mouse.move(await xAt(page, 6), y, { steps: 4 });
+ const live = page.locator("[data-gap-selection-why]");
+ await expect(live).toContainText("stopped at the cut's end");
+ await expect(live).toContainText("keep at least 0.5 s");
+ await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused");
+ expect(spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection"))[1]).toBeCloseTo(4, 2);
+ await shot(page, "gap-at-cut-wall");
+ await page.mouse.up();
+ await page.keyboard.up("Alt");
+ await expect(page.locator("[data-bench-note]")).toContainText("stopped at the cut's end");
+ await page.locator("body").press("Escape");
+
+ // The cut's end tab drags the edge out; written on release, with an Undo.
+ const grip = page.locator("[data-wave-cut-grip=end]");
+ const gb = (await grip.boundingBox())!;
+ await page.mouse.move(gb.x + gb.width / 2, gb.y + gb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(await xAt(page, 7), gb.y + gb.height / 2, { steps: 5 });
+ await page.mouse.up();
+ await expect.poll(() => cutOf().cutEnd ?? 0).toBeGreaterThan(6.5);
+ expect(cutOf().cutStart).toBe(1);
+ await expect(page.locator("[data-bench-note]")).toContainText("the cut moved to");
+ await page.locator("[data-cut-undo]").click();
+ await expect.poll(() => cutOf().cutEnd).toBe(4);
+
+ // Use the whole clip: the cut cleared, the wall gone; Undo puts it back.
+ await page.locator("[data-cut-use-whole]").click();
+ await expect.poll(() => cutOf().cutStart).toBeNull();
+ await expect(page.locator("[data-cut-limits]")).toHaveCount(0);
+ await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(0);
+ await page.locator("[data-cut-undo]").click();
+ await expect.poll(() => cutOf()).toEqual({ cutStart: 1, cutEnd: 4 });
+ await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(2);
+ } finally {
+ expect((await putWindow(request, { cutStart: "", cutEnd: "", lockCut: false })).ok()).toBeTruthy();
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Every wall a gap stops at is drawn and said (lane/clip-fixes; operator, 6
+// Nov: "the gap tool gets blocked at random invisible walls in the clip"): the
+// no-cut zones (outside the span, the keep bands at its edges and beside each
+// gap), a tick at each second a gap can't cover, and the writer's whole rule
+// checked on every move -- the claim marks included, which the bench used to
+// leave to the writer, which then refused with a sentence the bench had not
+// said.
+// ---------------------------------------------------------------------------
+
+/** Put a claim mark's second on g01 (`claim: {id, verdict, at}`), straight into the manifest; null takes it off. */
+const setStamp = (at: number | null) => {
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Record<string, unknown>[] };
+ const e = m.timeline.find((x) => x.id === "g01")!;
+ if (at == null) delete e.claim;
+ else e.claim = { id: "k9", verdict: "CORROBORATED", at };
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+};
+/** An Alt + drag from a to b, held (not released): what the span says WHILE it is dragged. */
+const altDragHeld = async (page: Page, a: number, b: number) => {
+ await page.keyboard.down("Alt");
+ const y = await midY(page);
+ await page.mouse.move(await xAt(page, a), y);
+ await page.mouse.down();
+ await page.mouse.move(await xAt(page, b), y, { steps: 4 });
+};
+const altRelease = async (page: Page) => {
+ await page.mouse.up();
+ await page.keyboard.up("Alt");
+};
+
+test("the walls are drawn: no-cut zones and the marks a gap can't cover; a drag into one turns red with the reason before release; a gap over a claim mark is refused with the writer's sentence", async ({ page, request }) => {
+ expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy();
+ setStamp(7);
+ try {
+ await openBench(page);
+ // The zones: outside the clip (the view runs 0-9, the clip 0.5-8.5), 0.5 s
+ // at each of its edges, and 0.5 s either side of the gap.
+ const kinds = await page.locator("[data-gap-nocut]").evaluateAll((els) => els.map((e) => `${e.getAttribute("data-gap-nocut")} ${e.getAttribute("data-gap-nocut-at")}`));
+ expect(kinds).toEqual(
+ expect.arrayContaining(["outside 0.00-0.50", "outside 8.50-9.00", "keep-start 0.50-1.00", "keep-end 8.00-8.50", "keep-gap 3.00-3.50", "keep-gap 5.50-6.00"]),
+ );
+ await expect(page.locator("[data-gap-nocut='keep-gap']").first()).toHaveAttribute("title", /keep at least 0.5 s between cuts/);
+ await expect(page.locator("[data-gap-span-edge]")).toHaveCount(2);
+ // The mark's second, ticked, with what it means on hover.
+ const tick = page.locator("[data-gap-wall-mark='7']");
+ await expect(tick).toHaveAttribute("data-gap-wall-mark-kind", "mark");
+ await expect(tick.locator("span")).toHaveAttribute("title", /a gap can't cover this/);
+ await shot(page, "walls");
+
+ // Into the keep band beside the gap: red, and why, while still dragging.
+ await altDragHeld(page, 5.7, 6.6);
+ await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused");
+ await expect(page.locator("[data-gap-selection-why]")).toContainText("keep at least 0.5 s");
+ await shot(page, "gap-into-keep-band");
+ await altRelease(page);
+ await page.locator("body").press("Escape");
+
+ // Over the mark's second: refused here, with the writer's own sentence.
+ await altDragHeld(page, 6.6, 7.6);
+ await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused");
+ await expect(page.locator("[data-gap-selection-why]")).toContainText("the mark k9's second (at 7) lies inside the gap");
+ await shot(page, "gap-over-mark");
+ await altRelease(page);
+ const [a, b] = spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection"));
+ const posts: string[] = [];
+ page.on("request", (r) => {
+ if (r.method() === "PUT" && r.url().endsWith("/api/report/window")) posts.push(r.url());
+ });
+ await page.locator("[data-gap-cut]").click();
+ // The writer, asked the same span, says the same thing (less the clip id it starts with).
+ const r = await putWindow(request, { gapAdd: `${a}-${b}` });
+ expect(r.status()).toBe(400);
+ const said = ((await r.json()) as { error: string }).error.replace(/^g01: /, "");
+ expect(said).toContain("the mark k9's second (at 7) lies inside the gap");
+ await expect(page.locator("[data-bench-note]")).toContainText(`not cut: ${said}`);
+ // Refused before anything was sent.
+ expect(posts).toEqual([]);
+ expect(clipOf("g01").gaps).toEqual([{ from: 3.5, to: 5.5 }]);
+
+ // Touching the gap: no wall -- it says the two become one.
+ await page.locator("body").press("Escape");
+ await altDragHeld(page, 5.2, 6.4);
+ await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "merge");
+ await expect(page.locator("[data-gap-selection-why]")).toContainText("touches a gap — cutting makes one gap 3.50–");
+ await altRelease(page);
+ } finally {
+ setStamp(null);
+ }
+});
diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts
@@ -11,7 +11,8 @@ import {
} from "@/lib/projects/report.mjs";
import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs";
import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs";
-import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs";
+import { FETCH_MAX_WINDOW } from "@/lib/report/driver.mjs";
+import { gapWalls } from "umtool-report-to-video/gaps";
import { deckOn } from "umtool-report-to-video/deck";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import { readWorkingCut } from "@/lib/report/workingCut.mjs";
@@ -132,6 +133,9 @@ export async function clipBenchData(
gaps:
((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId)
?.gaps ?? [],
+ // The seconds no gap may cover (claim marks, a stamp), from the manifest's own entry.
+ marks: gapWalls({ ...(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}), type: "clip", muteFrom: null })
+ .marks.map((m) => ({ id: m.id, at: m.at })),
verdict:
entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null,
// What the walk said that is not a verdict, and a deliberate repeat.
@@ -201,7 +205,7 @@ export async function clipBenchData(
// The widest the fetch route will go. The BUTTON has to know it: it names
// the pad it will ask for, and "that is as wide as it goes" is a different
// sentence from a number the server quietly clamps.
- maxPad: FETCH_MAX_PAD,
+ maxWindow: FETCH_MAX_WINDOW,
// The widest cached RAW window: it has no chrome burned in, which is what a
// mix is looking at, and it exists as soon as the clip has been fetched
// once. start/end are the window minus the file's own start, because a mix
diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs
@@ -285,13 +285,20 @@ export function narrateCardSteps(project, cardId) {
}
/**
- * The widest pad the bench may ask for.
+ * The widest WINDOW the bench may ask for, in seconds, end to end: the
+ * editor's own cap on one fetched window (common/lib/clipWindow.ts
+ * MAX_CLIP_WINDOW_SECONDS; POST /api/media/fetch-window refuses wider). Past it
+ * the answer is the whole recording.
*
- * Here rather than in the route, because the BENCH has to know it too: the
- * button reads "fetch to ±N s" and has to say "that is as wide as it goes"
- * rather than offering a number the server will quietly clamp.
+ * It replaced a cap of 120 s PER SIDE measured from the clip's SAVED edges
+ * (lane/clip-fixes, operator 6 Nov: "I try to drag a clip and it just doesn't
+ * expand beyond a certain point"): an edge dragged out to the cached edge could
+ * never be given more than 120 s past where it was last saved, and the bench
+ * went quiet there. Here rather than in the route, because the BENCH has to
+ * know it too: the button says how far it will ask, and says when this is the
+ * limit, rather than offering a number the server would refuse.
*/
-export const FETCH_MAX_PAD = 120;
+export const FETCH_MAX_WINDOW = 900;
/**
* Fetch ONE clip's window, wide. What the bench's "fetch more" runs.
diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs
@@ -19,6 +19,8 @@ import { finaleLayout } from "./chrome-finale.mjs";
import { FINALE_MOTION } from "./finale.mjs";
import { resolveDial, resolveOdometer, resolveTrail } from "./instruments.mjs";
import { promiseStates, upSpans } from "./measure-extras.mjs";
+import { ghostOpacity, ghostRamp, ghostTicks, resolveGhosts } from "./measure-ghosts.mjs";
+import { goalBoard, goalsAt } from "./measure-goals.mjs";
import { resolveMeasureExtra } from "./modules/measure-extras-settings.mjs";
import {
cueList, dayNumber, dialAngle, dialFaceSvg, dialFigures, DIAL_SWEEP, esc, fmtDate, fmtSigned, fmtWeight, INSTANT, measureTrack,
@@ -119,6 +121,64 @@ export const goalWords = (g) => {
return when ? `${what} · ${String(when).toUpperCase()}` : what;
};
+/** A goal's day as the dial says it: his words ("BY CHRISTMAS 2026", the year added when they name none), else "BY APR 2026". */
+export function goalWhen(g) {
+ const year = /^(\d{4})-/.exec(String(g?.deadlineDate ?? ""))?.[1] ?? null;
+ if (g?.deadline) return `${String(g.deadline).toUpperCase()}${year && !/\d{4}/.test(g.deadline) ? ` ${year}` : ""}`;
+ return g?.deadlineDate ? `BY ${fmtDate(g.deadlineDate, { day: false })}` : "";
+}
+
+/**
+ * A goal board's goal (measure-goals.mjs) in words: "GOAL 320 · BY APR 2026", "GOAL 230–240",
+ * "GOAL 250 · LOSE 50" (a loss resolved, no day), "LOSE 75" (unresolved); `missed`: "MISSED 320 · BY APR 2026".
+ */
+export function boardGoalWords(g, { missed = false } = {}) {
+ if (!g) return "";
+ const when = goalWhen(g);
+ const num = Array.isArray(g.range) && g.range.length === 2 ? `${fmtWeight(g.range[0])}–${fmtWeight(g.range[1])}`
+ : Number.isFinite(g.target) ? fmtWeight(g.target) : null;
+ if (missed) return [`MISSED ${num ?? (Number.isFinite(g.loss) ? `LOSE ${fmtWeight(g.loss)}` : "GOAL")}`, when].filter(Boolean).join(" · ");
+ const what = num !== null
+ ? `GOAL ${num}${g.kind === "goalLoss" && Number.isFinite(g.loss) && !when ? ` · LOSE ${fmtWeight(g.loss)}` : ""}`
+ : Number.isFinite(g.loss) ? `LOSE ${fmtWeight(g.loss)}` : "GOAL";
+ return [what, when].filter(Boolean).join(" · ");
+}
+
+/**
+ * The goal board's goals as the dial marks them: each goal the board ever holds (in the order it first does), its
+ * angle (null when it has no weight on the face), and its status in each board state -- "head", "other", "missed"
+ * (with `wasHeadline`) or "off".
+ */
+export function goalMarks(board, scale) {
+ const goals = [];
+ const index = new Map();
+ for (const b of board) {
+ for (const g of [...b.active, ...b.missed]) {
+ if (index.has(g.row)) continue;
+ index.set(g.row, goals.length);
+ const onFace = Number.isFinite(g.target) && g.target >= scale.min && g.target <= scale.max;
+ const r = g.range;
+ const band = Array.isArray(r) && dialAngle(r[1], scale) > dialAngle(r[0], scale);
+ goals.push({ goal: g, angle: onFace ? dialAngle(g.target, scale) : null, band });
+ }
+ }
+ const statusIn = (b, row) => {
+ const m = b.missed.find((x) => x.row === row);
+ if (m) return { status: "missed", wasHeadline: !!m.wasHeadline };
+ if (b.headline?.row === row) return { status: "head" };
+ return b.active.some((x) => x.row === row) ? { status: "other" } : { status: "off" };
+ };
+ return goals.map((x) => ({ ...x, states: board.map((b) => ({ t: b.t, ...statusIn(b, x.goal.row) })) }));
+}
+
+/** What the goal line under the digits says in each board state: the latest miss while it is held, else the headline. */
+export function goalLines(board) {
+ return board.map((b) => {
+ const miss = [...b.missed].sort((x, y) => x.at - y.at).pop();
+ return { t: b.t, words: miss ? boardGoalWords(miss, { missed: true }) : boardGoalWords(b.headline), missed: !!miss };
+ });
+}
+
// ---------------------------------------------------------------------------
// The dial.
// ---------------------------------------------------------------------------
@@ -179,7 +239,7 @@ function asofSpots({ C, Rf, u, a, head, forms, px, fpx }) {
* the hub and the readout blocks. Shared by the column's dial and the
* finale's. Returns its markup and css; its cues are the caller's.
*/
-function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, prefix = "", preState = true }) {
+function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [], lines = [], ghosts = null, prefix = "", preState = true }) {
const face = dialFaceSvg({ size, scale, mark: cfg.mark, colors: { ...colors, mark: colors.accent }, labelFont: fontStack(fonts, "condensed") });
const { C, R, Rf, u } = face;
const px = (v) => Math.round(v * u * 100) / 100;
@@ -188,6 +248,20 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, prefix = ""
const layer = (k, inner, cls = "ly") => `<div class="${cls}" data-k="${prefix}${k}"><svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${inner}</svg></div>`;
const parts = [];
parts.push(`<div class="ly face">${face.svg}</div>`);
+ // The claim ghosts (deck.measure.ghosts, measure-ghosts.mjs): under everything on the face, a thin tick across the
+ // rim at each value he has claimed -- one line per step of the ramp (its colour, a little thicker each step), the
+ // step its count is on shown, and a pulse line that flashes as a repeat lands.
+ if (ghosts) {
+ // From just in from the bezel's outer edge to just short of the scale's ticks (they start 6 px in).
+ const r0 = C - R + 2 * u, r1 = C - Rf + 8 * u;
+ ghosts.ticks.forEach((x, i) => {
+ const lines = ghosts.ramp.map((c, k) =>
+ `<div class="ly" data-k="${prefix}gt${i}s${k}"><svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><line x1="${C}" y1="${r0}" x2="${C}" y2="${r1}" stroke="${c}" stroke-width="${px(ghostWidth(k, ghosts.ramp.length))}" stroke-linecap="round"/></svg></div>`).join("");
+ const pulses = ghosts.cfg.pulse ? ghosts.ramp.map((c, k) => (k === 0 ? "" :
+ `<div class="ly" data-k="${prefix}gt${i}p${k}"><svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><line x1="${C}" y1="${C - R - 1 * u}" x2="${C}" y2="${C - Rf + 14 * u}" stroke="${c}" stroke-width="${px(ghostWidth(k, ghosts.ramp.length) + 2)}" stroke-linecap="round"/></svg></div>`)).join("") : "";
+ parts.push(`<div class="ly" data-k="${prefix}gt${i}">${lines}${pulses}</div>`);
+ });
+ }
// Where words laid on the face must not go: its scale figures, and the hub.
const faceFigures = dialFigures({ size, scale, mark: cfg.mark });
const hub = { x0: C - 18 * u, x1: C + 18 * u, y0: C - 18 * u, y1: C + 18 * u };
@@ -223,13 +297,20 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, prefix = ""
parts.push(`<div class="qlab" data-k="${prefix}ql${j}" style="left:${spot.x}px; top:${spot.y}px">${esc(words)}</div>`);
});
if (cfg.goal) {
- parts.push(layer("gl", `<polygon points="${C - 11 * u},${C - R - 2 * u} ${C + 11 * u},${C - R - 2 * u} ${C},${C - Rf + 16 * u}" fill="${colors.amber}" stroke="${colors.bg}" stroke-width="${px(2)}"/>`));
- // A goal he gave as a range: the tick spans it, an amber band on the bezel.
- track.goals.forEach((g, j) => {
- const r = g.goal?.range;
- if (!Array.isArray(r)) return;
- const b0 = dialAngle(r[0], scale), b1 = dialAngle(r[1], scale);
- if (b1 > b0) parts.push(`<div class="ly" data-k="${prefix}gr${j}"><svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><path d="${sectorPath(C, C, Rf + 2 * u, R + 4 * u, b0, b1)}" fill="${colors.amber}" fill-opacity="0.9"/></svg></div>`);
+ // EVERY goal in force (measure-goals.mjs goalBoard), each a mark on the bezel at its weight: the headline -- the
+ // closest -- the full amber triangle; the others a thin amber tick; a missed one struck through in the needle's
+ // red, a red flash as it is missed. A range is an amber band on the bezel besides (its headline's brighter).
+ const svg = (k, inner) => `<div class="ly" data-k="${prefix}${k}"><svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${inner}</svg></div>`;
+ marks.forEach((m, i) => {
+ const r = m.goal.range;
+ if (m.band) parts.push(svg(`gb${i}`, `<path d="${sectorPath(C, C, Rf + 2 * u, R + 4 * u, dialAngle(r[0], scale), dialAngle(r[1], scale))}" fill="${colors.amber}"/>`));
+ if (m.angle === null) return;
+ const head = `<polygon points="${C - 11 * u},${C - R - 2 * u} ${C + 11 * u},${C - R - 2 * u} ${C},${C - Rf + 16 * u}" fill="${colors.amber}" stroke="${colors.bg}" stroke-width="${px(2)}"/>`;
+ const other = `<polygon points="${C - 7 * u},${C - R - 1 * u} ${C + 7 * u},${C - R - 1 * u} ${C},${C - Rf + 11 * u}" fill="${colors.amber}" stroke="${colors.bg}" stroke-width="${px(1.5)}"/>`;
+ const strike = `<line x1="${C - 13 * u}" y1="${C - R + 1 * u}" x2="${C + 13 * u}" y2="${C - Rf + 12 * u}" stroke="${colors.needle}" stroke-width="${px(4)}" stroke-linecap="round"/>` +
+ `<line x1="${C + 13 * u}" y1="${C - R + 1 * u}" x2="${C - 13 * u}" y2="${C - Rf + 12 * u}" stroke="${colors.needle}" stroke-width="${px(4)}" stroke-linecap="round"/>`;
+ const flash = `<polygon points="${C - 17 * u},${C - R - 5 * u} ${C + 17 * u},${C - R - 5 * u} ${C},${C - Rf + 26 * u}" fill="none" stroke="${colors.needle}" stroke-width="${px(3)}" stroke-linejoin="round"/>`;
+ parts.push(`<div class="ly" data-k="${prefix}gm${i}">${svg(`gm${i}h`, head)}${svg(`gm${i}o`, other)}${svg(`gm${i}x`, strike)}${svg(`gm${i}p`, flash)}</div>`);
});
}
if (cfg.ghosts && track.remembered.length) {
@@ -265,8 +346,8 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, prefix = ""
parts.push(`<div class="read${pre ? " pre" : ""}" data-k="${prefix}cv${j}" style="top:${C + 86 * u}px"><div class="big">${has ? `${esc(weightWords(c))}<i>LB</i>` : pre ? "NO WEIGHT<br>STATED YET" : "—"}</div>${has && c.date ? `<div class="when" style="top:${78 * u}px">${esc(fmtDate(c.date))}</div>` : ""}</div>`);
});
if (cfg.goal) {
- track.goals.forEach((g, j) => {
- parts.push(`<div class="goalw" data-k="${prefix}gw${j}" style="top:${C + 188 * u}px">${esc(goalWords(g.goal))}</div>`);
+ lines.forEach((g, j) => {
+ parts.push(`<div class="goalw${g.missed ? " miss" : ""}" data-k="${prefix}gw${j}" style="top:${C + 188 * u}px">${esc(g.words)}</div>`);
});
}
const css = `
@@ -291,15 +372,25 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, prefix = ""
.dial .qlab { position: absolute; transform: translate(-50%, -50%); font-family: ${fontStack(fonts, "display")}; font-size: ${px(26)}px;
color: ${colors.accent}; white-space: nowrap; padding: ${px(1)}px ${px(6)}px; border-radius: ${px(5)}px; background: ${rgba(colors.face, 0.9)}; }
.dial .goalw { position: absolute; left: 0; width: ${size}px; text-align: center; font-family: ${fontStack(fonts, "bold")};
- font-size: ${fpx(17)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.05em; color: ${colors.amber}; white-space: nowrap; }`;
+ font-size: ${fpx(17)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.05em; color: ${colors.amber}; white-space: nowrap; }
+ .dial .goalw.miss { color: ${colors.needle}; }`;
return { html: `<div class="dial">${parts.join("\n ")}</div>`, css, face };
}
+/** A claim ghost's width (face px at 524) on step `k` of a ramp of `n`: 1.8 at 1x to 3.4 at the last. */
+export const ghostWidth = (k, n) => Math.round((1.8 + (n > 1 ? (k / (n - 1)) * 1.6 : 0)) * 100) / 100;
+
+/** The claim ghosts' seconds: a step's fade, a pulse's flash and its decay. */
+export const GHOST_MOTION = Object.freeze({ fade: 0.35, flash: 0.12, decay: 0.9 });
+
+/** A miss's flash: in, held, out (s). */
+export const MISS_MOTION = Object.freeze({ in: 0.15, hold: 0.5, out: 0.8 });
+
/** The needle's ease (`deck.dial.motion`): the spring's overshoot and settle, or a plain ease. */
const needleEase = (cfg, spring = INSTRUMENT_MOTION.needleEase) => (cfg.motion === "ease" ? INSTRUMENT_MOTION.needlePlain : spring);
/** The dial's cues over the cut: the needle on each stated weight, the ghosts, the wedges, the goal, the readout. */
-function dialCues(L, { track, scale, cfg, prefix = "", finale = false }) {
+function dialCues(L, { track, scale, cfg, marks = [], lines = [], ghosts = null, prefix = "", finale = false, at = 0 }) {
const M = INSTRUMENT_MOTION;
const a0 = DIAL_SWEEP.a0;
const k = (s) => `${prefix}${s}`;
@@ -352,37 +443,85 @@ function dialCues(L, { track, scale, cfg, prefix = "", finale = false }) {
blocks(L, track.remembered, k("ga"), { fade: M.fade });
}
}
- if (cfg.goal) {
- // A goal off the face (a loss resolved below the scale's foot: "lose 100" from 240) has no tick --
- // pinned at the foot it would say a weight he never named. Its words stay under the digits.
- const onFace = (v) => Number.isFinite(v) && v >= scale.min && v <= scale.max;
- const first = track.goals.find((g) => onFace(g.goal?.value));
- L.set(k("gl"), { rotation: first ? dialAngle(first.goal.value, scale) : a0, autoAlpha: 0 });
- let up = false;
- for (const g of track.goals) {
- const v = g.goal?.value;
- if (onFace(v)) {
- if (!up) {
- L.add(k("gl"), g.t, INSTANT, { rotation: dialAngle(v, scale) });
- L.add(k("gl"), g.t, M.fade, { autoAlpha: 1 }, "power1.out");
- } else L.add(k("gl"), g.t, M.goal, { rotation: dialAngle(v, scale) }, "power2.inOut");
- up = true;
- } else if (up) {
- L.add(k("gl"), g.t, M.fade, { autoAlpha: 0 }, "power1.in");
- up = false;
+ if (cfg.goal) goalCues(L, { marks, lines, k });
+ if (ghosts) ghostCues(L, { ghosts, scale, k, finale, at });
+}
+
+/**
+ * The goal board's cues (goalMarks, goalLines): each mark's status from each board state -- the headline's triangle,
+ * an other's tick, a miss struck in red with a flash -- and the goal line's words.
+ */
+function goalCues(L, { marks, lines, k }) {
+ const M = INSTRUMENT_MOTION;
+ const view = { head: { h: 1, o: 0, x: 0, b: 0.9 }, other: { h: 0, o: 0.85, x: 0, b: 0.4 }, off: { h: 0, o: 0, x: 0, b: 0 } };
+ const look = (st) => (st.status === "missed" ? { h: st.wasHeadline ? 0.45 : 0, o: st.wasHeadline ? 0 : 0.45, x: 1, b: 0.3 } : view[st.status]);
+ marks.forEach((m, i) => {
+ const hasBand = m.band;
+ if (m.angle !== null) {
+ L.set(k(`gm${i}`), { rotation: m.angle, autoAlpha: 1 });
+ for (const c of ["h", "o", "x", "p"]) L.set(k(`gm${i}${c}`), { autoAlpha: 0 });
+ }
+ if (hasBand) L.set(k(`gb${i}`), { autoAlpha: 0 });
+ let was = view.off;
+ let wasMissed = false;
+ for (const st of m.states) {
+ const v = look(st);
+ if (m.angle !== null) {
+ for (const c of ["h", "o", "x"]) if (v[c] !== was[c]) L.add(k(`gm${i}${c}`), st.t, c === "x" ? MISS_MOTION.in : M.fade, { autoAlpha: v[c] }, "power1.out");
+ // The miss is the beat: a red flash round the mark as it lands.
+ if (st.status === "missed" && !wasMissed) {
+ L.add(k(`gm${i}p`), st.t, MISS_MOTION.in, { autoAlpha: 1 }, "power1.out");
+ L.add(k(`gm${i}p`), st.t + MISS_MOTION.in + MISS_MOTION.hold, MISS_MOTION.out, { autoAlpha: 0 }, "power2.in");
+ }
}
+ if (hasBand && v.b !== was.b) L.add(k(`gb${i}`), st.t, M.fade, { autoAlpha: v.b }, "power1.out");
+ was = v;
+ wasMissed = st.status === "missed";
}
- blocks(L, track.goals, k("gw"), { shown: (g) => !!g.goal });
- // A range goal's band, up while it is the latest goal.
- track.goals.forEach((g, j) => {
- const r = g.goal?.range;
- if (!Array.isArray(r) || !(dialAngle(r[1], scale) > dialAngle(r[0], scale))) return;
- L.set(k(`gr${j}`), { autoAlpha: 0 });
- L.add(k(`gr${j}`), g.t, M.fade, { autoAlpha: 1 }, "power1.out");
- const next = track.goals[j + 1];
- if (next) L.add(k(`gr${j}`), next.t, M.fade, { autoAlpha: 0 }, "power1.in");
- });
- }
+ });
+ blocks(L, lines, k("gw"), { shown: (g) => !!g.words });
+}
+
+/**
+ * The claim ghosts' cues (measure-ghosts.mjs ghostTicks): each tick at its angle, from each claim the step its count
+ * is on faded in and the one before out, and a repeat's pulse. The finale (`finale`) shows every tick at its count
+ * at the end of the cut from `at`, no pulses.
+ */
+function ghostCues(L, { ghosts, scale, k, finale, at }) {
+ const G = GHOST_MOTION;
+ const n = ghosts.ramp.length;
+ ghosts.ticks.forEach((x, i) => {
+ L.set(k(`gt${i}`), { rotation: dialAngle(x.value, scale) });
+ for (let s = 0; s < n; s += 1) {
+ L.set(k(`gt${i}s${s}`), { autoAlpha: 0 });
+ if (ghosts.cfg.pulse && s > 0) L.set(k(`gt${i}p${s}`), { autoAlpha: 0 });
+ }
+ if (finale) {
+ const s = Math.min(n - 1, x.claims.length - 1);
+ L.add(k(`gt${i}s${s}`), at, G.fade, { autoAlpha: ghostOpacity(ghosts.cfg.opacity, s) }, "power1.out");
+ return;
+ }
+ let prev = -1;
+ for (const c of x.claims) {
+ const s = Math.min(n - 1, c.n - 1);
+ if (s !== prev) {
+ L.add(k(`gt${i}s${s}`), c.t, G.fade, { autoAlpha: ghostOpacity(ghosts.cfg.opacity, s) }, "power1.out");
+ if (prev >= 0) L.add(k(`gt${i}s${prev}`), c.t, G.fade, { autoAlpha: 0 }, "power1.in");
+ }
+ if (ghosts.cfg.pulse && c.n > 1) {
+ L.add(k(`gt${i}p${s}`), c.t, G.flash, { autoAlpha: 0.9 }, "power1.out");
+ L.add(k(`gt${i}p${s}`), c.t + G.flash, G.decay, { autoAlpha: 0 }, "power2.in");
+ }
+ prev = s;
+ }
+ });
+}
+
+/** The claim ghosts a page draws (deck.measure.ghosts), or null when off. */
+function ghostsOf(measure, render, colors) {
+ const cfg = resolveGhosts(render);
+ if (!cfg) return null;
+ return { cfg, ticks: ghostTicks(measure, cfg), ramp: ghostRamp(cfg, colors, mix) };
}
/**
@@ -400,10 +539,14 @@ export function dialHtml(schedule, render, opts = {}) {
const colors = colorsOf(render, cfg);
const track = measureTrack(M);
const size = even(Math.min(W, H));
- const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track });
+ const board = goalBoard(M);
+ const marks = goalMarks(board, M.scale);
+ const lines = goalLines(board);
+ const ghosts = ghostsOf(M, render, colors);
+ const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts });
const L = cueList(fps);
withDeck(L, schedule, render, "rt");
- dialCues(L, { track, scale: M.scale, cfg });
+ dialCues(L, { track, scale: M.scale, cfg, marks, lines, ghosts });
const { init, cues } = L.build();
return pageHtml({
id: "dial", W, H, fps, fonts, gsap: opts.gsap,
@@ -669,7 +812,8 @@ export function finaleNumbers(measure) {
range: lastCur && lastCur.value === to && Array.isArray(lastCur.range) ? lastCur.range : null,
lost, runs, from: Number.isFinite(from) ? from : null,
peak: peaks.length ? Math.max(...peaks) : null,
- goal: [...track.goals].reverse().find((g) => g.goal)?.goal ?? null,
+ // The goal the finale ends on: the board's headline at the cut's end -- the CLOSEST goal in force (measure-goals.mjs).
+ goal: goalsAt(goalBoard(measure), Infinity).headline ?? null,
};
}
@@ -730,11 +874,18 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) {
...full,
current: [{ t: from, value: null }, { t: A + 0.4, value: nums.weight, qualifier: nums.qualifier, date: null, ...(nums.range ? { range: nums.range } : {}) }],
remembered: rem,
- goals: nums.goal ? [{ t: from, goal: null }, { t: A + 0.4, goal: nums.goal }] : [{ t: from, goal: null }],
};
+ // The goals in force at the cut's end, all at once as the needle drops (the miss beats were the cut's).
+ const end = goalsAt(goalBoard(M), Infinity);
+ const board = [{ t: from, active: [], headline: null, missed: [] }, { t: A + 0.4, active: end.active, headline: end.headline, missed: [] }];
+ const marks = goalMarks(board, M.scale);
+ const lines = goalLines(board);
+ // The claim ghosts STAY: the finale is the summary, and the residue of every number he gave is the point of it --
+ // each tick at its count at the cut's end, in with the finale's grow under the needle's drop, no pulses.
+ const ghosts = ghostsOf(M, render, colors);
const size = even(Math.min(H, Math.round(W * 0.56)));
const k = size / 524;
- const dial = dialParts({ size, ox: 0, oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, prefix: "f", preState: false });
+ const dial = dialParts({ size, ox: 0, oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false });
const rw = W - size - Math.round(40 * k);
const top = Math.max(Number(M.totals?.lost) || 0, nums.lost);
const wheels = wheelCount(top);
@@ -758,7 +909,7 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) {
else if (D > 0 && from + dur - D > A + 0.4) L.add("rt", from + dur - D, D, { autoAlpha: 0 }, "power1.in");
// The needle starts at his highest remembered weight (the scale's top without one) and drops.
const start = Number.isFinite(nums.peak) ? nums.peak : M.scale.max;
- dialCues(L, { track, scale: M.scale, cfg, prefix: "f", finale: true });
+ dialCues(L, { track, scale: M.scale, cfg, marks, lines, ghosts, prefix: "f", finale: true, at: A });
L.set("fnd", { rotation: dialAngle(start, M.scale) });
if (Number.isFinite(nums.weight)) L.add("fnd", A + 0.4, 1.8, { rotation: dialAngle(nums.weight, M.scale) }, needleEase(cfg, "back.out(1.4)"));
for (let i = 0; i <= wheels; i += 1) L.set(`ow${i}`, { y: 0 });
diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs
@@ -16,11 +16,12 @@ import { formatDeckDate } from "./attribution.mjs";
import { rgba } from "./chrome-deck.mjs";
import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, r4, spanEvents } from "./chrome-cues.mjs";
import {
- daysBetween, daysLeftText, daysText, DIET_TAG, dietDays, dietStates, dietTagStep, goalStates, GOALS_SHELF, jitter, measureBox, measureExtraGeometry, measureOf, MEASURE_BOXES, promiseStripRect, promiseStripType,
+ daysBetween, daysLeftText, daysText, DIET_TAG, dietDays, dietStates, dietTagStep, goalStates, goalText, GOALS_SHELF, jitter, measureBox, measureExtraGeometry, measureOf, MEASURE_BOXES, promiseStripRect, promiseStripType,
MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText,
} from "./measure-extras.mjs";
import { dietTagWidth, MEASURE_RED, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
import { dialFinaleGeometry, dialFinaleHandoff } from "./chrome-instruments.mjs";
+import { goalBoard, goalsAt } from "./measure-goals.mjs";
/** How each module's panel comes in and goes out, s. */
export const MEASURE_FADE = Object.freeze({ in: 0.35, out: 0.4 });
@@ -300,17 +301,9 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
});
const spans = upSpans(states.map((s) => s.at), cfg, schedule);
const items = [];
- // THE ORDER ON THE SHELF: the headline goal in front when the state names one (the closest goal in force,
- // goalStates' `headline`), the rest by how recently he set them; else the newest in front, as the pile.
- let before = new Map();
- const shelfStates = states.map((st) => {
- const recent = [...st.notes].sort((a, b) => a.depth - b.depth);
- const lead = st.headline ? recent.find((n) => n.key === st.headline) : null;
- const list = lead ? [lead, ...recent.filter((n) => n !== lead)] : recent;
- const notes = list.map((n, i) => ({ ...n, depth: i, prev: before.has(n.key) ? before.get(n.key) : null }));
- before = new Map(notes.map((n) => [n.key, n.depth]));
- return { ...st, notes };
- });
+ // THE ORDER ON THE SHELF is the dial's (shelfGoalStates): the goal board's headline -- the closest goal in force --
+ // in front with "+N more" for the others in force, the rest by how recently he set them, a missed goal struck.
+ const shelfStates = shelfGoalStates(schedule, states);
const { init, cues } = stateCues(shelfStates, spans, {
own: (st, j, init) => {
const ev = [];
@@ -336,8 +329,11 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
init[k] = { x: to.x, y: to.y, rotation: to.rotation };
}
}
- init[`s${j}.c`] = { scale: 1.6, opacity: 0 };
- ev.push({ k: `s${j}.c`, at: st.at + 0.25, dur: 0.3, to: { scale: 1, opacity: 1 }, ease: "back.out(2.2)" });
+ // The count pops as a goal lands; a state the board alone changed (a goal met, missed, or lapsed) keeps it still.
+ if (st.top) {
+ init[`s${j}.c`] = { scale: 1.6, opacity: 0 };
+ ev.push({ k: `s${j}.c`, at: st.at + 0.25, dur: 0.3, to: { scale: 1, opacity: 1 }, ease: "back.out(2.2)" });
+ }
return ev;
},
});
@@ -356,7 +352,9 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
const back = backs && n.depth > 0
? `<div class="nb"${crossing ? ` data-k="${k}b"` : ""} style="opacity:${crossing ? 0 : 1}"><div class="bt">${esc(n.text)}</div>${n.date ? `<div class="bh">${esc(monthYear(n.date))}</div>` : ""}</div>`
: "";
- return `<div class="note" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}</div>`;
+ // Missed (the board's, held as the dial holds it): struck in red, MISSED on it.
+ const miss = st.missed?.includes(n.key) ? `<div class="mx"></div><div class="ms">Missed</div>` : "";
+ return `<div class="note${miss ? " missed" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}${miss}</div>`;
}).join("");
const html = `<div class="st" data-k="s${j}"><div class="gc"><div class="gn" data-k="s${j}.c">${st.goalsSet}</div><div class="gl">goal${st.goalsSet === 1 ? "" : "s"} set</div></div>${notes}</div>`;
items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html });
@@ -388,13 +386,51 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
color: rgba(42, 28, 6, 0.62); white-space: nowrap; }
.mo { position: absolute; right: ${px(8)}px; bottom: ${px(6)}px; padding: 0 ${px(7)}px; height: ${px(20)}px; border-radius: ${px(10)}px;
background: rgba(42, 28, 6, 0.85); color: ${paper}; font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(20)}px; }
+ .mx { position: absolute; left: ${px(6)}px; right: ${px(6)}px; top: 50%; height: ${px(4)}px; margin-top: ${px(-2)}px; background: ${MEASURE_RED};
+ transform: rotate(-8deg); border-radius: ${px(2)}px; }
+ .ms { position: absolute; left: ${px(10)}px; bottom: ${px(6)}px; padding: 0 ${px(7)}px; height: ${px(20)}px; border-radius: ${px(10)}px;
+ background: ${MEASURE_RED}; color: #fff; font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(20)}px;
+ letter-spacing: 0.1em; text-transform: uppercase; }
.ct { position: absolute; right: ${px(8)}px; top: ${px(5)}px; min-width: ${px(40)}px; height: ${px(24)}px; padding: 0 ${px(7)}px;
border-radius: ${px(12)}px; background: #2a1c06; color: ${paper}; text-align: center;
font-family: ${DISPLAY}; font-size: ${px(19)}px; line-height: ${px(24)}px; }`;
const body = `<div id="pn" data-k="pn">
${blocks.join("\n ")}
</div>`;
- return { html: page("goals", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items };
+ return { html: page("goals", schedule, opts, F, css, body, init, cues, shelfStates.map((_, j) => `s${j}`), render), items };
+}
+
+/**
+ * The shelf's goal states, ordered by the dial's goal board (measure-goals.mjs goalBoard / goalsAt), so the two
+ * always agree: each of goalStates' states (one per goal he sets) and a state wherever the board alone changes
+ * after the first (a goal met, missed or past its day; a missed one's hold ending) -- the same notes, `top` null.
+ * Each carries `headline` (the board headline's note key, or null: the newest leads), `active` (the goals in force)
+ * and `missed` (the note keys struck now); its notes in front-to-back order: the headline, then by recency.
+ */
+export function shelfGoalStates(schedule, states) {
+ if (!states.length) return [];
+ const m = schedule.measure;
+ const board = goalBoard(m);
+ const unit = m?.unit ?? "lb";
+ const keyOf = new Map((m?.events ?? []).filter((e) => e.kind === "goal" || e.kind === "goalLoss").map((e) => [e.row, goalText(e, unit).toLowerCase()]));
+ const times = [...new Set([...states.map((st) => st.at), ...board.map((b) => r4(b.t)).filter((t) => t > states[0].at)])].sort((a, b) => a - b);
+ let before = new Map();
+ return times.map((t) => {
+ const own = states.find((st) => Math.abs(st.at - t) < 1e-6);
+ const base = own ?? [...states].reverse().find((st) => st.at <= t);
+ const b = goalsAt(board, t);
+ const headline = b.headline ? keyOf.get(b.headline.row) ?? null : null;
+ const recent = [...base.notes].sort((x, y) => x.depth - y.depth);
+ const lead = headline ? recent.find((n) => n.key === headline) : null;
+ const list = lead ? [lead, ...recent.filter((n) => n !== lead)] : recent;
+ const notes = list.map((n, i) => ({ ...n, depth: i, prev: before.has(n.key) ? before.get(n.key) : null }));
+ before = new Map(notes.map((n) => [n.key, n.depth]));
+ return {
+ ...base, at: t, top: own ? own.top : null, ...(own ? {} : { repeat: false }),
+ headline: lead ? headline : null, active: b.active.length,
+ missed: b.missed.map((g) => keyOf.get(g.row)).filter(Boolean), notes,
+ };
+ });
}
// ---------------------------------------------------------------------------
diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs
@@ -6,7 +6,9 @@
//
// SOURCE seconds, like `start`/`end`/`cutStart`/`cutEnd`. Each gap lies inside
// the clip's CUT (its `cutStart`–`cutEnd`, else its extent), at least
-// GAP_LIMITS.min long, at most GAP_LIMITS.max of them, sorted, apart, and with
+// GAP_LIMITS.min long, at most GAP_LIMITS.max of them (40: a long clip cut down
+// to its sentences; nothing downstream counts them -- gapFilterParts splits into
+// as many pieces as there are), sorted, apart, and with
// at least GAP_LIMITS.keep seconds of material before the first, between any
// two and after the last: a sliver of picture between two jumps reads as a
// glitch, not a cut. A `muteFrom` or a claim mark's `at` strictly INSIDE a gap
@@ -29,7 +31,7 @@
// `validateGaps`.
/** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */
-export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 12, keep: 0.5 });
+export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 40, keep: 0.5 });
/** Each join's fade, in seconds: out over the end of the piece before, in over the start of the piece after -- short enough to keep a word, long enough not to click. */
export const GAP_FADE = 0.025;
@@ -173,6 +175,58 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}`
}
/**
+ * WHERE A GAP CANNOT GO in a clip, and why -- validateGaps's rules as spans
+ * and seconds a waveform can draw (lane/clip-fixes; operator, 6 Nov: "the gap
+ * tool gets blocked at random invisible walls"). Every wall a gap dragged on
+ * the bench stops at is one of these:
+ *
+ * span where gaps lie at all (gapSpan: the cut, else the extent); `whose`
+ * says which, in the words validateGaps uses
+ * zones inside the span, the seconds no gap may reach into: GAP_LIMITS.keep
+ * after the span's start and before its end, and beside each gap
+ * (a span reaching INTO a gap is not refused -- it grows it,
+ * editGaps -- but one stopping short in its keep band is)
+ * marks the seconds no gap may COVER (strictly inside): the mute mark, each
+ * claim mark's or stamp's `at`
+ *
+ * A gap avoiding every zone's interior and covering no mark, at least
+ * GAP_LIMITS.min long, apart from the rest and under GAP_LIMITS.max of them, is
+ * one validateGaps accepts (gaps.test.mjs holds the two to each other).
+ *
+ * @param {Record<string, any>} entry
+ * @returns {{ span: { from: number, to: number }, whose: "cut" | "clip",
+ * zones: Array<{ from: number, to: number, kind: "keep-start" | "keep-end" | "keep-gap", why: string }>,
+ * marks: Array<{ at: number, kind: "mute" | "mark" | "stamp", id: string | null, why: string }> }}
+ */
+export function gapWalls(entry) {
+ const span = gapSpan(entry);
+ const whose = fin(entry?.cutStart) && fin(entry?.cutEnd) ? "cut" : "clip";
+ const keep = GAP_LIMITS.keep;
+ const zones = [];
+ if (fin(span.from) && fin(span.to)) {
+ zones.push({ from: span.from, to: Math.min(span.to, span.from + keep), kind: "keep-start", why: `keep at least ${keep} s after the ${whose}'s start` });
+ zones.push({ from: Math.max(span.from, span.to - keep), to: span.to, kind: "keep-end", why: `keep at least ${keep} s before the ${whose}'s end` });
+ }
+ for (const g of gapsOf(entry)) {
+ const why = `keep at least ${keep} s between cuts — or drag into the gap ${g.from}–${g.to} to grow it`;
+ zones.push({ from: g.from - keep, to: g.from, kind: "keep-gap", why });
+ zones.push({ from: g.to, to: g.to + keep, kind: "keep-gap", why });
+ }
+ const marks = [];
+ if (fin(entry?.muteFrom)) marks.push({ at: entry.muteFrom, kind: "mute", id: null, why: `the mute mark (${entry.muteFrom}): a gap can't cover it — the cut never plays a second inside a gap` });
+ for (const m of marksAt(entry)) {
+ const id = typeof m.id === "string" && m.id ? m.id : null;
+ marks.push({
+ at: m.at,
+ kind: id ? "mark" : "stamp",
+ id,
+ why: `${id ? `the mark ${id}'s second` : "the stamp's second"} (${m.at}): a gap can't cover it — move it first, or cut around it`,
+ });
+ }
+ return { span, whose, zones, marks };
+}
+
+/**
* A clip beat's GAPS (lane/reel-bench): source seconds cut out of its middle,
* so two moments of one clip play as one beat of jump cuts -- the same shape
* and the same rule as a clip's gaps (gaps.mjs): each `{ from, to }` at least
diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs
@@ -13,7 +13,7 @@ import path from "node:path";
import test from "node:test";
import {
- GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin,
+ GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapWalls, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin,
inGap, keptSpans, normalizeGaps, offsetIn, parseGapSpec, recordGaps, renderGaps, sourceAtOffset, validateGapEntries, validateGaps,
} from "./gaps.mjs";
@@ -44,8 +44,10 @@ test("validateGaps: each refusal names what is wrong", () => {
assert.match(one([{ from: 102.3, to: 103 }])[0], /after the cut's start/);
assert.match(one([{ from: 117, to: 117.8 }])[0], /before the cut's end/);
assert.match(one([{ from: 117, to: 119 }])[0], /outside the clip's cut/);
- const many = Array.from({ length: 13 }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 }));
- assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 130, gaps: many })[0], /at most 12 gaps/);
+ // At most 40 (a long clip cut down to its sentences); 40 is fine, 41 is not.
+ const many = (n) => Array.from({ length: n }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 }));
+ assert.deepEqual(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 170, gaps: many(40) }), []);
+ assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 170, gaps: many(41) })[0], /at most 40 gaps/);
assert.match(validateGaps({ type: "card", id: "k", gaps: G })[0], /only a clip/);
});
@@ -219,3 +221,49 @@ test("fetchPieces: one padded span per kept piece; pieces under a minute apart a
[{ from: 0, to: 103 }, { from: 397, to: 413 }, { from: 897, to: 1003 }],
);
});
+
+
+// ---- the walls, drawn (lane/clip-fixes) -------------------------------------
+
+test("gapWalls: the span, the keep bands at its edges and beside each gap, and the marks no gap may cover", () => {
+ const w = gapWalls({ ...CLIP, gaps: G, muteFrom: 116, claims: [{ id: "a", verdict: "FALSE", at: 104 }, { verdict: "FALSE", at: 112 }] });
+ assert.deepEqual(w.span, { from: 102, to: 118 });
+ assert.equal(w.whose, "cut");
+ assert.deepEqual(
+ w.zones.map((z) => [z.kind, z.from, z.to]),
+ [["keep-start", 102, 102.5], ["keep-end", 117.5, 118], ["keep-gap", 104.5, 105], ["keep-gap", 107, 107.5], ["keep-gap", 109.5, 110], ["keep-gap", 110.5, 111]],
+ );
+ assert.match(w.zones[0].why, /after the cut's start/);
+ assert.match(w.zones[2].why, /drag into the gap 105–107 to grow it/);
+ assert.deepEqual(w.marks.map((m) => [m.kind, m.at, m.id]), [["mute", 116, null], ["mark", 104, "a"], ["stamp", 112, null]]);
+ assert.match(w.marks[0].why, /can't cover it/);
+ // No cut: the extent, said as the clip's.
+ const x = gapWalls({ type: "clip", id: "x", start: 10, end: 20 });
+ assert.deepEqual(x.span, { from: 10, to: 20 });
+ assert.equal(x.whose, "clip");
+ assert.deepEqual(x.marks, []);
+});
+
+test("gapWalls and validateGaps agree: a new gap clear of every zone and mark is accepted, one reaching into either is refused", () => {
+ const entry = { ...CLIP, gaps: G, muteFrom: 116, claims: [{ id: "a", verdict: "FALSE", at: 104 }, { verdict: "FALSE", at: 112.6 }] };
+ const w = gapWalls(entry);
+ // A seeded walk: deterministic, many spans, every edge on the writer's 2 dp grid.
+ let seed = 7;
+ const rand = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
+ let checked = 0;
+ for (let i = 0; i < 4000; i += 1) {
+ const a = Number((w.span.from + rand() * (w.span.to - w.span.from)).toFixed(2));
+ const b = Number((a + 0.2 + rand() * 3).toFixed(2));
+ if (b > w.span.to) continue;
+ // Touching or overlapping a gap is a merge (editGaps), not a wall: not this test's question.
+ if (G.some((g) => g.to >= a && g.from <= b)) continue;
+ const hitsZone = w.zones.some((z) => a < z.to - 0.02 && b > z.from + 0.02);
+ const nearZone = w.zones.some((z) => (Math.abs(a - z.to) <= 0.02 || Math.abs(b - z.from) <= 0.02));
+ if (nearZone) continue; // within the writer's 0.02 tolerance of a band's edge
+ const coversMark = w.marks.some((m) => m.at > a && m.at < b);
+ const errs = validateGaps({ ...entry, gaps: normalizeGaps([...G, { from: a, to: b }]) });
+ assert.equal(errs.length === 0, !hitsZone && !coversMark, `${a}–${b}: ${errs.join("; ") || "accepted"}`);
+ checked += 1;
+ }
+ assert.ok(checked > 500, `checked ${checked}`);
+});
diff --git a/umtool/report-to-video/instruments.mjs b/umtool/report-to-video/instruments.mjs
@@ -6,7 +6,8 @@
// render.chrome.deck.dial an analog bathroom-scale face: a red needle to
// every weight he states, on the word, with a
// spring; his remembered weights as grey ghosts;
-// his latest goal as an amber tick on the bezel
+// every goal in force on the bezel, the closest
+// headlined (measure-goals.mjs)
// render.chrome.deck.odometer rolling digits of the pounds he says he has
// lost (only ever up), NET beside them
// render.chrome.deck.trail his stated weights by DATE, a thin line drawn
@@ -37,7 +38,8 @@ export const DIAL_DEFAULTS = Object.freeze({
mark: 300,
// The remembered weights as ghost ticks, the latest a long ghost needle with its as-of date.
ghosts: true,
- // The latest goal as an amber tick on the bezel, and its words under the digits.
+ // Every goal in force as a mark on the bezel, the CLOSEST (measure-goals.mjs) the full amber tick
+ // and its words under the digits, a missed one struck in red.
goal: true,
// The needle's colour: a #hex.
needle: NEEDLE_RED,
diff --git a/umtool/report-to-video/instruments.test.mjs b/umtool/report-to-video/instruments.test.mjs
@@ -244,7 +244,10 @@ test("the dial's finale: the record's numbers, a window page the frame keys mode
const html = dialFinaleHtml(schedule, RENDER, win, { fonts });
assert.match(html, /data-composition-id="dial-finale"/);
assert.match(html, />291\.5<i>LB<\/i>/);
- assert.match(html, /GOAL 235</);
+ // The goal it ends on is the CLOSEST in force at the cut's end (measure-goals.mjs), not simply the latest row of the
+ // record: w85, "lose 50" from 300 -> 250 (w90's 235 is the fixture's state, not a goal the cut shows).
+ assert.equal(n.goal.row, "w85");
+ assert.match(html, /GOAL 250 · LOSE 50</);
const keys = frameKeys({ html, region: "dial-finale", fps: FPS, frames: win.frames, version: "t" });
assert.ok(keys);
// Held once the needle, the wheels and NET are in (by 4 s into the window): one key.
diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs
@@ -229,9 +229,11 @@ export function goalStates(schedule, render) {
const states = [];
let prevDepth = new Map();
let n = 0;
- const rowKey = new Map();
for (const { e, s } of stepsOf(m)) {
if (e.kind !== "goal" && e.kind !== "goalLoss") continue;
+ // A goal of his that counts: not another speaker's, not an `unresolved` row (a joke) -- as the slice's tallies
+ // and the dial's goal board (measure-slice.mjs isUsable, measure-goals.mjs).
+ if (e.unresolved === true || (typeof e.speaker === "string" && e.speaker.trim())) continue;
n += 1;
const text = goalText(e, m.unit ?? "lb");
const key = text.toLowerCase();
@@ -252,22 +254,14 @@ export function goalStates(schedule, render) {
const target = s?.goal && s.goal.row === e.row && Number.isFinite(s.goal.value) ? s.goal.value
: e.kind === "goal" && Number.isFinite(e.value) ? e.value : null;
note.target = target;
- rowKey.set(e.row, key);
order = [...order.filter((k) => k !== key), key];
const shown = order.slice(-cfg.max);
const depth = new Map(shown.map((k, i) => [k, shown.length - 1 - i]));
- // The headline goal, when the state names one (the closest goal in force -- the measure state's
- // `goals.headline`, a row or a goal carrying its row): its note's key, else null (the newest leads).
- const hl = s?.goals && !Array.isArray(s.goals) ? s.goals.headline : s?.goalHeadline;
- const hlRow = typeof hl === "string" ? hl : hl?.row ?? null;
- const active = s?.goals && !Array.isArray(s.goals) && Array.isArray(s.goals.active) ? s.goals.active.length : null;
states.push({
at: r4(e.t),
top: key,
repeat: note.count > 1,
- ...(hlRow && rowKey.has(hlRow) ? { headline: rowKey.get(hlRow) } : {}),
- ...(active !== null ? { active } : {}),
- goalsSet: Array.isArray(s?.goals) ? s.goals.length : Array.isArray(s?.goals?.set) ? s.goals.set.length : n,
+ goalsSet: Array.isArray(s?.goals) ? s.goals.length : n,
notes: shown.map((k) => {
const x = notes.get(k);
return {
diff --git a/umtool/report-to-video/measure-ghosts.mjs b/umtool/report-to-video/measure-ghosts.mjs
@@ -0,0 +1,133 @@
+// THE DIAL'S CLAIM GHOSTS (`render.chrome.deck.measure.ghosts`, 6 Nov 2026):
+// every weight the cut has shown him claim leaves a faint residual tick on the
+// dial's rim at its value, so after a few minutes the face carries the history
+// of everything he has said; a value claimed again changes that tick's colour
+// along a short ramp (1x faint neutral, 2x warm, 3x+ hot) and thickens it, and
+// the tick pulses once as the repeat lands.
+//
+// Not the dial's own `deck.dial.ghosts` (his REMEMBERED weights as long grey
+// ticks with their as-of words, the latest a long ghost needle): those stay as
+// they are, drawn over these.
+//
+// A claim is a measure event the cut shows (`measure.events`, t finite) of his
+// own (no `speaker`) that puts a number on his weight: a STATED weight (each
+// one the needle goes to) or a REMEMBERED one. Two claims are the same tick
+// when their values are within `tolerance` lb of the tick's first value; an
+// "≈" value counts as its rounded number; a ">300" or "<300" is a claim at
+// 300 (its bound is where it stands on the face).
+//
+// PURE and SEEK-SAFE: ghostTicks is a function of the schedule's measure alone,
+// in cut order -- no state from playback -- so Play, the live preview and the
+// render draw the same tick at the same second from either side of it.
+//
+// A LEAF: measure-slice.mjs (the setting's validator) and chrome-instruments.mjs
+// (the dial's page) import it; it imports nothing.
+
+/** The setting's knobs and their defaults (`ghosts: true`). */
+export const GHOST_DEFAULTS = Object.freeze({
+ // The 1x tick's opacity; each step of the ramp adds GHOST_OPACITY_STEP, to at most 0.95.
+ opacity: 0.5,
+ // Pounds: a claim within this of a tick's value is a repeat of it.
+ tolerance: 0.5,
+ // The ramp's colours, 1x first, the last for every count from there up (2 to 4 #hex), or
+ // null: the palette's -- its muted, its amber, and amber half way to the needle's red.
+ ramp: null,
+ // The tick pulses once as a repeat lands.
+ pulse: true,
+});
+
+export const GHOST_OPACITY = Object.freeze([0.15, 0.9]);
+export const GHOST_OPACITY_STEP = 0.2;
+export const GHOST_TOLERANCE = Object.freeze([0, 5]);
+export const GHOST_RAMP = Object.freeze([2, 4]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
+const inRange = (v, [lo, hi]) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+
+/** `render.chrome.deck.measure.ghosts`, as sentences. */
+export function validateGhosts(v, where = "render.chrome.deck.measure.ghosts") {
+ if (v === undefined || typeof v === "boolean") return [];
+ if (!isObj(v)) return [`${where} must be true, false or { ${Object.keys(GHOST_DEFAULTS).join(", ")} }`];
+ const errors = [];
+ for (const k of Object.keys(v)) {
+ if (!Object.hasOwn(GHOST_DEFAULTS, k)) errors.push(`${where}.${k} is not a setting of it (${Object.keys(GHOST_DEFAULTS).join(", ")})`);
+ }
+ if (v.opacity !== undefined && !inRange(v.opacity, GHOST_OPACITY)) errors.push(`${where}.opacity must be a number from ${GHOST_OPACITY[0]} to ${GHOST_OPACITY[1]}`);
+ if (v.tolerance !== undefined && !inRange(v.tolerance, GHOST_TOLERANCE)) errors.push(`${where}.tolerance must be pounds from ${GHOST_TOLERANCE[0]} to ${GHOST_TOLERANCE[1]}`);
+ if (v.ramp !== undefined && v.ramp !== null) {
+ if (!Array.isArray(v.ramp) || v.ramp.length < GHOST_RAMP[0] || v.ramp.length > GHOST_RAMP[1] || v.ramp.some((c) => typeof c !== "string" || !HEX_RE.test(c))) {
+ errors.push(`${where}.ramp must be ${GHOST_RAMP[0]} to ${GHOST_RAMP[1]} #hex colours (1x first), or null for the palette's`);
+ }
+ }
+ if (v.pulse !== undefined && typeof v.pulse !== "boolean") errors.push(`${where}.pulse must be true or false`);
+ return errors;
+}
+
+/** The ghosts' settings, defaults filled, or null when off (absent, `false`). */
+export function resolveGhosts(render) {
+ const v = render?.chrome?.deck?.measure?.ghosts;
+ if (v === true) return { ...GHOST_DEFAULTS };
+ if (!isObj(v)) return null;
+ return { ...GHOST_DEFAULTS, ...v };
+}
+
+/** The ramp's colours: the setting's, else from the palette roles (`muted`, `amber`, `needle`, and a `mix`). */
+export function ghostRamp(cfg, { muted, amber, needle }, mix) {
+ if (Array.isArray(cfg?.ramp) && cfg.ramp.length >= GHOST_RAMP[0]) return [...cfg.ramp];
+ return [muted, amber, mix(amber, needle, 0.5)];
+}
+
+/** Step `k` (0 = 1x) of a ramp of `n`: its opacity from the 1x opacity. */
+export const ghostOpacity = (base, k) => Math.min(0.95, Math.round((base + k * GHOST_OPACITY_STEP) * 100) / 100);
+
+/** The claim's value as its tick counts it: an "≈" value is its rounded number. */
+export const claimValue = (e) => (e?.qualifier === "≈" ? Math.round(Number(e.value)) : Number(e.value));
+
+/** Is this event a weight claim of his the cut shows: stated or remembered, a number, a time, no other speaker. */
+export const isClaim = (e) =>
+ !!e && (e.kind === "stated" || e.kind === "remembered") && Number.isFinite(Number(e.value)) && e.value !== null &&
+ Number.isFinite(e.t) && !(typeof e.speaker === "string" && e.speaker.trim());
+
+/**
+ * The ghost ticks of a measure: one per value claimed, in the order first
+ * claimed -- `{ value, claims: [{ t, row, kind, n }] }`, `value` the first
+ * claim's (as its tick counts it), each claim with its count `n` (1 the
+ * first). In cut order: a claim joins the first tick whose value is within
+ * `tolerance` of it, else starts a tick.
+ *
+ * @param {{ events?: object[] }} measure the schedule's measure slice
+ * @param {{ tolerance?: number }} [cfg]
+ */
+export function ghostTicks(measure, cfg = {}) {
+ const tol = Number.isFinite(cfg.tolerance) ? cfg.tolerance : GHOST_DEFAULTS.tolerance;
+ const claims = (Array.isArray(measure?.events) ? measure.events : [])
+ .map((e, i) => ({ e, i }))
+ .filter(({ e }) => isClaim(e))
+ .sort((a, b) => a.e.t - b.e.t || a.i - b.i);
+ const ticks = [];
+ for (const { e } of claims) {
+ const v = claimValue(e);
+ let tick = ticks.find((x) => Math.abs(x.value - v) <= tol + 1e-9);
+ if (!tick) ticks.push((tick = { value: v, claims: [] }));
+ tick.claims.push({ t: e.t, row: e.row ?? null, kind: e.kind, n: tick.claims.length + 1 });
+ }
+ return ticks;
+}
+
+/**
+ * The ticks as they stand at cut second `t`: each tick claimed by then with
+ * its count so far (`count`), the ramp step it is on (`step`, 0 = 1x, held at
+ * the ramp's last), and whether a repeat landed within `pulse` s before `t`.
+ * A pure function of the ticks and `t` -- what a frame at `t` shows.
+ */
+export function ghostsAt(ticks, t, { steps = 3, pulse = 0 } = {}) {
+ const out = [];
+ for (const x of ticks) {
+ const by = x.claims.filter((c) => c.t <= t + 1e-9);
+ if (!by.length) continue;
+ const last = by[by.length - 1];
+ out.push({ value: x.value, count: by.length, step: Math.min(steps - 1, by.length - 1), pulsing: pulse > 0 && last.n > 1 && t - last.t < pulse });
+ }
+ return out;
+}
diff --git a/umtool/report-to-video/measure-ghosts.test.mjs b/umtool/report-to-video/measure-ghosts.test.mjs
@@ -0,0 +1,158 @@
+// The dial's claim ghosts (measure-ghosts.mjs, chrome-instruments.mjs): the
+// setting, the accumulation in cut order, the repeat ramp and its tolerance,
+// and that what a frame shows at t is a pure function of the schedule.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { estimateSchedule } from "./deck.mjs";
+import { mix } from "./chrome-deck.mjs";
+import { dialFinaleHtml, dialHtml } from "./chrome-instruments.mjs";
+import { frameKeys } from "./frame-keys.mjs";
+import { GHOST_DEFAULTS, claimValue, ghostOpacity, ghostRamp, ghostTicks, ghostsAt, isClaim, resolveGhosts, validateGhosts } from "./measure-ghosts.mjs";
+import { validateMeasureSettings } from "./measure-slice.mjs";
+import { moduleById } from "./modules/index.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-dial", "measure.json"), "utf8"));
+const FPS = 30;
+const fonts = { DeckSans: "assets/DeckSans.ttf", DeckSansBold: "assets/DeckSansBold.ttf" };
+const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const renderWith = (measure) => ({
+ width: 1920, height: 1080, fps: FPS, transition: 0.4, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false }, ...(measure ? { measure } : {}) } },
+});
+
+function cut(render) {
+ const timeline = Array.from({ length: 9 }, (_, i) => ({
+ type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}),
+ }));
+ const manifest = { slug: "m", title: "M", provenance: {}, render, timeline };
+ return { ...estimateSchedule(manifest), measure: MEASURE };
+}
+
+const dataOf = (html, id = "dial") => JSON.parse(new RegExp(`<script id="${id}-data" type="application/json">(.*?)</script>`, "s").exec(html)[1]);
+
+/** An element's property at cut second `t` from a page's init and cues, as the interpreter lands on it at rest. */
+function valueAt(data, k, p, t) {
+ let v = data.init[k]?.[p];
+ for (const c of data.cues) if (c.k === k && p in c.to && c.at + c.dur <= t + 1e-9) v = c.to[p];
+ return v;
+}
+
+test("the setting: off unless asked; true, false or its knobs; checked where deck.measure is", () => {
+ assert.equal(resolveGhosts(renderWith({})), null);
+ assert.equal(resolveGhosts(renderWith({ ghosts: false })), null);
+ assert.deepEqual(resolveGhosts(renderWith({ ghosts: true })), { ...GHOST_DEFAULTS });
+ assert.deepEqual(resolveGhosts(renderWith({ ghosts: { tolerance: 1, pulse: false } })), { ...GHOST_DEFAULTS, tolerance: 1, pulse: false });
+ assert.deepEqual(validateGhosts(true), []);
+ assert.deepEqual(validateGhosts({ opacity: 0.3, tolerance: 2, ramp: ["#888888", "#e8a33f", "#ff5a4e"], pulse: true }), []);
+ assert.deepEqual(validateGhosts({ opacity: 2, tolerance: -1, ramp: ["red"], pulse: "yes", glow: 1 }), [
+ "render.chrome.deck.measure.ghosts.glow is not a setting of it (opacity, tolerance, ramp, pulse)",
+ "render.chrome.deck.measure.ghosts.opacity must be a number from 0.15 to 0.9",
+ "render.chrome.deck.measure.ghosts.tolerance must be pounds from 0 to 5",
+ "render.chrome.deck.measure.ghosts.ramp must be 2 to 4 #hex colours (1x first), or null for the palette's",
+ "render.chrome.deck.measure.ghosts.pulse must be true or false",
+ ]);
+ assert.deepEqual(validateGhosts("on"), ["render.chrome.deck.measure.ghosts must be true, false or { opacity, tolerance, ramp, pulse }"]);
+ assert.deepEqual(validateMeasureSettings({ ghosts: { ramp: [] } }), [
+ "render.chrome.deck.measure.ghosts.ramp must be 2 to 4 #hex colours (1x first), or null for the palette's",
+ ]);
+ // The palette's ramp: muted, amber, amber half way to the needle.
+ assert.deepEqual(ghostRamp(GHOST_DEFAULTS, { muted: "#98a29b", amber: "#e8a33f", needle: "#ff5a4e" }, mix), ["#98a29b", "#e8a33f", mix("#e8a33f", "#ff5a4e", 0.5)]);
+ assert.deepEqual([0, 1, 2, 5].map((k) => ghostOpacity(0.5, k)), [0.5, 0.7, 0.9, 0.95]);
+});
+
+test("every claim he makes leaves a tick, in cut order: stated and remembered, his own, a number, on screen", () => {
+ assert.equal(isClaim({ kind: "stated", value: 300, t: 1 }), true);
+ assert.equal(isClaim({ kind: "remembered", value: 390, t: 1 }), true);
+ assert.equal(isClaim({ kind: "goal", value: 250, t: 1 }), false);
+ assert.equal(isClaim({ kind: "stated", value: null, t: 1 }), false);
+ assert.equal(isClaim({ kind: "stated", value: 300, t: null }), false);
+ assert.equal(isClaim({ kind: "stated", value: 300, t: 1, speaker: "madamsavvy" }), false);
+ const ticks = ghostTicks(MEASURE, GHOST_DEFAULTS);
+ // The fixture's 21 claims on 15 values: 390 four times (≈390 thrice and 390 once), 300 four times (>300, 300, >300, <300).
+ assert.equal(ticks.reduce((n, x) => n + x.claims.length, 0), 21);
+ assert.equal(ticks.length, 15);
+ const by = new Map(ticks.map((x) => [x.value, x.claims.map((c) => c.n)]));
+ assert.deepEqual(by.get(390), [1, 2, 3, 4]);
+ assert.deepEqual(by.get(300), [1, 2, 3, 4]);
+ assert.deepEqual(by.get(291.5), [1]);
+ // In the order first claimed.
+ assert.deepEqual(ticks.slice(0, 3).map((x) => x.value), [240, 390, 365.7]);
+});
+
+test("a repeat is a claim within the tolerance of a tick's first value; an ≈ counts as its rounded number", () => {
+ const ev = (t, value, qualifier = null, kind = "stated") => ({ t, kind, value, qualifier, row: `r${t}` });
+ const m = { events: [ev(1, 300), ev(2, 300.4), ev(3, 300.6), ev(4, 389.6, "≈", "remembered"), ev(5, 390), ev(6, 299.5)] };
+ const half = ghostTicks(m, { tolerance: 0.5 });
+ assert.deepEqual(half.map((x) => [x.value, x.claims.length]), [[300, 3], [300.6, 1], [390, 2]]);
+ assert.equal(claimValue({ value: 389.6, qualifier: "≈" }), 390);
+ const none = ghostTicks(m, { tolerance: 0 });
+ assert.deepEqual(none.map((x) => x.value), [300, 300.4, 300.6, 390, 299.5]);
+ const wide = ghostTicks(m, { tolerance: 1 });
+ assert.deepEqual(wide.map((x) => [x.value, x.claims.length]), [[300, 4], [390, 2]]);
+});
+
+test("the ramp: 1x, 2x, 3x and up held on the last; a repeat pulses, a first claim does not", () => {
+ const ticks = ghostTicks(MEASURE, GHOST_DEFAULTS);
+ const t390 = ticks.find((x) => x.value === 390).claims.map((c) => c.t);
+ const at = (t) => ghostsAt(ticks, t, { steps: 3, pulse: 1 }).find((x) => x.value === 390) ?? null;
+ assert.equal(at(t390[0] - 0.01), null);
+ assert.deepEqual(at(t390[0]), { value: 390, count: 1, step: 0, pulsing: false });
+ assert.deepEqual(at(t390[1] + 0.5), { value: 390, count: 2, step: 1, pulsing: true });
+ assert.deepEqual(at(t390[1] + 1.5), { value: 390, count: 2, step: 1, pulsing: false });
+ assert.deepEqual(at(t390[3] + 2), { value: 390, count: 4, step: 2, pulsing: false });
+});
+
+test("the dial draws them only when asked; the page is a cue list the frame keys model, and a frame at t shows the ticks at t", () => {
+ const off = renderWith({});
+ const on = renderWith({ ghosts: true });
+ const plain = dialHtml(cut(off), off, { fonts });
+ assert.doesNotMatch(plain, /data-k="gt0/);
+ const html = dialHtml(cut(on), on, { fonts });
+ assert.match(html, /data-k="gt0"/);
+ // Pure: the same schedule draws the same page.
+ assert.equal(html, dialHtml(cut(on), on, { fonts }));
+ const schedule = cut(on);
+ const frames = Math.round(schedule.total * FPS);
+ const keys = frameKeys({ html, region: "dial", fps: FPS, frames, version: "t" });
+ assert.ok(keys, "the frame keys model the dial's page with its ghosts");
+ assert.ok(new Set(keys).size < frames / 2, "the ghosts at rest are reused frame to frame");
+ const data = dataOf(html);
+ const ticks = ghostTicks(MEASURE, GHOST_DEFAULTS);
+ // SEEK-SAFE: at any second, each tick's visible step is ghostsAt's -- read from init and the cues, never from playback.
+ for (const t of [0, 5, 7.25 + 1, 21.25 + 1, 44 + 1, 58 + 1, 61]) {
+ const want = new Map(ghostsAt(ticks, t, { steps: 3 }).map((x) => [x.value, x.step]));
+ ticks.forEach((x, i) => {
+ const shown = [0, 1, 2].filter((s) => (valueAt(data, `gt${i}s${s}`, "autoAlpha", t) ?? 0) > 0);
+ assert.deepEqual(shown, want.has(x.value) ? [want.get(x.value)] : [], `tick ${x.value} at ${t}s`);
+ });
+ }
+ // The 1x opacity, faint; the third step the strongest; a pulse decays to nothing.
+ const i390 = ticks.findIndex((x) => x.value === 390);
+ assert.equal(valueAt(data, `gt${i390}s2`, "autoAlpha", 61), 0.9);
+ assert.equal(valueAt(data, `gt${i390}p1`, "autoAlpha", 61), 0);
+ assert.ok(data.cues.some((c) => c.k === `gt${i390}p1` && c.to.autoAlpha === 0.9), "the second telling pulses");
+ // pulse: false draws no pulse lines.
+ const quiet = renderWith({ ghosts: { pulse: false } });
+ assert.doesNotMatch(dialHtml(cut(quiet), quiet, { fonts }), /data-k="gt\d+p/);
+});
+
+test("the finale keeps them: every tick at its count at the cut's end, in with the finale, no pulses", () => {
+ const on = renderWith({ ghosts: true });
+ const schedule = cut(on);
+ const win = moduleById("dial-finale").window(schedule, { fps: FPS, total: schedule.total });
+ const html = dialFinaleHtml(schedule, on, win, { fonts });
+ const data = dataOf(html, "dial-finale");
+ const ticks = ghostTicks(MEASURE, GHOST_DEFAULTS);
+ ticks.forEach((x, i) => {
+ const s = Math.min(2, x.claims.length - 1);
+ assert.equal(valueAt(data, `fgt${i}s${s}`, "autoAlpha", win.to), ghostOpacity(GHOST_DEFAULTS.opacity, s));
+ });
+ assert.ok(!data.cues.some((c) => /^fgt\d+p/.test(c.k) && c.to.autoAlpha > 0));
+ assert.ok(frameKeys({ html, region: "dial-finale", fps: FPS, frames: win.frames, version: "t" }));
+});
diff --git a/umtool/report-to-video/measure-goals.mjs b/umtool/report-to-video/measure-goals.mjs
@@ -0,0 +1,173 @@
+// THE GOAL BOARD (6 Nov 2026, the operator: "in a sequence of multiple goals
+// such as at the 7m clip, show each goal on the dial, and prioritize the
+// closest one rather than the most ambitious one since failing the easiest
+// goal would be the most interesting"): every goal in force at the playhead,
+// the CLOSEST of them as the headline, and each one whose deadline passed
+// unmet, held a moment as MISSED.
+//
+// active every goal (`goal`, `goal_loss`) of his the cut has shown (an
+// `unresolved` row -- a joke -- is no goal), not
+// yet met, replaced or past its deadline -- in the order set.
+// A newer goal with the same HORIZON replaces the older one: the
+// same deadline day, else the same deadline words, else both
+// undated ("eventual" goals stay until one replaces them).
+// headline the active goal with the least loss still needed from his
+// latest stated weight (to a range's top); a goal with no weight
+// (an unresolved "lose 75") by its loss; ties to the soonest
+// deadline, then the latest set. Not the most ambitious, not
+// simply the latest.
+// missed the goals whose deadline the record's date (the latest date of
+// the events shown so far) has passed with no stated weight of his
+// at or under it by then, while his latest stated weight is over
+// it -- each `{ ...goal, at, wasHeadline }`, held MISS_HOLD s from
+// `at`, then gone. A goal whose deadline passes with his latest
+// weight under it (a reading after the day: we cannot say) or that
+// a reading meets in time leaves quietly.
+//
+// A goal: `{ row, kind, t, said, target, range, loss, display, deadline,
+// deadlineDate, key }` -- `target` the weight it comes to (a `goal_loss`
+// resolved against its base by the slice: the state's `goal.value`), null
+// when unresolved; `deadlineDate` the ledger's `due`, else the date his
+// deadline words name (measure-extras.mjs deadlineDate), else the row's
+// `asOf` (the day a goal is for: "320 by his birthday", asOf 2026-04-01).
+//
+// PURE and SEEK-SAFE: goalBoard is a function of the schedule's measure alone;
+// goalsAt(board, t) is the board at a cut second. The dial draws it
+// (chrome-instruments.mjs); any page that shows a goal reads the same
+// `headline` from here.
+import { deadlineDate } from "./measure-extras.mjs";
+
+/** How long a missed goal stays on the dial, struck, before it goes (s). */
+export const MISS_HOLD = 6;
+
+const ISO_RE = /^\d{4}-\d{2}-\d{2}$/;
+const isIso = (v) => typeof v === "string" && ISO_RE.test(v);
+const own = (e) => !(typeof e?.speaker === "string" && e.speaker.trim());
+const r4 = (v) => Math.round(v * 10000) / 10000;
+
+/** The weight a goal must be at or under to be met: a range's top, else its target. */
+export const goalEdge = (g) => (Array.isArray(g?.range) && g.range.length === 2 ? Math.max(g.range[0], g.range[1]) : g?.target ?? null);
+
+/** Pounds still to lose from `cur` to goal `g` (its loss when it has no weight), or Infinity when unknown. */
+export function goalNeed(g, cur) {
+ const edge = goalEdge(g);
+ if (Number.isFinite(edge) && Number.isFinite(cur)) return r4(cur - edge);
+ if (Number.isFinite(g?.loss)) return g.loss;
+ return Infinity;
+}
+
+/**
+ * The closest of `goals` from weight `cur`: the least still needed (a goal
+ * already under `cur`'s reach -- need 0 or less -- after every one still
+ * ahead), ties to the soonest deadline (undated last), then the latest set.
+ */
+export function headlineOf(goals, cur) {
+ if (!goals.length) return null;
+ const rank = (g) => {
+ const n = goalNeed(g, cur);
+ return n > 0 ? n : 1e9 - n;
+ };
+ return [...goals].sort((a, b) =>
+ rank(a) - rank(b) ||
+ String(a.deadlineDate ?? "9999").localeCompare(String(b.deadlineDate ?? "9999")) ||
+ b.t - a.t)[0];
+}
+
+/** A goal event as the board carries it, with the state after it (`s`, for a goal_loss's resolution). */
+function goalOf(e, s) {
+ const kind = e.kind;
+ const resolved = s?.goal && s.goal.row === e.row ? s.goal : null;
+ const target = kind === "goal" && Number.isFinite(Number(e.value)) && e.value !== null ? Number(e.value)
+ : Number.isFinite(resolved?.value) ? resolved.value : null;
+ const loss = kind === "goalLoss" && Number.isFinite(Number(e.value)) ? Math.abs(Number(e.value)) : Number.isFinite(resolved?.loss) ? resolved.loss : null;
+ const words = typeof e.deadline === "string" && e.deadline.trim() ? e.deadline.trim() : null;
+ const date = isIso(e.due) ? e.due : (words ? deadlineDate(words, e.date) : null) ?? (isIso(e.asOf) ? e.asOf : null);
+ const range = Array.isArray(e.range) && e.range.length === 2 ? [...e.range] : Array.isArray(resolved?.range) ? [...resolved.range] : null;
+ return {
+ row: e.row ?? null, kind, t: e.t, said: isIso(e.date) ? e.date : null,
+ target, ...(range ? { range } : {}), loss, display: e.display ?? null,
+ deadline: words, deadlineDate: date,
+ key: date ? `d:${date}` : words ? `w:${words.toLowerCase()}` : "eventual",
+ };
+}
+
+const sameBoard = (a, b) => a && b &&
+ a.headline?.row === b.headline?.row &&
+ a.active.map((g) => g.row).join("|") === b.active.map((g) => g.row).join("|") &&
+ a.missed.map((g) => g.row).join("|") === b.missed.map((g) => g.row).join("|");
+
+/**
+ * The goal board over the cut: `[{ t, active, headline, missed, cur }]`, one
+ * per change, the first at t 0 (nothing yet), each the board from its `t` to
+ * the next one's. `cur` is his latest stated weight then (null before one).
+ *
+ * @param {{ events?: object[], state?: object[] }} measure the schedule's measure slice
+ * @param {{ hold?: number }} [opts] how long a missed goal is held (MISS_HOLD)
+ */
+export function goalBoard(measure, { hold = MISS_HOLD } = {}) {
+ const events = Array.isArray(measure?.events) ? measure.events : [];
+ const states = Array.isArray(measure?.state) ? measure.state : [];
+ const steps = events
+ .map((e, i) => ({ e, s: states[i + 1] ?? states[states.length - 1] ?? null, i }))
+ .filter(({ e }) => Number.isFinite(e?.t) && own(e) && e.unresolved !== true)
+ .sort((a, b) => a.e.t - b.e.t || a.i - b.i);
+ let active = [];
+ let cur = null;
+ let recordDate = null;
+ const misses = [];
+ const points = [{ t: 0, active: [], headline: null, cur: null }];
+ for (const { e, s } of steps) {
+ if (isIso(e.date) && (recordDate === null || e.date > recordDate)) recordDate = e.date;
+ const before = headlineOf(active, cur);
+ if (e.kind === "goal" || e.kind === "goalLoss") {
+ const g = goalOf(e, s);
+ active = [...active.filter((x) => x.key !== g.key), g];
+ } else if (e.kind === "stated" && Number.isFinite(Number(e.value)) && e.value !== null) {
+ cur = Number(e.value);
+ // Met: a reading of his at or under it, said once it was set and by its day. A ">300" says nothing under.
+ if (e.qualifier !== ">") {
+ active = active.filter((g) => {
+ const edge = goalEdge(g);
+ const inTime = !g.deadlineDate || !isIso(e.date) || e.date <= g.deadlineDate;
+ const after = !g.said || !isIso(e.date) || e.date >= g.said;
+ return !(Number.isFinite(edge) && cur <= edge + 1e-9 && inTime && after);
+ });
+ }
+ }
+ // Past its day: missed when his latest weight is over it, else gone without a word.
+ if (recordDate) {
+ const kept = [];
+ for (const g of active) {
+ if (g.deadlineDate && recordDate > g.deadlineDate) {
+ const edge = goalEdge(g);
+ if (Number.isFinite(edge) && Number.isFinite(cur) && cur > edge) {
+ misses.push({ ...g, at: e.t, wasHeadline: before?.row === g.row });
+ }
+ } else kept.push(g);
+ }
+ active = kept;
+ }
+ points.push({ t: e.t, active: [...active], headline: headlineOf(active, cur), cur });
+ }
+ // Every second the board changes: each step, and each missed goal's end.
+ const times = [...new Set([...points.map((p) => p.t), ...misses.map((m) => r4(m.at + hold))])].sort((a, b) => a - b);
+ const at = (t) => {
+ let p = points[0];
+ for (const q of points) if (q.t <= t + 1e-9) p = q; else break;
+ return p;
+ };
+ const out = [];
+ for (const t of times) {
+ const p = at(t);
+ const b = { t, active: p.active, headline: p.headline, missed: misses.filter((m) => m.at <= t + 1e-9 && t < m.at + hold - 1e-9), cur: p.cur };
+ if (!out.length || !sameBoard(out[out.length - 1], b)) out.push(b);
+ }
+ return out;
+}
+
+/** The board at cut second `t` (goalBoard's state in force then). */
+export function goalsAt(board, t) {
+ let b = board[0] ?? { t: 0, active: [], headline: null, missed: [], cur: null };
+ for (const x of board) if (x.t <= t + 1e-9) b = x; else break;
+ return b;
+}
diff --git a/umtool/report-to-video/measure-goals.test.mjs b/umtool/report-to-video/measure-goals.test.mjs
@@ -0,0 +1,174 @@
+// The goal board (measure-goals.mjs) and how the dial draws it
+// (chrome-instruments.mjs): every goal in force, the closest as the headline,
+// a newer goal of the same horizon replacing the older, a goal met or past its
+// day leaving -- missed, struck in red a moment, when his weight is over it.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { boardGoalWords, dialHtml, goalLines, goalMarks } from "./chrome-instruments.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { frameKeys } from "./frame-keys.mjs";
+import { MISS_HOLD, goalBoard, goalNeed, goalsAt, headlineOf } from "./measure-goals.mjs";
+
+const FPS = 30;
+const SCALE = { min: 220, max: 400 };
+const fonts = { DeckSans: "assets/DeckSans.ttf", DeckSansBold: "assets/DeckSansBold.ttf" };
+
+/** A measure from events: each state after it, its `goal` the resolution of a goalLoss when `resolved` names one. */
+function measureOf(events) {
+ const state = [{ t: 0 }];
+ for (const e of events) state.push({ t: e.t, ...(e.resolved ? { goal: { row: e.row, value: e.resolved, loss: Math.abs(e.value) } } : {}) });
+ return { scale: SCALE, events: events.map(({ resolved, ...e }) => e), state };
+}
+const stated = (t, row, date, value, qualifier = null) => ({ t, row, date, kind: "stated", value, qualifier });
+const goal = (t, row, date, value, extra = {}) => ({ t, row, date, kind: "goal", value, ...extra });
+const loss = (t, row, date, value, resolved, extra = {}) => ({ t, row, date, kind: "goalLoss", value, resolved, ...extra });
+
+const rows = (b) => b.active.map((g) => g.row);
+
+test("a ladder of three: each in force, the CLOSEST the headline -- not the most ambitious, not the latest", () => {
+ const m = measureOf([
+ stated(1, "s1", "2026-01-09", 337),
+ goal(2, "g1", "2026-01-16", 320, { asOf: "2026-04-01" }), // by his birthday: 17 to go
+ loss(3, "g2", "2026-01-16", -75, 262, { deadline: "by the end of 2026" }), // 75 to go
+ goal(4, "g3", "2026-01-16", 240), // eventual: 97 to go
+ ]);
+ const board = goalBoard(m);
+ const end = goalsAt(board, 10);
+ assert.deepEqual(rows(end), ["g1", "g2", "g3"]);
+ assert.equal(end.headline.row, "g1");
+ assert.equal(end.headline.deadlineDate, "2026-04-01", "a goal's asOf is the day it is for");
+ assert.equal(end.active[1].deadlineDate, "2026-12-31", "his deadline words, read");
+ assert.equal(goalNeed(end.active[1], 337), 75);
+ // Each step on its own second.
+ assert.equal(goalsAt(board, 2.5).headline.row, "g1");
+ assert.deepEqual(rows(goalsAt(board, 3.5)), ["g1", "g2"]);
+ // The words: the headline's, with its day.
+ assert.equal(boardGoalWords(end.headline), "GOAL 320 · BY APR 2026");
+ assert.equal(boardGoalWords(end.active[1]), "GOAL 262 · BY THE END OF 2026");
+ assert.equal(boardGoalWords(end.active[2]), "GOAL 240");
+});
+
+test("ties go to the soonest deadline, then the latest set; a goal with no weight ranks by its loss", () => {
+ const a = { row: "a", t: 1, target: 300, deadlineDate: "2026-12-25" };
+ const b = { row: "b", t: 2, target: 300, deadlineDate: "2026-06-01" };
+ const c = { row: "c", t: 3, target: 300, deadlineDate: null };
+ assert.equal(headlineOf([a, b, c], 320).row, "b");
+ assert.equal(headlineOf([a, c], 320).row, "a", "undated last");
+ assert.equal(headlineOf([{ ...c, row: "c1", t: 1 }, { ...c, row: "c2", t: 2 }], 320).row, "c2", "then the latest set");
+ const unresolved = { row: "u", t: 1, target: null, loss: 15, deadlineDate: null };
+ assert.equal(headlineOf([a, unresolved], 320).row, "u", "15 to lose beats 20");
+ // Before any stated weight a goal's own loss is all there is; a weight already under reach ranks after any still ahead.
+ assert.equal(goalNeed({ target: 250, loss: 50 }, null), 50);
+ assert.equal(headlineOf([{ row: "met", t: 1, target: 330 }, { row: "ahead", t: 2, target: 300 }], 320).row, "ahead");
+});
+
+test("a newer goal of the same horizon replaces the older: the same day, the same words, or both undated", () => {
+ const m = measureOf([
+ goal(1, "a", "2025-08-15", 275, { asOf: "2026-04-01" }),
+ goal(2, "b", "2026-01-16", 320, { asOf: "2026-04-01" }),
+ goal(3, "c", "2026-01-16", 240),
+ goal(4, "d", "2026-01-17", 250),
+ loss(5, "e", "2026-01-18", -80, 211, { deadline: "by my birthday" }),
+ loss(6, "f", "2026-01-18", -90, 201, { deadline: "By my birthday" }),
+ ]);
+ assert.deepEqual(rows(goalsAt(goalBoard(m), 10)), ["b", "d", "f"]);
+});
+
+test("a goal met in time leaves quietly; one past its day with his weight over it is MISSED, held, then gone", () => {
+ const m = measureOf([
+ stated(1, "s1", "2026-01-09", 337),
+ goal(2, "g1", "2026-01-16", 320, { asOf: "2026-04-01" }),
+ goal(3, "g2", "2026-01-16", 330, { due: "2026-03-01" }),
+ goal(4, "g3", "2026-01-16", 240),
+ stated(5, "s2", "2026-02-10", 329), // meets g2 (330) by its day
+ stated(10, "s3", "2026-05-02", 326), // past g1's day (Apr 2026), over 320: MISSED
+ stated(30, "s4", "2026-06-01", 238.5, "<"), // meets the eventual 240
+ ]);
+ const board = goalBoard(m);
+ assert.deepEqual(rows(goalsAt(board, 6)), ["g1", "g3"], "g2 met");
+ assert.equal(goalsAt(board, 6).headline.row, "g1");
+ const miss = goalsAt(board, 10);
+ assert.deepEqual(rows(miss), ["g3"]);
+ assert.deepEqual(miss.missed.map((g) => [g.row, g.at, g.wasHeadline]), [["g1", 10, true]]);
+ assert.equal(miss.headline.row, "g3");
+ assert.equal(goalsAt(board, 10 + MISS_HOLD - 0.01).missed.length, 1);
+ assert.equal(goalsAt(board, 10 + MISS_HOLD).missed.length, 0, "held MISS_HOLD s, then gone");
+ assert.deepEqual(rows(goalsAt(board, 31)), [], "met");
+ assert.equal(goalsAt(board, 31).missed.length, 0, "a goal met is no miss");
+ // The line under the digits says the miss while it is held, then the next headline.
+ const lines = goalLines(board);
+ const lineAt = (t) => [...lines].reverse().find((l) => l.t <= t);
+ assert.deepEqual(lineAt(11), { t: 10, words: "MISSED 320 · BY APR 2026", missed: true });
+ assert.equal(lineAt(17).words, "GOAL 240");
+ // A day passed with his latest weight UNDER the goal (a reading after the day): no miss, it leaves quietly.
+ const late = goalBoard(measureOf([stated(1, "s1", "2026-01-09", 337), goal(2, "g1", "2026-01-16", 320, { asOf: "2026-04-01" }), stated(3, "s2", "2026-07-05", 300)]));
+ assert.deepEqual(goalsAt(late, 4), { ...goalsAt(late, 4), active: [], missed: [] });
+});
+
+test("seek-safe: the board at t is a pure function of the measure, and the dial's marks read it from either side", () => {
+ const m = measureOf([
+ stated(1, "s1", "2026-01-09", 337),
+ goal(2, "g1", "2026-01-16", 320, { asOf: "2026-04-01" }),
+ goal(3, "g2", "2026-01-16", 240),
+ goal(4, "g3", "2026-01-16", 225, { range: [220, 230], due: "2027-01-01" }),
+ stated(6, "s2", "2026-05-02", 326),
+ ]);
+ assert.deepEqual(goalBoard(m), goalBoard(structuredClone(m)));
+ const board = goalBoard(m);
+ const marks = goalMarks(board, SCALE);
+ assert.deepEqual(marks.map((x) => x.goal.row), ["g1", "g2", "g3"]);
+ assert.equal(marks[2].band, true);
+ const statusAt = (x, t) => [...x.states].reverse().find((s) => s.t <= t)?.status;
+ assert.deepEqual(marks.map((x) => statusAt(x, 3.5)), ["head", "other", "off"]);
+ assert.deepEqual(marks.map((x) => statusAt(x, 6.5)), ["missed", "head", "other"]);
+ assert.deepEqual(marks.map((x) => statusAt(x, 6 + MISS_HOLD + 1)), ["off", "head", "other"]);
+
+ // On the dial's page: the marks' cues, which the frame keys model.
+ const timeline = Array.from({ length: 2 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + 8, cite: 1, section: 0, quote: "q", onscreen: { title: "T" } }));
+ const render = { width: 1920, height: 1080, fps: FPS, palette: {}, chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, qr: { show: false } } } };
+ const schedule = { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render, timeline }), measure: m };
+ const html = dialHtml(schedule, render, { fonts });
+ assert.match(html, /data-k="gm0h"/);
+ assert.match(html, /class="goalw miss" data-k="gw\d+"[^>]*>MISSED 320 · BY APR 2026</);
+ const data = JSON.parse(/<script id="dial-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+ const at = (k, t) => {
+ let v = data.init[k]?.autoAlpha;
+ for (const c of data.cues) if (c.k === k && "autoAlpha" in c.to && c.at + c.dur <= t + 1e-9) v = c.to.autoAlpha;
+ return v;
+ };
+ assert.deepEqual([at("gm0h", 3.5), at("gm1o", 3.5), at("gm0x", 3.5)], [1, 0.85, 0]);
+ assert.deepEqual([at("gm0x", 7), at("gm1h", 7), at("gm0p", 9)], [1, 1, 0]);
+ assert.ok(data.cues.some((c) => c.k === "gm0p" && c.to.autoAlpha === 1), "the miss flashes");
+ const frames = Math.round(schedule.total * FPS);
+ assert.ok(frameKeys({ html, region: "dial", fps: FPS, frames, version: "t" }));
+});
+
+test("the shelf's goal fan reads the same board: the headline in front, +N more, a missed goal struck; a joke or another's goal is no note", async () => {
+ const { goalStates } = await import("./measure-extras.mjs");
+ const { goalsHtml, shelfGoalStates } = await import("./chrome-measure-extras.mjs");
+ const m = { ...measureOf([
+ stated(1, "s1", "2026-01-09", 337),
+ goal(2, "g1", "2026-01-16", 320, { asOf: "2026-04-01" }),
+ goal(3, "g2", "2026-01-16", 240),
+ goal(4, "j1", "2026-01-16", 150, { unresolved: true }),
+ goal(5, "o1", "2026-01-16", 200, { speaker: "madamsavvy" }),
+ stated(10, "s2", "2026-05-02", 326),
+ ]), unit: "lb" };
+ const render = { width: 1920, height: 1080, fps: FPS, palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { measure: {}, dial: true, shelf: { items: ["goals"] }, goals: { position: "shelf" } } } };
+ const schedule = { kind: "deck", fps: FPS, total: 40, transition: 0, segments: [{ id: "a", start: 0, duration: 40, end: 40 }], measure: m };
+ const states = goalStates(schedule, render);
+ assert.deepEqual(states.map((s) => s.at), [2, 3], "the joke and her goal are no notes");
+ const shelf = shelfGoalStates(schedule, states);
+ // A state per goal set, and one where the board alone changes: g1 missed at 10, its hold's end.
+ assert.deepEqual(shelf.map((s) => s.at), [2, 3, 10, 10 + MISS_HOLD]);
+ const front = (s) => s.notes.find((n) => n.depth === 0).key;
+ // At 3 the newest is 240, but the CLOSEST leads: 320, with one more in force.
+ assert.deepEqual([front(shelf[1]), shelf[1].headline, shelf[1].active], ["320 lb", "320 lb", 2]);
+ assert.deepEqual([shelf[2].top, shelf[2].missed, front(shelf[2])], [null, ["320 lb"], "240 lb"]);
+ assert.deepEqual(shelf[3].missed, []);
+ const { html } = goalsHtml(schedule, render, {});
+ assert.match(html, /\+1 more/);
+ assert.match(html, /class="note missed"/);
+});
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -21,9 +21,10 @@
//
// The odometer rule (ruled 5 Nov 2026, "go by his words"): see lossRuns.
import { chronological, dateKey, daysBetween } from "./ledger-shared.mjs";
-import { PROMISE_FORMS, measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs";
+import { PROMISE_FORMS, boundAgrees, displayRange, measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs";
import { goalCell, nextRegime, offOf } from "./panel-model.mjs";
import { offsetIn } from "./gaps.mjs";
+import { validateGhosts } from "./measure-ghosts.mjs";
import { dietRecord } from "./diet-record.mjs";
import { dietRunsOn } from "./finale.mjs";
@@ -32,7 +33,7 @@ export const MEASURE_SLICE_VERSION = 1;
export { PROMISE_FORMS };
/** `render.chrome.deck.measure`'s keys. */
-export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf"]);
+export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts"]);
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`));
@@ -40,16 +41,17 @@ const r1 = (v) => Math.round(v * 10) / 10;
const r3 = (v) => Math.round(v * 1000) / 1000;
/**
- * `render.chrome.deck.measure`, checked: `{ scopes?, scale?, asOf? }` --
+ * `render.chrome.deck.measure`, checked: `{ scopes?, scale?, asOf?, ghosts? }` --
* `scopes` a list of track keys (unique, at least one), `scale` `{ min, max }`
- * (numbers, min < max), `asOf` a date (YYYY-MM-DD). Whether the scopes are
+ * (numbers, min < max), `asOf` a date (YYYY-MM-DD), `ghosts` the dial's claim
+ * ghosts (measure-ghosts.mjs: true, false or their knobs). Whether the scopes are
* the ledger's tracks is measureSettingsProblems' (it has the schema).
*
* @returns {string[]}
*/
export function validateMeasureSettings(v, where = "render.chrome.deck.measure") {
if (v === undefined) return [];
- if (!isObj(v)) return [`${where} must be { scopes, scale, asOf }`];
+ if (!isObj(v)) return [`${where} must be { ${MEASURE_SETTINGS_KEYS.join(", ")} }`];
const errors = [];
for (const k of Object.keys(v)) if (!MEASURE_SETTINGS_KEYS.includes(k)) errors.push(`${where}.${k} is not a measure setting (${MEASURE_SETTINGS_KEYS.join(", ")})`);
if (v.scopes !== undefined) {
@@ -64,6 +66,7 @@ export function validateMeasureSettings(v, where = "render.chrome.deck.measure")
else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`);
}
if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`);
+ errors.push(...validateGhosts(v.ghosts, `${where}.ghosts`));
return errors;
}
@@ -210,11 +213,7 @@ const entrySource = (entry) => (entry?.type === "clip" ? "clip" : entry?.type ==
* as a range -- a wedge, "330–340" -- never the middle alone.
*/
export function rangeOf(row) {
- const m = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(row?.display ?? ""));
- if (!m) return null;
- const lo = Number(m[1]);
- const hi = Number(m[2]);
- return Number.isFinite(lo) && Number.isFinite(hi) && hi > lo ? [lo, hi] : null;
+ return displayRange(row?.display);
}
function eventOf(row, schema, runOf) {
@@ -242,6 +241,8 @@ function eventOf(row, schema, runOf) {
run: kind === "lost" && runOf.has(row.id) ? runOf.get(row.id) : null,
speaker: speakerOf(row),
outcome: row.population === "promise_outcome" && typeof row.outcome === "string" ? row.outcome : null,
+ // Not a usable claim (a joke, a misattributed line): on screen when pinned, in no tally (isUsable).
+ ...(row.scopeConfidence === "unresolved" ? { unresolved: true } : {}),
};
}
@@ -253,6 +254,15 @@ function eventOf(row, schema, runOf) {
*/
export const speakerOf = (row) => (typeof row?.speaker === "string" && row.speaker.trim() ? row.speaker.trim() : null);
+/**
+ * Does the row COUNT -- in a tally (goals set, diets, pledges, the odometer,
+ * "under 300", the goal ladder)? Not when its scope is `unresolved`: the
+ * ledger's word for "not a usable claim" (a joke -- w44, "only way I'm losing
+ * 100 lbs is by amputation" -- or a line that is not his). Such a row is still
+ * a row: pinned, it is on screen, and a reading still reads (operator, 6 Nov).
+ */
+export const isUsable = (row) => row?.scopeConfidence !== "unresolved" && row?.unresolved !== true;
+
// ---------------------------------------------------------------------------
// When a row lands: the spoken number in the clip's words
// ---------------------------------------------------------------------------
@@ -395,7 +405,9 @@ export function measureSlice(manifest, schedule, opts = {}) {
const byId = new Map(rows.map((r) => [r.id, r]));
// HIS rows: every number the instruments draw is the subject's own.
const own = rows.filter((r) => speakerOf(r) === null);
- const { runs, runOf, claims: lossClaims, total } = lossRuns(own, s);
+ // What counts in a tally: his own usable rows.
+ const counted = own.filter(isUsable);
+ const { runs, runOf, claims: lossClaims, total } = lossRuns(counted, s);
const runById = new Map(runs.map((r) => [r.run, r]));
// ---- events: each pinned row at the cut second it lands -------------------
@@ -537,7 +549,12 @@ export function measureSlice(manifest, schedule, opts = {}) {
const row = byId.get(ev.row);
// Another speaker's row feeds the promises and nothing else.
if (ev.speaker !== null && ev.kind !== "promiseClaim" && ev.kind !== "promiseOutcome") { state.push(snapshot(ev.t)); continue; }
- if (ev.kind === "stated" && ev.value !== null) current = { value: ev.value, qualifier: ev.qualifier, row: ev.row, date: ev.date, asOf: ev.asOf, ...(ev.range ? { range: [...ev.range] } : {}) };
+ // An unresolved row is no claim to count: it moves a reading (it is on screen), never a goal, a diet, a promise.
+ if (ev.unresolved && ev.kind !== "stated" && ev.kind !== "remembered") { state.push(snapshot(ev.t)); continue; }
+ // A bound that agrees with the specific weight in force (">300" while he is at 342) is no new figure: the needle
+ // and the number stay (boundAgrees). One that contradicts it (">300" at 291) moves them, as any reading does.
+ if (ev.kind === "stated" && ev.value !== null && boundAgrees(ev, current)) { /* the current weight stands */ }
+ else if (ev.kind === "stated" && ev.value !== null) current = { value: ev.value, qualifier: ev.qualifier, row: ev.row, date: ev.date, asOf: ev.asOf, ...(ev.range ? { range: [...ev.range] } : {}) };
else if (ev.kind === "remembered" && ev.value !== null) remembered.push({ value: ev.value, asOf: ev.asOf, row: ev.row, date: ev.date, ...(ev.qualifier ? { qualifier: ev.qualifier } : {}), ...(ev.range ? { range: [...ev.range] } : {}) });
else if (ev.kind === "goal" || ev.kind === "goalLoss") { goal = goalOf(row); goals.push(ev.row); }
else if (ev.kind === "lost" && ev.run !== null) {
@@ -571,7 +588,8 @@ export function measureSlice(manifest, schedule, opts = {}) {
// ---- totals over the whole record in scope --------------------------------
const all = chronological(own);
const lastStated = [...readings].filter((r) => r.population === "current").pop() ?? null;
- const goalRows = all.filter((r) => r.population === "goal" || r.population === "goal_loss");
+ const tallied = all.filter(isUsable);
+ const goalRows = tallied.filter((r) => r.population === "goal" || r.population === "goal_loss");
const repeats = {};
for (const r of goalRows) { const d = measureDisplay(r, s); repeats[d] = (repeats[d] ?? 0) + 1; }
const goalRepeats = Object.fromEntries(Object.entries(repeats).filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));
@@ -585,18 +603,18 @@ export function measureSlice(manifest, schedule, opts = {}) {
const peakDrift = [...new Set(readings.filter((r) => r.population === "past" && r.asOf && firstStated && dateKey(r.asOf) >= firstStated && Number(r.value) > maxStated).map((r) => Number(r.value)))].sort((a, b) => a - b);
// UNDER 300: a weight he stated below it, or "under 300" itself -- never a
// bound the other way ("over 240" is not a weight under 300).
- const under = stated.filter((r) => {
+ const under = stated.filter(isUsable).filter((r) => {
const q = measureQualifier(r, s);
return q !== ">" && (Number(r.value) < 300 || (Number(r.value) === 300 && q === "<"));
});
const dates = all.map((r) => plotDate(r)).filter(Boolean).map(dateKey).sort();
- const promiseRows = all.filter((r) => r.population === "promise");
+ const promiseRows = tallied.filter((r) => r.population === "promise");
const checksOf = (id) => all.filter((r) => r.population === "promise_check" && r.promise === id);
const outcomeRowOf = (id) => chronological(rows).filter((r) => r.population === "promise_outcome" && r.promise === id && typeof r.outcome === "string").pop() ?? null;
const claimsOf = (id) => chronological(rows).filter((r) => r.population === "promise_claim" && r.promise === id).map(claimOf);
let diets = 0;
try {
- diets = measureTotals(own, s, { strict: false }).switches;
+ diets = measureTotals(counted, s, { strict: false }).switches;
} catch {
diets = 0;
}
@@ -640,7 +658,7 @@ export function measureSlice(manifest, schedule, opts = {}) {
totals,
// The whole diet record, for the finale's detailed runs (`deck.finale.dietRuns`): only when it asks.
...(dietRunsOn(manifest?.render?.chrome?.deck?.finale?.dietRuns)
- ? { record: dietRecord(own, s, regimeTrack, readings, isObj(manifest.render.chrome.deck.finale.dietRuns) ? manifest.render.chrome.deck.finale.dietRuns : {}) }
+ ? { record: dietRecord(counted, s, regimeTrack, readings, isObj(manifest.render.chrome.deck.finale.dietRuns) ? manifest.render.chrome.deck.finale.dietRuns : {}) }
: {}),
};
}
diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs
@@ -5,12 +5,15 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
- isRealtimeLoss, kindOf, lossRuns, measureOn, measureSettingsProblems, measureSlice, pinnedRows, spokenAt, spokenNumbers,
+ isRealtimeLoss, isUsable, kindOf, lossRuns, measureOn, measureSettingsProblems, measureSlice, pinnedRows, spokenAt, spokenNumbers,
validateMeasureSettings,
} from "./measure-slice.mjs";
import { estimateSchedule, validateChrome } from "./deck.mjs";
import { scheduleSlices } from "./modules/index.mjs";
import { validateClaims } from "./factcheck.mjs";
+import { goalBoard } from "./measure-goals.mjs";
+import { boundAgrees, measureScoreboard, measureTotals } from "./measure-totals.mjs";
+import { nextReading } from "./panel-model.mjs";
const SCHEMA = {
kind: "measure",
@@ -195,7 +198,7 @@ test("the settings: their shape, their scopes against the ledger, and when a cut
assert.deepEqual(validateMeasureSettings(undefined), []);
assert.deepEqual(validateMeasureSettings({ scopes: ["weight"], scale: { min: 220, max: 400 }, asOf: "2026-11-05" }), []);
assert.deepEqual(validateMeasureSettings({ scopes: [], scale: { min: 4, max: 2 }, asOf: "Nov 5", x: 1 }), [
- "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf)",
+ "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf, ghosts)",
"render.chrome.deck.measure.scopes must be a list of the ledger's track keys (at least one)",
"render.chrome.deck.measure.scale.min must be below scale.max",
"render.chrome.deck.measure.asOf must be a date (YYYY-MM-DD)",
@@ -276,3 +279,90 @@ test("a promise's outcome: how it ended, and \"kept\" keeps it -- the totals unt
assert.equal(kept.totals.promises[0].kept, true);
assert.equal(plain.state.at(-1).promises[0].outcome, null);
});
+
+// ---------------------------------------------------------------------------
+// The operator's rulings of 6 Nov: a bound that agrees with the weight in force does not move it; an unresolved
+// row and another speaker's count in no tally.
+// ---------------------------------------------------------------------------
+
+test("boundAgrees: a bound the specific weight satisfies agrees; one it contradicts, or a bound in force, does not", () => {
+ const at = (value, extra = {}) => ({ value, qualifier: null, ...extra });
+ assert.equal(boundAgrees({ value: 300, qualifier: ">" }, at(342)), true);
+ assert.equal(boundAgrees({ value: 300, qualifier: ">" }, at(291)), false, "contradicts: new information");
+ assert.equal(boundAgrees({ value: 300, qualifier: ">" }, at(300)), false, "300 is not over 300");
+ assert.equal(boundAgrees({ value: 300, qualifier: "<" }, at(291)), true);
+ assert.equal(boundAgrees({ value: 300, qualifier: "<" }, at(305)), false);
+ assert.equal(boundAgrees({ value: 390, qualifier: "≈" }, at(388)), true);
+ assert.equal(boundAgrees({ value: 390, qualifier: "≈" }, at(380)), false);
+ assert.equal(boundAgrees({ value: 335, range: [330, 340] }, at(337)), true);
+ assert.equal(boundAgrees({ value: 335, range: [330, 340] }, at(342)), false);
+ assert.equal(boundAgrees({ value: 342 }, at(300)), false, "a specific reading always moves it");
+ assert.equal(boundAgrees({ value: 300, qualifier: ">" }, null), false, "nothing in force: as today");
+ assert.equal(boundAgrees({ value: 300, qualifier: ">" }, at(320, { qualifier: ">" })), false, "a bound in force is replaced as today");
+});
+
+test("a bound that agrees with the weight in force leaves the needle and the number; one that contradicts moves them", () => {
+ const rows = (...extra) => [
+ row({ id: "a1", date: "2025-05-01", population: "current", value: 342, display: "342 lb", entryId: "c3" }),
+ ...extra,
+ ];
+ const sliceOf = (ledger) => measureSlice({ ...manifest(), ledger }, { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const currentAfter = (sl, id) => sl.state[sl.events.findIndex((e) => e.row === id) + 1].current;
+ // ">300" at 342: the 342 stands -- its event is still there (its ghost tick, the trail's point).
+ const agree = sliceOf(rows(row({ id: "a2", date: "2025-05-10", population: "current", value: 300, qualifier: ">", display: ">300 lb", entryId: "c4" })));
+ assert.equal(currentAfter(agree, "a2").row, "a1");
+ assert.equal(currentAfter(agree, "a2").value, 342);
+ assert.ok(agree.events.some((e) => e.row === "a2" && e.kind === "stated"));
+ // "<300" at 342 contradicts it: new information, the needle moves.
+ const contra = sliceOf(rows(row({ id: "a2", date: "2025-05-10", population: "current", value: 300, qualifier: "<", display: "<300 lb", entryId: "c4" })));
+ assert.deepEqual([currentAfter(contra, "a2").row, currentAfter(contra, "a2").qualifier], ["a2", "<"]);
+ // A bound with nothing specific in force behaves as it did: it is the reading.
+ const first = sliceOf([row({ id: "a2", date: "2025-05-10", population: "current", value: 300, qualifier: ">", display: ">300 lb", entryId: "c4" })]);
+ assert.equal(currentAfter(first, "a2").row, "a2");
+ // The panel's reading cell keeps the same rule.
+ const prev = nextReading(null, row({ id: "a1", date: "2025-05-01", population: "current", value: 342, display: "342 lb" }), SCHEMA);
+ assert.equal(nextReading(prev, row({ id: "a2", date: "2025-05-10", population: "current", value: 300, qualifier: ">", display: ">300 lb" }), SCHEMA).row, "a1");
+ assert.equal(nextReading(prev, row({ id: "a3", date: "2025-05-10", population: "current", value: 300, qualifier: "<", display: "<300 lb" }), SCHEMA).row, "a3");
+});
+
+test("an unresolved row (a joke) counts in no tally -- goals set, the goal, diets, promises, the odometer, under 300 -- pinned or not", () => {
+ const sliceOf = (ledger) => measureSlice({ ...manifest(), ledger }, { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const plain = sliceOf(LEDGER);
+ const joke = { scopeConfidence: "unresolved" };
+ const extra = [
+ // w44's shape: "only way I'm losing 100 lbs is by amputation" -- unpinned, and a pinned one besides.
+ row({ id: "j1", date: "2025-06-07", population: "goal_loss", value: -100, display: "lose 100", ...joke }),
+ row({ id: "j2", date: "2025-06-07", population: "goal", value: 200, display: "200", entryId: "c5", ...joke }),
+ row({ id: "j3", date: "2025-06-07", scope: "regime", population: "status", value: "glp1", event: "start", display: "glp1", entryId: "c5", ...joke }),
+ row({ id: "j4", date: "2025-06-07", population: "delta", value: -150, display: "-150", entryId: "c5", ...joke }),
+ row({ id: "j5", date: "2025-06-07", population: "promise", value: null, display: "a joke promise", entryId: "c5", ...joke }),
+ ];
+ const sl = sliceOf([...LEDGER, ...extra]);
+ for (const k of ["goals", "goalRepeats", "diets", "lost", "runs", "under300"]) assert.deepEqual(sl.totals[k], plain.totals[k], k);
+ assert.deepEqual(sl.totals.promises.map((p) => p.row), plain.totals.promises.map((p) => p.row));
+ const last = sl.state.at(-1), was = plain.state.at(-1);
+ for (const k of ["goal", "goals", "diet", "lost", "current"]) assert.deepEqual(last[k], was[k], k);
+ // Pinned, it is still an event (on screen), marked; the goal board passes over it.
+ assert.equal(sl.events.find((e) => e.row === "j2").unresolved, true);
+ assert.equal(plain.events.find((e) => e.row === "w11").unresolved, undefined, "a usable row's event is as it was");
+ assert.ok(!goalBoard(sl).some((b) => b.active.some((g) => g.row === "j2")));
+ assert.equal(isUsable({ scopeConfidence: "unresolved" }), false);
+ assert.equal(isUsable({ scopeConfidence: "read" }), true);
+});
+
+test("the scoreboard's tallies (goals set, diets, pledges) count neither an unresolved row nor another speaker's", () => {
+ const base = [
+ row({ id: "g1", date: "2025-01-01", population: "goal", value: 250, display: "250" }),
+ row({ id: "r1", date: "2025-01-02", scope: "regime", population: "status", value: "keto", event: "start", display: "keto" }),
+ ];
+ const noise = [
+ row({ id: "g2", date: "2025-02-01", population: "goal_loss", value: -100, display: "lose 100", scopeConfidence: "unresolved" }),
+ row({ id: "g3", date: "2025-02-02", population: "goal", value: 200, display: "200", speaker: "madamsavvy" }),
+ row({ id: "r2", date: "2025-02-03", scope: "regime", population: "status", value: "carnivore", event: "start", display: "carnivore", speaker: "madamsavvy" }),
+ row({ id: "r3", date: "2025-02-04", scope: "regime", population: "status", value: "glp1", event: "start", display: "glp1", scopeConfidence: "unresolved" }),
+ ];
+ const board = (ledger) => measureScoreboard(measureTotals(ledger, SCHEMA, { strict: false })).final;
+ const a = board(base), b = board([...base, ...noise]);
+ assert.deepEqual([b.goals.count, b.diets.count, b.pledges.count], [a.goals.count, a.diets.count, a.pledges.count]);
+ assert.equal(b.goals.last.id, "g1");
+});
diff --git a/umtool/report-to-video/measure-totals.mjs b/umtool/report-to-video/measure-totals.mjs
@@ -1056,7 +1056,9 @@ export function measureTotals(ledger, schema, { strict = true } = {}) {
for (const e of all) {
const gaps = measureGaps(e, s);
const ruled = gaps.length === 0;
- const settled = ruled && e.scopeConfidence !== "unresolved";
+ // Counted only when it is a usable claim of HIS: an `unresolved` scope (a joke, a misattributed line) and another
+ // speaker's row (`speaker`) are in the record and on screen, never in a tally (operator, 6 Nov).
+ const settled = ruled && e.scopeConfidence !== "unresolved" && !(typeof e.speaker === "string" && e.speaker.trim());
const tr = trackOf(s, e.scope);
const at = plotDate(e);
const flags = [];
@@ -1610,6 +1612,41 @@ export function freshestReading(claim, at, prev) {
return !prev || dateKey(at) > dateKey(prev.at);
}
+/** A range his words give ("330-340", "220–240 lb"), as `[lo, hi]`, or null. */
+export function displayRange(display) {
+ const m = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(display ?? ""));
+ if (!m) return null;
+ const lo = Number(m[1]);
+ const hi = Number(m[2]);
+ return Number.isFinite(lo) && Number.isFinite(hi) && hi > lo ? [lo, hi] : null;
+}
+
+/**
+ * Does a QUALIFIED reading agree with the SPECIFIC one in force -- so it is no
+ * new figure and the current weight stays (operator, 6 Nov: "If a range is
+ * provided (e.g. 'over 300') and we already match with a specific number
+ * (e.g. 342), don't change the current weight")? `bound` and `specific` are
+ * `{ value, qualifier?, range? }`. Agrees when `specific` is a plain number (no
+ * qualifier, no range) and `bound` is a qualified one it satisfies: ">300"
+ * by anything over 300, "<300" by anything under, "≈390" by 387 to 391 (the
+ * dial's wedge), a range by anything inside it. A bound that CONTRADICTS the
+ * specific reading (">300" against 291) is new information: it does not agree,
+ * and it moves the reading as any other does.
+ */
+export function boundAgrees(bound, specific) {
+ if (!bound || !specific) return false;
+ const c = Number(specific.value);
+ if (!Number.isFinite(c) || specific.qualifier || Array.isArray(specific.range)) return false;
+ const v = Number(bound.value);
+ const r = Array.isArray(bound.range) && bound.range.length === 2 ? bound.range : null;
+ if (r) return c >= r[0] && c <= r[1];
+ if (!Number.isFinite(v)) return false;
+ if (bound.qualifier === ">") return c > v;
+ if (bound.qualifier === "<") return c < v;
+ if (bound.qualifier === "≈") return c >= v - 3 && c <= v + 1;
+ return false;
+}
+
/**
* A goal as a weight, when it can be one.
*
diff --git a/umtool/report-to-video/modules/dial.mjs b/umtool/report-to-video/modules/dial.mjs
@@ -2,9 +2,13 @@
// the instruments' column (instruments.mjs, deck.mjs instrumentsGeometry). A
// red needle swings to every weight he states, on the word, overshoots and
// settles; "almost", "over", "under" draw a wedge; his remembered weights are
-// grey ghost ticks, the latest a long ghost needle with its as-of date; his
-// latest goal an amber tick on the bezel; the 300 lb mark accented; the
-// weight in big digits under the hub. chrome-instruments.mjs writes the page.
+// grey ghost ticks, the latest a long ghost needle with its as-of date; every
+// goal in force a mark on the bezel, the CLOSEST (measure-goals.mjs) the full
+// amber tick with its words, a missed one struck in red; with
+// `deck.measure.ghosts`, a faint tick on the rim for every weight he has
+// claimed, coloured by how often (measure-ghosts.mjs); the 300 lb mark
+// accented; the weight in big digits under the hub. chrome-instruments.mjs
+// writes the page.
import path from "node:path";
import { instrumentsGeometry } from "../deck.mjs";
@@ -21,7 +25,7 @@ export default defineModule({
kind: "overlay-whole",
slot: "instruments",
title: "Scale dial",
- summary: "A bathroom-scale face: the needle swings to each weight he states, his remembered weights as ghosts, his goal on the bezel.",
+ summary: "A bathroom-scale face: the needle swings to each weight he states, his remembered weights as ghosts, every goal in force on the bezel (the closest headlined), and -- with deck.measure.ghosts -- a faint tick for every weight he has claimed.",
configKey: "render.chrome.deck.dial",
defaults: DIAL_DEFAULTS,
validate: settingsOf("dial").validate,
@@ -29,7 +33,7 @@ export default defineModule({
ui: [
{ key: "mark", type: "number", min: 0, max: 2000, step: 1, label: "Accented weight", default: 300 },
{ key: "ghosts", type: "boolean", label: "Remembered weights as ghosts", default: true },
- { key: "goal", type: "boolean", label: "The latest goal on the bezel", default: true },
+ { key: "goal", type: "boolean", label: "Every goal in force on the bezel, the closest headlined", default: true },
{ key: "finale", type: "boolean", label: "Large in the finale", default: true },
{ key: "label", type: "text", label: "Over the digits", default: DIAL_DEFAULTS.label },
{ key: "placement", type: "enum", options: ["column", "corner"], label: "Where the instruments stand", default: "column" },
@@ -40,11 +44,14 @@ export default defineModule({
],
docs: {
heading: "Scale dial",
- intro: "A bathroom-scale face at the top of the instruments' column (the right of the frame; the clip moves to the left -- `instrumentsGeometry`, 1248×702 footage beside a 600 px column at 1920×1080). It reads the schedule's `measure` (the measure ledger's slice): the red needle swings to each STATED weight at its event's `t` (the spoken word) with a spring (`back.out`, 0.9 s) and rests there -- a frame at rest is reused, not captured again; a qualifier draws a wedge in pounds (≈ 3 under to 1 over, `>` 10 up, `<` 10 down); every REMEMBERED weight is a grey tick, the latest a long ghost needle with its as-of date; the latest goal is an amber tick on the bezel and its words under the digits. It comes and goes with the deck (a card, the finale). With any instrument on, the posts stay in the footage box (`posts.shift` does not apply), and the side panel (`threads`, `flips`) and the posts feed are refused.",
+ intro: "A bathroom-scale face at the top of the instruments' column (the right of the frame; the clip moves to the left -- `instrumentsGeometry`, 1248×702 footage beside a 600 px column at 1920×1080). It reads the schedule's `measure` (the measure ledger's slice): the red needle swings to each STATED weight at its event's `t` (the spoken word) with a spring (`back.out`, 0.9 s) and rests there -- a frame at rest is reused, not captured again; a BOUND that agrees with the specific weight in force (\">300\" while he is at 342, \"≈390\" at 388, \"330-340\" at 337) is no new figure and moves neither the needle nor the number (measure-totals.mjs `boundAgrees`; it still leaves its claim ghost), while one that contradicts it (\">300\" at 291) moves them as any reading does; a qualifier draws a wedge in pounds (≈ 3 under to 1 over, `>` 10 up, `<` 10 down); every REMEMBERED weight is a grey tick, the latest a long ghost needle with its as-of date. GOALS (measure-goals.mjs `goalBoard`): every goal in force at the playhead is a mark on the bezel at its weight -- in force from the moment the cut shows it until he meets it in time, a newer goal of the same HORIZON replaces it (the same deadline day, the same deadline words, or both undated), or the record's date passes its day. The HEADLINE is the CLOSEST of them -- the least still to lose from his latest stated weight (a range to its top), ties to the soonest deadline -- the full amber tick, its words under the digits (`GOAL 320 · BY APR 2026`); the others a thin amber tick, no words; a range an amber band too. A goal whose day passes with his latest weight over it is MISSED: struck in the needle's red with a red flash, the line under the digits `MISSED 320 · BY APR 2026` for 6 s (`MISS_HOLD`), then gone; a day passing with his weight under it (a reading after the day) leaves quietly. A goal's day: the ledger's `due`, else his `deadline` words read (\"by Christmas\", \"by the end of 2026\"), else the row's `asOf`. Any page that shows a goal reads the same board: `goalBoard(schedule.measure)` -> `[{ t, active, headline, missed, cur }]`, `goalsAt(board, t)`. It comes and goes with the deck (a card, the finale). With any instrument on, the posts stay in the footage box (`posts.shift` does not apply), and the side panel (`threads`, `flips`) and the posts feed are refused.",
rows: [
["`deck.dial`", "`true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off", "`umtool look <p> deck.dial=false`"],
["`deck.dial.mark`", "a weight, or `null` · default `300` (its tick and label in the accent)", "`umtool look <p> deck.dial.mark=300`"],
- ["`deck.dial.ghosts`, `.goal`", "bool · default `true` each", "`umtool look <p> deck.dial.ghosts=false`"],
+ ["`deck.dial.ghosts`, `.goal`", "bool · default `true` each (`.goal`: every goal in force, the closest headlined)", "`umtool look <p> deck.dial.ghosts=false`"],
+ ["`deck.measure.ghosts`", "`true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t", "`umtool look <p> deck.measure.ghosts=true`"],
+ ["`deck.measure.ghosts.opacity`, `.tolerance`", "0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5`", "`umtool look <p> deck.measure.ghosts='{\"tolerance\":1}'`"],
+ ["`deck.measure.ghosts.ramp`, `.pulse`", "2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true`", "`umtool look <p> deck.measure.ghosts='{\"ramp\":[\"#98a29b\",\"#e8a33f\",\"#f37e47\"],\"pulse\":false}'`"],
["`deck.dial.needle`", "a #hex · default `#ff5a4e`", "`umtool look <p> deck.dial.needle='\"#ff5a4e\"'`"],
["`deck.dial.label`", "words over the digits, ≤ 40 · default `HE SAYS HE WEIGHS`", "`umtool look <p> deck.dial.label='\"…\"'`"],
["`deck.dial.finale`", "bool · default `true`: the dial and the odometer large in the finale (module `dial-finale`)", "`umtool look <p> deck.dial.finale=false`"],
diff --git a/umtool/report-to-video/modules/goals.mjs b/umtool/report-to-video/modules/goals.mjs
@@ -28,7 +28,7 @@ export default measureExtraModule({
rows: [
["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
["`deck.goals.position`, `.x`/`.y`, `.scale`", "`top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1", "`umtool look <p> deck.goals.position=bottom-left`"],
- ["`deck.goals.position=shelf`", "its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- the headline goal in front when the measure state names one (\`goals.headline\`: the closest goal in force) with \"+N more\" for the others in force, else the newest; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial", "`umtool look <p> deck.shelf.items='[\"diet\",\"goals\"]' deck.goals.position=shelf`"],
+ ["`deck.goals.position=shelf`", "its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs \`goalsAt(goalBoard(schedule.measure), t)\`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with \"+N more\" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial", "`umtool look <p> deck.shelf.items='[\"diet\",\"goals\"]' deck.goals.position=shelf`"],
["`deck.goals.max`, `.color`, `.countdown`", "1–8 notes · #hex paper · bool · default 4, the palette's amber, `true`", "`umtool look <p> deck.goals.max=6`"],
["`deck.goals.hold`, `.finale`", "0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide`", "`umtool look <p> deck.goals.hold=0`"],
],
diff --git a/umtool/report-to-video/panel-model.mjs b/umtool/report-to-video/panel-model.mjs
@@ -19,7 +19,7 @@
// cell to THIS track's off regime, and only when it names what is
// open (offCloses: "off GLP-1" said three weeks into keto leaves
// Keto in the cell; the off-scope fix, eff32c8d).
-import { freshestReading, goalAbsolute, measureDisplay, measureQualifier, measureSchema, offCloses, plotDate } from "./measure-totals.mjs";
+import { boundAgrees, displayRange, freshestReading, goalAbsolute, measureDisplay, measureQualifier, measureSchema, offCloses, plotDate } from "./measure-totals.mjs";
/** The events that OPEN or sustain a regime segment, against those that close. */
export const OPENING = new Set(["start", "on"]);
@@ -47,6 +47,8 @@ export function offOf(schema, trackKey) {
export function nextReading(prev, row, schema) {
const at = plotDate(row);
if (!freshestReading(row, at, prev)) return prev;
+ // A bound the reading in force already satisfies (">300" at 342) leaves it as it is (boundAgrees).
+ if (row.population === "current" && boundAgrees({ value: row.value, qualifier: measureQualifier(row, schema), range: displayRange(row.display) }, prev && { ...prev, range: displayRange(prev.display) })) return prev;
return {
value: Number(row.value),
at,
diff --git a/umtool/report-to-video/shelf.test.mjs b/umtool/report-to-video/shelf.test.mjs
@@ -10,7 +10,8 @@ import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { dietHtml, goalsHtml, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
+import { dietHtml, goalsHtml, shelfGoalStates, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
+import { goalBoard, goalsAt } from "./measure-goals.mjs";
import { shelfHtml, shelfNoteGeometry } from "./chrome-shelf.mjs";
import { deckGeometry, entryShelfNotes, estimateSchedule, instrumentsGeometry, parseShelfNote, validateChrome } from "./deck.mjs";
import { dietDays, dietStates, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs";
@@ -258,25 +259,30 @@ test("goals on the shelf: the count and the fanned notes, the fan taking the she
assert.match(html, /<div class="gc"><div class="gn" data-k="s0\.c">1<\/div><div class="gl">goal set<\/div><\/div>/);
assert.match(html, /class="note" data-k="s\d+\.n\d+" style="z-index:19"><div class="tape"><\/div><div class="nf"/);
assert.match(html, /<div class="nb"[^>]*><div class="bt">LOSE 100<\/div>/, "an older note shows its words beside the one in front");
- assert.equal(items.length, goalStates(schedule(), r).length);
+ // A block per state of the fan: each goal he sets, and each second the goal board alone changes (shelfGoalStates).
+ assert.equal(items.length, shelfGoalStates(schedule(), goalStates(schedule(), r)).length);
// Off the shelf: the pile in the footage, as it was.
assert.doesNotMatch(goalsHtml(schedule(), renderOf(INSTRUMENTS), { fonts: {} }).html, /class="gc"/);
});
-test("goals on the shelf: the headline goal leads when the state names one (goals.headline), with the ladder's count; else the newest", () => {
+test("goals on the shelf: the dial's goal board orders the fan -- its headline in front, +N more for the others in force", () => {
const r = renderOf(FAN);
const m = clone(MEASURE);
- // The state as the dial-ghosts lane writes it: goals an object with the headline (a goal carrying its row) and those in force.
- const firstGoal = m.events.findIndex((e) => e.kind === "goal" || e.kind === "goalLoss");
+ // Two goals in force at the end, the newer the more ambitious: the closer one leads, not the newest.
const lastGoal = m.events.map((e, i) => [e, i]).filter(([e]) => e.kind === "goal" || e.kind === "goalLoss").at(-1)[1];
- const hl = m.events[firstGoal].row;
- const s = m.state[lastGoal + 1];
- s.goals = { set: Array.isArray(s.goals) ? s.goals : [], headline: { row: hl }, active: [hl, "x", "y"] };
- const states = goalStates(schedule({ measure: m }), r);
- assert.equal(states.at(-1).headline, states[0].top, "the first goal's note heads the last state");
- assert.equal(states.at(-1).active, 3);
- const { html } = goalsHtml(schedule({ measure: m }), r, { fonts: {} });
- assert.match(html, /<div class="mo">\+2 more<\/div>/);
- // Without it, the newest leads, as before.
- assert.equal("headline" in goalStates(schedule(), r).at(-1), false);
+ const t = m.events[lastGoal].t;
+ m.events.splice(lastGoal + 1, 0, { ...m.events[lastGoal], t: t + 0.5, row: "far", kind: "goal", value: 221, display: "221", qualifier: null, deadline: null, due: null, asOf: null, range: undefined });
+ m.state.splice(lastGoal + 2, 0, { ...m.state[lastGoal + 1], t: t + 0.5 });
+ const sched = schedule({ measure: m });
+ const board = goalBoard(m);
+ const end = goalsAt(board, Infinity);
+ assert.ok(end.active.length > 1 && end.headline.row !== "far", "the fixture's last goal is closer than 221");
+ const shelf = shelfGoalStates(sched, goalStates(sched, r));
+ const last = shelf.at(-1);
+ const front = last.notes.find((n) => n.depth === 0);
+ assert.equal(front.key, last.headline, "the board's headline is in front");
+ assert.notEqual(front.key, "221 lb", "not the newest");
+ assert.equal(last.active, end.active.length);
+ const { html } = goalsHtml(sched, r, { fonts: {} });
+ assert.match(html, new RegExp(`<div class="mo">\\+${end.active.length - 1} more</div>`));
});