Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2b81e91e8d2047c4f62cd031e6a8a4e7e626b48f
parent 6111ff288ff4c7c7186026d1590c4c4fddf13df7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 20:57:19 -0500

Merge main into lane/dial-ghosts (shelf-overlap, clip-fixes): the slice imports both; the diet record counts his usable rows only

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/clip/route.ts | 9+++++++++
Mumtool/app/api/report/fetch/route.ts | 36++++++++++++++++++++++++++----------
Mumtool/components/projects/ClipBench.tsx | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/components/projects/bench/BenchWave.tsx | 7++++++-
Aumtool/components/projects/bench/CutEdges.tsx | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/GapsZoom.tsx | 131++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/bench/useGapEditor.ts | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/components/projects/reel/ReelBench.tsx | 13+++++++++++--
Mumtool/components/projects/review/ClipEditor.tsx | 25+++++++++++++++++++++++++
Mumtool/docs/clip-bench.md | 20++++++++++++++++++--
Mumtool/docs/knobs.md | 25++++++++++++++++++++-----
Mumtool/docs/report-video.md | 2+-
Mumtool/e2e/clip-bench.spec.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 16++++++++++++++++
Mumtool/e2e/gaps-zoom.spec.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/play-measure.spec.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/benchData.ts | 8++++++--
Mumtool/lib/report/driver.mjs | 17++++++++++++-----
Mumtool/lib/report/serve.mjs | 2+-
Mumtool/report-to-video/chrome-measure-extras.mjs | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/chrome-runs-finale.mjs | 298+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 10++++++++--
Aumtool/report-to-video/diet-record.mjs | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/finale.mjs | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/gaps.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/gaps.test.mjs | 54+++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/measure-extras.mjs | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/report-to-video/measure-slice.mjs | 6++++++
Mumtool/report-to-video/modules/diet.mjs | 6+++++-
Mumtool/report-to-video/modules/finale.mjs | 3++-
Mumtool/report-to-video/modules/goals.mjs | 1+
Mumtool/report-to-video/modules/index.mjs | 3++-
Mumtool/report-to-video/modules/measure-extras-settings.mjs | 32++++++++++++++++++++++++++++++--
Mumtool/report-to-video/modules/registry.test.mjs | 4++--
Aumtool/report-to-video/modules/runs-finale.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/modules/shelf.mjs | 2+-
Aumtool/report-to-video/runs-finale.test.mjs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/shelf.test.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
38 files changed, 2392 insertions(+), 117 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&apos;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 @@ -152,7 +152,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 @@ -1252,7 +1252,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=` | @@ -1536,6 +1536,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr | [Flips](#flips) `flips` | Pairs of what was said then and now, in the side panel. (a page over the whole cut) | `render.chrome.flips` | | [Chapters](#chapters) `chapter` | A section bumper over the first seconds of the clip it opens: title, subtitle, date. (pages at their own seconds) | `render.chrome.chapter` | | [Finale](#finale) `finale` | The cut's last clips under the rail redrawn large, the final totals and stats cards. (pages at their own seconds) | `render.chrome.deck.finale` | +| [Diet runs in the finale](#diet-runs-in-the-finale) `runs-finale` | The finale's detailed diet record: every run from the first row a bar in its diet's ink, the empty years a break, the stops and medication marked, his weights over it, the long runs and the open one labelled. (pages at their own seconds) | -- | | [Dial finale](#dial-finale) `dial-finale` | The finale with the dial and the odometer large: the needle drops to his last stated weight, the wheels roll to the total, NET holds. (pages at their own seconds) | -- | | [Promise clock](#promise-clock) `promise` | Days since a promise -- to the clip on screen, then to the render date -- with each check's words and whether it was kept. (a page over the whole cut) | `render.chrome.deck.promise` | @@ -1549,7 +1550,7 @@ it can be seeked. `POST /api/report/chrome/preview` returns every such module th build's predicate) as `layers: [{id, z, region, clock, ready, geometry, src | windows}]`; the client lays them by z over the deck's page, a whole-cut page for the whole cut, a window module's page only inside each window. -Declaring `play`: `stats`, `pair`, `status`, `fx`, `shelf`, `streak`, `diet`, `peak`, `goals`, `threads`, `dial`, `odometer`, `trail`, `flips`, `chapter`, `dial-finale`, `promise`. +Declaring `play`: `stats`, `pair`, `status`, `fx`, `shelf`, `streak`, `diet`, `peak`, `goals`, `threads`, `dial`, `odometer`, `trail`, `flips`, `chapter`, `runs-finale`, `dial-finale`, `promise`. Still drawn by their own paths (the response's `src`, `feed`, `posts`, `stamp` and `finale` keys), and what moving each onto `play` needs: the deck (`shell`) -- its typed words patched in live (`deck:text`) and the `deck:ready` @@ -1756,7 +1757,7 @@ Overlays on the picture -- receipts, a zoom, the scrubber, a kinetic quote, punc ### Shelf -A strip of the frame cleared beside the footage (`render.chrome.deck.shelf`, shelf-settings.mjs): the footage moves to the frame's top, `railGap` (24 px) in (`side: "below"`), or down onto the deck (`"above"`), and what it leaves -- as wide as the footage, 24 px clear of it and of the frame's edge or the deck -- is the shelf (beside the instruments' column, 1248×116 at (24, 750)). Everything that reads the footage box (the instruments, the posts, the chapter band, the finale, Play) follows it. Its occupants stand in it left to right in `items` order, `gap` apart, each at its own width scaled to the shelf's height (all a size down together when they would not fit): the measure extras that take `position: "shelf"` -- `diet` (its dated tags by default: `deck.diet.form`), `streak`, `goals`, `peak` -- and `note`, an entry's `shelfNote` in the width left (a chip that comes and goes with its entry; at least 160 px). Nothing covers the shelf, so its occupants never dodge a post card or a chapter band (an entry's `hideModules` still hides one). It needs 72 px of room or the deck refuses, naming the way out (a smaller `footageScale`, or `subtitle.lines 1`): with the instruments' column it is 116 px, 77 with `subtitle.lines: 2`; full-width footage at the default 0.82 leaves none. Off (absent, `false`), the footage stands where it always did. +A strip of the frame cleared beside the footage (`render.chrome.deck.shelf`, shelf-settings.mjs): the footage moves to the frame's top, `railGap` (24 px) in (`side: "below"`), or down onto the deck (`"above"`), and what it leaves -- as wide as the footage, 24 px clear of it and of the frame's edge or the deck -- is the shelf (beside the instruments' column, 1248×116 at (24, 750)). Everything that reads the footage box (the instruments, the posts, the chapter band, the finale, Play) follows it. Its occupants stand in it left to right in `items` order, `gap` apart, each at its own width scaled to the shelf's height (all a size down together when they would not fit; a goal stack on it takes the width left over, its notes fanning wider, so the shelf does not end in a gap): the measure extras that take `position: "shelf"` -- `diet` (its dated tags by default: `deck.diet.form`), `streak`, `goals`, `peak` -- and `note`, an entry's `shelfNote` in the width left (a chip that comes and goes with its entry; at least 160 px). Nothing covers the shelf, so its occupants never dodge a post card or a chapter band (an entry's `hideModules` still hides one). It needs 72 px of room or the deck refuses, naming the way out (a smaller `footageScale`, or `subtitle.lines 1`): with the instruments' column it is 116 px, 77 with `subtitle.lines: 2`; full-width footage at the default 0.82 leaves none. Off (absent, `false`), the footage stands where it always did. | Knob | Range · default | From a terminal | |---|---|---| @@ -1791,6 +1792,8 @@ The diet he names as a rubber stamp in a corner of the footage box (`render.chro | `deck.diet.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `bottom-left`, unset, 1 | `umtool look <p> deck.diet.position=top-right` | | `deck.diet.hold`, `.finale` | 0 (up from the first diet on) or 2–600 s · `hide` `show` · default 0, `hide` | `umtool look <p> deck.diet.hold=15` | | `deck.diet.form`, `.tags` | `stamp` · `tags`: the last `tags` diets as a row of dated tags -- each a small stamp with the regime's word in its ink, "DIET #n" and the ledger's words (less the regime they open with: "5 carbs a day"), and the day he switched to it (`state.diet.since`, "Mar 14, 2025"; new words for the same diet keep that day); at each change the new tag slams in at the left, the older slide right and dim, the one past `tags` falls off; a change of words alone fades the new tag over the old; a null diet is a grey "NO DIET" tag with its date · 1–4 · default `stamp` (`tags` on the shelf), 3 | `umtool look <p> deck.diet.form=tags deck.diet.tags=2` | +| `deck.diet.overlap` | 0–0.8, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past `tags` slides off the back. The fan is narrower by what hides. An older tag's word and date need 110 design px of it, so it is refused past 0.5 (0.63 with `days`) | `umtool look <p> deck.diet.overlap=0.5` | +| `deck.diet.days` | `true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's "Day N"), in a column of its own -- the tag 300 design px wide · default `false` | `umtool look <p> deck.diet.days=true` | | `deck.diet.colors`, `.labels` | `{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names | `umtool look <p> deck.diet.labels='{"glp1":"Ozempic"}'` | | `deck.diet.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.diet.onPosts=hide` | | `deck.diet.position=shelf` | in its own slot on the shelf (`deck.shelf`: under or over the footage), scaled to the shelf's height, left to right in `deck.shelf.items` order -- nothing covers it there, so it never dodges (`onPosts`, `onChapters`, `x`/`y`, `scale` and `avoid` do not apply), and it is over the finale as the shelf is (`deck.shelf.finale`) | `umtool look <p> deck.shelf=true deck.diet.position=shelf` | @@ -1818,6 +1821,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.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` | @@ -1898,9 +1902,20 @@ The full reference is [The finale](#the-finale-the-timeline-in-primary-view). It | Knob | Range · default | From a terminal | |---|---|---| -| `deck.finale` | `{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims}` | `umtool look <p> deck.finale='{…}'` | +| `deck.finale` | `{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims, dietRuns}` -- `dietRuns`: the whole diet record under the rail ([Diet runs in the finale](#diet-runs-in-the-finale)) | `umtool look <p> deck.finale='{…}'` | | a clip's `layout` | `finale` on one run of clips at the end | `umtool set <p> <clip> layout=finale` | +### Diet runs in the finale + +With `deck.finale.dietRuns: true` (and a measure ledger with a regime track), the finale's timeline panel -- under the large rail's track, the rail's width, down to the panel's foot: with the weight layer (120, 202) 1704×220 at 1080p, the track staying where its labels put it and the timeline taking the room under it (up to `FINALE_SHARE.max`); without it 1704×122 -- carries the WHOLE record of his diets (the measure slice's `record`, diet-record.mjs: every regime row in scope, on camera or not, through the state's own rule): each run a bar in its diet's ink on a time axis from the earliest row; a stretch of more than two years with nothing on record squeezed to a marked break ("2013–2018"), and a run whose end the record does not have fading into it; a row that stopped a diet a grey tick under the bars, one naming the medication (GLP-1) a purple one; his stated weights a light line over the bars, the weights the video marks (`marks`: his heaviest as THE peak) and his low as labelled dots on it; the run still going and the longest ones labelled in two rows under the bars where they fit -- the diet's word (the run's own name when its row gives one: "WEIGHT WATCHERS"), its number when the cut showed it ("DIET #6", the shelf's), its dates and its days, the open one "N days and counting" to the in-record date. It sweeps in left to right over 2.6 s after the finale's grow, each label as the sweep reaches it, then holds; it stands clear of the side video, the lower column's instruments and the promise clock. It needs `deck.finale.railLabels` `sections` or `none` (the pips' labels and dates use that space) and at least 100 px under the rail. + +| Knob | Range · default | From a terminal | +|---|---|---| +| `deck.finale.dietRuns` | `true` · `false` · `{weights, marks, low}` · default `false` | `umtool look <p> deck.finale.dietRuns=true` | +| `deck.finale.dietRuns.weights` | `applied` · `said` · `false` · default `applied`: the WEIGHT LAYER over the bars on the dial's scale (the panel 218 design px, the finale's timeline taking that room under the track) -- every weight he gave (a `current` or `past` row with a number) at the day it APPLIED (its asOf, else its date; `said`: the day he said it). Given at the time: solid, joined -- his claimed trajectory (a bound like "over 240" is a point, not joined). Told 30 days or more after it applied: hollow, with a thin leader to a tick at the day he said it, so a retold weight piles up at one period from its tellings. `>`/`<` a caret, `≈` a ring, a range a bar. A loss or gain (`delta`) and "N over" (`overweight_by`) name no weight the ledger resolves: left out (the record counts them, `record.leftOut`). `false`: the light line of his stated weights alone | `umtool look <p> deck.finale.dietRuns='{"weights":"said"}'` | +| `deck.finale.dietRuns.marks` | up to 8 `{row, label, peak?}`: a dot on the weight line at the row's day (its asOf, else its date) and value, the label -- his words, at most 60 characters -- and the month beside it; THE peak (the one marked `peak`, else the heaviest marked) a size up in the needle's red. A row the ledger lacks is left out | `umtool look <p> deck.finale.dietRuns='{"marks":[{"row":"w21","label":"his heaviest · \"almost 400\""}]}'` | +| `deck.finale.dietRuns.low` | `true` · `false` · its label · default `true`: the lowest weight he stated (never a bound like "over 240"; of one weigh-in told twice the same day, the fuller: 291.5 over "291.") marked in the accent, "his low · 291.5" | `umtool look <p> deck.finale.dietRuns='{"low":false}'` | + ### Dial finale With the dial on (`deck.dial`) and a finale (a run of `layout: "finale"` clips), the finale's lower column -- beside the clip, under the finale's totals when it draws them -- carries the instruments large over the finale's window: in over the finale's grow, the needle dropping (1.8 s, `back.out`) from his highest remembered weight (the measure's `totals.peakDrift` and remembered weights) to his last stated one (`totals.net.to`), every ghost tick and the latest goal on the bezel; the odometer rolling up from zero to the whole record's `totals.lost` (the rows the cut never shows included) with `ACROSS N RUNS`; NET (`totals.net`) held beside it; out through the finale's dissolve. Laid over the finale (z 95), in Play too. It needs the lower column clear: a finale with stats cards (`deck.finale.stats`) is refused -- set `deck.dial.finale` false, or drop the cards. 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/e2e/play-measure.spec.ts b/umtool/e2e/play-measure.spec.ts @@ -150,3 +150,51 @@ test("on the shelf: the footage at the frame's top, the diet's dated tags and th await put(before); } }); + +test("the fan: the diet's tags overlapped with the day count on the front one, the goals' fan beside them on the shelf", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const enc = encodeURIComponent; + const read = async () => (await (await request.get(`/api/report/chrome?project=${enc(PROJECT)}`)).json()) as { chrome: Record<string, any>; token: string }; + const put = async (chrome: unknown) => { + const { token } = await read(); + const r = await request.put("/api/report/chrome", { data: { project: PROJECT, chrome, token } }); + expect(r.ok(), await r.text()).toBeTruthy(); + }; + const before = (await read()).chrome; + const deck = before.deck ?? {}; + try { + await put({ + ...before, + deck: { + ...deck, shelf: { items: ["diet", "goals"] }, streak: false, + diet: { ...(deck.diet ?? {}), position: "shelf", overlap: 0.6, days: true }, + goals: { ...(deck.goals ?? {}), position: "shelf" }, + }, + }); + await page.goto(urls.playHref(PROJECT, { clip: "c04", at: 1 })); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + for (const id of ["diet", "goals"]) { + await expect(page.getByTestId(`play-layer-${id}`)).toHaveAttribute("data-feed-ready", "1", { timeout: 30_000 }); + expect(await page.getByTestId(`play-layer-${id}`).evaluate((el) => parseFloat((el as HTMLElement).style.top))).toBeCloseTo((750 / 1080) * 100, 1); + } + await expect(page.locator('[data-play-layer="streak"]')).toHaveCount(0); + const diet = page.frameLocator('[data-testid="play-layer-diet-iframe"]').locator("#pn"); + // The front tag (carnivore, c03) with its running day count; keto behind it, still carnivore-free of a dim. + await expect.poll(() => diet.evaluate((pn) => { + const on = [...pn.querySelectorAll<HTMLElement>(".tg")].filter((e) => getComputedStyle(e).visibility !== "hidden" && Number(getComputedStyle(e).opacity) > 0.5) + .sort((a, b) => a.getBoundingClientRect().left - b.getBoundingClientRect().left); + return on.map((e) => (e.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 9)); + }), { timeout: 10_000 }).toEqual([expect.stringContaining("Carnivore"), expect.stringContaining("Keto")]); + const days = await diet.evaluate((pn) => [...pn.querySelectorAll<HTMLElement>(".dy")].filter((e) => getComputedStyle(e).visibility !== "hidden").map((e) => (e.textContent ?? "").trim())); + expect(days).toHaveLength(1); + expect(days[0]).toMatch(/^\d+days?$/); + const goals = page.frameLocator('[data-testid="play-layer-goals-iframe"]').locator("#pn"); + await expect.poll(() => goals.evaluate((pn) => { + const st = [...pn.querySelectorAll<HTMLElement>(".st")].find((e) => getComputedStyle(e).visibility !== "hidden"); + return st ? (st.querySelector(".gc")?.textContent ?? "").replace(/\s+/g, " ").trim() : null; + }), { timeout: 10_000 }).toBe("3goals set"); + await page.screenshot({ path: test.info().outputPath("play-measure-fan.png") }); + } finally { + await put(before); + } +}); 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/lib/report/serve.mjs b/umtool/lib/report/serve.mjs @@ -982,7 +982,7 @@ export function previewDirFor(projectDir, variant, rest, segmentIds) { // (Every module that declares `play` must be here, or Play's iframe of its page is a 404: the measure // extras and the instruments too -- the dial's finale is a window its module names `dial-finale-preview`, // never confused with the dial's `dial-preview-<segment>`.) -export const LAYER_REGIONS = Object.freeze(["pair", "status", "chapter", "stats", "threads", "flips", "fx", "shelf", "diet", "peak", "goals", "promise", "streak", "dial", "odometer", "trail", "dial-finale"]); +export const LAYER_REGIONS = Object.freeze(["pair", "status", "chapter", "stats", "threads", "flips", "fx", "shelf", "diet", "peak", "goals", "promise", "streak", "dial", "odometer", "trail", "dial-finale", "runs-finale"]); /** The project name a layer preview is served under, or null when `head` is not one. */ export function layerPreviewOf(head, segmentIds = []) { diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs @@ -16,10 +16,10 @@ 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, dietStates, goalStates, measureBox, measureExtraGeometry, measureOf, MEASURE_BOXES, promiseStripRect, promiseStripType, + daysBetween, daysLeftText, daysText, DIET_TAG, dietDays, dietStates, dietTagStep, goalStates, 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 { MEASURE_RED, resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; +import { dietTagWidth, MEASURE_RED, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs"; import { dialFinaleGeometry, dialFinaleHandoff } from "./chrome-instruments.mjs"; /** How each module's panel comes in and goes out, s. */ @@ -30,7 +30,10 @@ const feedOf = (schedule) => schedule?.layout === "feed"; /** The page's frame: its region, its pixel scale against its design box, its fps. */ function frameOf(id, schedule, render) { const geo = measureExtraGeometry(id, render, { feed: feedOf(schedule) }); - const k = geo.width / measureBox(id, render).width; + // On the shelf a module is scaled to the shelf's HEIGHT: its slot may be wider than its box (the goals' fan + // takes the width left over) and is never narrower. + const box = measureBox(id, render); + const k = resolveMeasureExtra(id, render)?.position === SHELF_POSITION ? geo.height / box.height : geo.width / box.width; const px = (v) => Math.max(1, Math.round(v * k)); return { geo, k, px, fps: schedule.fps ?? render.fps ?? 30 }; } @@ -191,6 +194,7 @@ export function goalsHtml(schedule, render, opts = {}) { const m = measureOf(schedule); const states = goalStates(schedule, render); if (!cfg || !m || !states.length) throw new Error("goals: the schedule's measure slice has no goal on camera"); + if (cfg.position === SHELF_POSITION) return goalsShelfHtml(schedule, render, opts, cfg, states); const F = frameOf("goals", schedule, render); const { geo, px } = F; const H = geo.height; @@ -268,6 +272,131 @@ export function goalsHtml(schedule, render, opts = {}) { return { html: page("goals", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items }; } +/** + * The goal stack ON THE SHELF (`goals.position: "shelf"`): the count of goals + * set in a column at the left, then the notes -- the same paper, tape, shadow + * and ink as the pile in the footage -- fanned sideways like the diet's tags, + * the newest in front landing from above (the pile's own landing), the older + * ones a place to the right behind it, each showing its goal's words in the + * strip beside the one in front (all of each when the slot is wide enough: + * shelfLayout gives the fan the shelf's spare width). A block per state, as the + * pile's: a repeat comes to the front with its count; the number of goals set + * pops at each. + */ +function goalsShelfHtml(schedule, render, opts, cfg, states) { + const F = frameOf("goals", schedule, render); + const { geo, px } = F; + const pal = render.palette; + const paper = cfg.color ?? pal.amber ?? "#E8A33F"; + const G = GOALS_SHELF; + const max = cfg.max ?? 4; + const room = geo.width / F.k - G.count - G.gap - G.card; + const step = max > 1 ? Math.max(G.back, Math.min(G.card + G.step, room / (max - 1))) : 0; + const backs = step < G.card; + const place = (note, depth) => ({ + x: px(G.count + G.gap + depth * step), + y: Math.round(px(6) + note.dx * 0.15 * F.k + (depth ? px(1) : 0)), + rotation: r4(note.rot * 0.45 + (depth ? (depth % 2 ? -1.4 : 1.2) : 0)), + }); + 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 }; + }); + const { init, cues } = stateCues(shelfStates, spans, { + own: (st, j, init) => { + const ev = []; + for (const n of st.notes) { + const k = `s${j}.${n.id}`; + const to = place(n, n.depth); + if (n.key === st.top) { + // The pile's landing: from above, turned, a size up -- onto the fan. + init[k] = { x: to.x - px(30), y: to.y - px(140), rotation: r4(to.rotation + 13), scale: 1.12, opacity: 0 }; + ev.push({ k, at: st.at, dur: 0.42, to: { x: to.x, y: to.y, rotation: to.rotation, scale: 1, opacity: 1 }, ease: "back.out(1.3)" }); + } else if (n.prev !== null && n.prev !== n.depth) { + const from = place(n, n.prev); + init[k] = { x: from.x, y: from.y, rotation: from.rotation }; + ev.push({ k, at: st.at, dur: 0.36, to: { x: to.x, y: to.y, rotation: to.rotation }, ease: "power2.out" }); + // Out of the front: its whole face gives way to the strip that shows beside the new one. + if (backs && n.prev === 0 && n.depth > 0) { + init[`${k}f`] = { opacity: 1 }; + init[`${k}b`] = { opacity: 0 }; + ev.push({ k: `${k}f`, at: st.at, dur: 0.3, to: { opacity: 0 }, ease: "power1.out" }); + ev.push({ k: `${k}b`, at: st.at + 0.1, dur: 0.3, to: { opacity: 1 }, ease: "power1.out" }); + } + } else { + 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)" }); + return ev; + }, + }); + const blocks = shelfStates.map((st, j) => { + const notes = st.notes.map((n) => { + const k = `s${j}.${n.id}`; + const dl = cfg.countdown && n.deadline + ? `<div class="dl">${esc(n.deadline)}${n.days !== null ? ` · ${esc(daysLeftText(n.days))}` : ""}${n.target !== null ? ` · needs ${esc(weightText(n.target))}` : ""}</div>` + : ""; + const count = n.count > 1 ? `<div class="ct">×${n.count}</div>` : ""; + // The ladder: how many more goals are in force beside the headline one, when the state says. + const more = n.depth === 0 && st.headline && Number.isFinite(st.active) && st.active > 1 ? `<div class="mo">+${st.active - 1} more</div>` : ""; + const front = n.depth === 0 || !backs; + const crossing = backs && n.prev === 0 && n.depth > 0; + const face = `<div class="nf"${crossing ? ` data-k="${k}f"` : ""} style="opacity:${front || crossing ? 1 : 0}"><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${dl}</div>`; + 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>`; + }).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 }); + return html; + }); + const css = ` + #pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + .st { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + .gc { position: absolute; left: 0; top: 0; width: ${px(G.count)}px; height: ${px(G.height)}px; display: flex; flex-direction: column; + align-items: center; justify-content: center; border-radius: ${px(10)}px; background: ${rgba(pal.bg, 0.88)}; } + .gn { font-family: ${DISPLAY}; font-size: ${px(46)}px; line-height: ${px(46)}px; color: ${paper}; font-variant-numeric: tabular-nums; } + .gl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(15)}px; letter-spacing: 0.12em; text-transform: uppercase; + color: ${pal.muted}; text-align: center; } + .note { position: absolute; left: 0; top: 0; width: ${px(G.card)}px; height: ${px(G.height - 12)}px; border-radius: ${px(3)}px; color: #2a1c06; + background: linear-gradient(168deg, ${paper} 0%, ${paper} 62%, ${rgba(paper, 0.86)} 100%); + box-shadow: 0 ${px(8)}px ${px(18)}px rgba(0, 0, 0, 0.45), ${px(-4)}px 0 ${px(10)}px rgba(0, 0, 0, 0.3), 0 ${px(1)}px ${px(2)}px rgba(0, 0, 0, 0.3); } + .tape { position: absolute; left: 50%; top: ${px(-6)}px; width: ${px(70)}px; height: ${px(18)}px; margin-left: ${px(-35)}px; + background: rgba(255, 255, 255, 0.38); transform: rotate(-3deg); } + .nf { position: absolute; inset: 0; padding: ${px(8)}px ${px(14)}px; display: flex; flex-direction: column; justify-content: center; gap: ${px(1)}px; overflow: hidden; } + .nb { position: absolute; right: 0; top: 0; bottom: 0; width: ${px(Math.min(step, G.card) - 14)}px; padding: 0 ${px(6)}px; + display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; } + .nh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; letter-spacing: 0.14em; + text-transform: uppercase; color: rgba(42, 28, 6, 0.62); white-space: nowrap; } + .nt { font-family: ${DISPLAY}; font-size: ${px(40)}px; line-height: ${px(44)}px; white-space: nowrap; letter-spacing: 0.01em; } + .dl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; color: #7d150c; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; } + .bt { font-family: ${DISPLAY}; font-size: ${px(24)}px; line-height: ${px(27)}px; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; } + .bh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(15)}px; letter-spacing: 0.1em; text-transform: uppercase; + 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; } + .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 }; +} + // --------------------------------------------------------------------------- // PEAK: the moving start. // --------------------------------------------------------------------------- @@ -727,7 +856,18 @@ function dietTagsHtml(schedule, render, opts, cfg, states) { const SLIDE = 0.4; const DIM = 0.45; const n = cfg.tags ?? 3; - const slotX = (i) => px(i * (DIET_TAG.width + DIET_TAG.gap)); + const daysOn = cfg.days === true; + const W = dietTagWidth(daysOn); + const overlap = cfg.overlap ?? 0; + // FANNED (`overlap` > 0): the goal stack's look turned on its side -- each tag its own small turn and drop, + // the depth's tilt, the stack's shadow; the newest lands on top from above (the goal note's landing), the + // older ones slide a place right behind it and show their regime word and date in the strip beside it. They + // keep their colours: the depth is the overlap and the shadow. Side by side (0): the row, the slam and the dim. + const fan = overlap > 0; + const step = dietTagStep(overlap, daysOn); + const slotX = (i) => px(i * step); + const rotOf = (id, i) => (fan ? r4(jitter(`diet${id}`) * 1.8 + (i ? (i % 2 ? -1.6 : 1.3) : 0)) : 0); + const yOf = (id, i) => (fan ? Math.round(px(2) + jitter(`diet${id}`, 7) * px(2) + (i ? px(1) : 0)) : 0); const spans = upSpans(states.map((s) => s.at), cfg, schedule); const init = { pn: { autoAlpha: 0 } }; const ev = []; @@ -737,10 +877,11 @@ function dietTagsHtml(schedule, render, opts, cfg, states) { states.forEach((st) => { for (const t of st.tags) if (!tags.has(t.id)) tags.set(t.id, t); }); for (const id of tags.keys()) { const k = `t${id}`; - init[k] = { x: 0, autoAlpha: 0 }; + init[k] = { x: 0, y: yOf(id, 0), rotation: rotOf(id, 0), scale: 1, autoAlpha: 0 }; init[`${k}.d`] = { opacity: 1 }; init[`${k}.w`] = { x: 0 }; - init[`${k}.s`] = { scale: 1, rotation: -3, opacity: 1 }; + init[`${k}.s`] = { scale: 1, rotation: fan ? 0 : -3, opacity: 1 }; + if (fan) { init[`${k}.f`] = { opacity: 1 }; init[`${k}.b`] = { opacity: 0 }; } } states.forEach((st, j) => { const prev = j ? states[j - 1].tags.map((t) => t.id) : []; @@ -749,23 +890,37 @@ function dietTagsHtml(schedule, render, opts, cfg, states) { const front = cur[0]; if (!prev.includes(front)) { const k = `t${front}`; - ev.push({ k, at, dur: INSTANT, to: { x: 0, autoAlpha: 1 }, ease: "none" }); - if (st.slam) { - // The slam: in from big and turned, hard onto the shelf, then a shake. - init[`${k}.s`] = { scale: 2.3, rotation: -15, opacity: 0 }; - ev.push({ k: `${k}.s`, at, dur: SLAM, to: { scale: 1, rotation: -3, opacity: 1 }, ease: "power4.in" }); - [8, -6, 4, -2, 0].map((v) => Math.round(v * F.k)).forEach((x, m) => ev.push({ k: `${k}.w`, at: at + SLAM + m * 0.045, dur: 0.045, to: { x }, ease: "sine.inOut" })); + if (fan && !st.replaced && st.diet) { + // The goal note's landing: from above, turned, a size up -- onto the stack. + init[k] = { x: -px(30), y: yOf(front, 0) - px(140), rotation: r4(rotOf(front, 0) + 13), scale: 1.12, autoAlpha: 0 }; + ev.push({ k, at, dur: 0.42, to: { x: 0, y: yOf(front, 0), rotation: rotOf(front, 0), scale: 1, autoAlpha: 1 }, ease: "back.out(1.3)" }); } else { - init[`${k}.s`] = { scale: 1, rotation: -3, opacity: 0 }; - ev.push({ k: `${k}.s`, at, dur: 0.3, to: { opacity: 1 }, ease: "power1.out" }); + ev.push({ k, at, dur: INSTANT, to: { x: 0, autoAlpha: 1 }, ease: "none" }); + if (st.slam && !fan) { + // The slam: in from big and turned, hard onto the shelf, then a shake. + init[`${k}.s`] = { scale: 2.3, rotation: -15, opacity: 0 }; + ev.push({ k: `${k}.s`, at, dur: SLAM, to: { scale: 1, rotation: -3, opacity: 1 }, ease: "power4.in" }); + [8, -6, 4, -2, 0].map((v) => Math.round(v * F.k)).forEach((x, m) => ev.push({ k: `${k}.w`, at: at + SLAM + m * 0.045, dur: 0.045, to: { x }, ease: "sine.inOut" })); + } else { + init[`${k}.s`] = { scale: 1, rotation: fan ? 0 : -3, opacity: 0 }; + ev.push({ k: `${k}.s`, at, dur: 0.3, to: { opacity: 1 }, ease: "power1.out" }); + } } } - // The older ones a place to the right, dimmed. + // The older ones a place to the right: dimmed in the row; in the fan, behind the new one, its strip showing. cur.forEach((id, i) => { const p = prev.indexOf(id); if (p < 0 || p === i) return; - ev.push({ k: `t${id}`, at, dur: SLIDE, to: { x: slotX(i) }, ease: "power2.inOut" }); - ev.push({ k: `t${id}.d`, at, dur: SLIDE, to: { opacity: i === 0 ? 1 : DIM }, ease: "power1.out" }); + if (fan) { + ev.push({ k: `t${id}`, at, dur: 0.36, to: { x: slotX(i), y: yOf(id, i), rotation: rotOf(id, i) }, ease: "power2.out" }); + if (p === 0) { + ev.push({ k: `t${id}.f`, at, dur: 0.3, to: { opacity: 0 }, ease: "power1.out" }); + ev.push({ k: `t${id}.b`, at: at + 0.1, dur: 0.3, to: { opacity: 1 }, ease: "power1.out" }); + } + } else { + ev.push({ k: `t${id}`, at, dur: SLIDE, to: { x: slotX(i) }, ease: "power2.inOut" }); + ev.push({ k: `t${id}.d`, at, dur: SLIDE, to: { opacity: i === 0 ? 1 : DIM }, ease: "power1.out" }); + } }); // Off the row: the one replaced by new words fades where it stands; the one past `tags` slides off. for (const id of prev) { @@ -774,6 +929,34 @@ function dietTagsHtml(schedule, render, opts, cfg, states) { else ev.push({ k: `t${id}`, at, dur: SLIDE, to: { x: slotX(n), autoAlpha: 0 }, ease: "power2.in" }); } }); + // THE RUNNING DAY COUNT (`days`): on the front tag, the days on its diet to the in-record date at the playhead + // (dietDays), a number per stretch it holds -- cut wherever the count or the front tag changes. + const dayBlocks = new Map(); + if (daysOn) { + const counts = dietDays(schedule, render); + const cuts = [...new Set([...counts.map((c) => c.at), ...states.map((s) => s.at)])].sort((a, b) => a - b); + const end = Number(schedule.total) || 0; + const valueAt = (list, t) => { let v = null; for (const x of list) { if (x.at <= t + 1e-6) v = x; else break; } return v; }; + const runs = []; + cuts.forEach((t, i) => { + const st = valueAt(states, t); + const c = valueAt(counts, t); + const card = st?.diet && c && c.days !== null ? st.tags[0].id : null; + const days = card === null ? null : c.days; + const last = runs[runs.length - 1]; + const to = cuts[i + 1] ?? end; + if (last && last.card === card && last.days === days) { last.to = to; return; } + runs.push({ from: t, to, card, days }); + }); + runs.filter((r) => r.card !== null).forEach((r, m) => { + const k = `t${r.card}.y${m}`; + init[k] = { autoAlpha: 0 }; + ev.push({ k, at: r.from, dur: INSTANT, to: { autoAlpha: 1 }, ease: "none" }); + if (r.to < end - 1e-6) ev.push({ k, at: r.to, dur: INSTANT, to: { autoAlpha: 0 }, ease: "none" }); + if (!dayBlocks.has(r.card)) dayBlocks.set(r.card, []); + dayBlocks.get(r.card).push(`<div class="dy" data-k="${k}"><div class="dyn">${r.days}</div><div class="dyl">day${r.days === 1 ? "" : "s"}</div></div>`); + }); + } const { cues } = compileCues(init, ev); const items = []; const room = DIET_TAG.width - 44; @@ -788,23 +971,38 @@ function dietTagsHtml(schedule, render, opts, cfg, states) { const sub = d ? `<div class="sb"><span class="dn">Diet${d.n !== null ? ` #${d.n}` : ""}</span>${words ? `<span class="dd">${esc(words)}</span>` : ""}</div>` : `<div class="sb"><span class="dd">he says he is on none</span></div>`; - const html = `<div class="tg" data-k="${k}"><div class="dm" data-k="${k}.d"><div class="sw" data-k="${k}.w"><div class="sp${d ? "" : " off"}" data-k="${k}.s">` + - `<div class="ink" style="color:${ink};border-color:${ink}"><div class="lb" style="font-size:${px(size)}px;line-height:${px(Math.round(size * 1.02))}px">${esc(label)}</div>${sub}` + - `${date ? `<div class="dt">${esc(date)}</div>` : ""}</div></div></div></div></div>`; + const faceBody = `<div class="lb" style="font-size:${px(size)}px;line-height:${px(Math.round(size * 1.02))}px">${esc(label)}</div>${sub}` + + `${date ? `<div class="dt">${esc(date)}</div>` : ""}`; + const face = daysOn ? `<div class="fc">${faceBody}</div><div class="dc">${(dayBlocks.get(t.id) ?? []).join("")}</div>` : faceBody; + // The strip an older tag shows beside the one in front of it: its regime word and its date. + const back = fan + ? `<div class="bk" data-k="${k}.b"><div class="bl" style="font-size:${px(Math.min(32, tagWordSize(label, step - 30)))}px">${esc(label)}</div>${date ? `<div class="bd">${esc(date)}</div>` : ""}</div>` + : ""; + const html = `<div class="tg" data-k="${k}"${fan ? ` style="z-index:${10 + t.id}"` : ""}><div class="dm" data-k="${k}.d"><div class="sw" data-k="${k}.w"><div class="sp${d ? "" : " off"}" data-k="${k}.s">` + + `<div class="ink" style="color:${ink};border-color:${ink}"><div class="fr"${fan ? ` data-k="${k}.f"` : ""}>${face}</div>${back}</div></div></div></div></div>`; items.push({ key: k, gate: [k, "autoAlpha"], html }); return html; }); const css = ` #pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; } - .tg { position: absolute; left: 0; top: 0; width: ${px(DIET_TAG.width)}px; height: ${px(DIET_TAG.height)}px; visibility: hidden; opacity: 0; } + .tg { position: absolute; left: 0; top: 0; width: ${px(W)}px; height: ${px(DIET_TAG.height)}px; visibility: hidden; opacity: 0;${fan ? " transform-origin: 30% 60%;" : ""} } .dm, .sw { position: absolute; inset: 0; } /* A tag: the stamp's plate and pressed ink, small. The plate is solid; only the ink is pressed. */ .sp { position: absolute; left: ${px(4)}px; top: ${px(4)}px; right: ${px(4)}px; bottom: ${px(4)}px; border-radius: ${px(8)}px; - background: ${rgba(pal.bg, 0.93)}; padding: ${px(4)}px; box-shadow: 0 ${px(6)}px ${px(16)}px rgba(0, 0, 0, 0.45); } - .ink { height: 100%; padding: ${px(3)}px ${px(10)}px ${px(4)}px; border: ${px(4)}px solid; border-radius: ${px(6)}px; - box-shadow: inset 0 0 0 ${px(2)}px ${rgba(pal.bg, 0.9)}, inset 0 0 0 ${px(3)}px currentColor; - display: flex; flex-direction: column; align-items: center; justify-content: center; overflow: hidden; + background: ${rgba(pal.bg, fan ? 0.97 : 0.93)}; padding: ${px(4)}px; + box-shadow: ${fan ? `0 ${px(8)}px ${px(18)}px rgba(0, 0, 0, 0.5), ${px(-4)}px 0 ${px(10)}px rgba(0, 0, 0, 0.35)` : `0 ${px(6)}px ${px(16)}px rgba(0, 0, 0, 0.45)`}; } + .ink { position: relative; height: 100%; padding: ${px(3)}px ${px(10)}px ${px(4)}px; border: ${px(4)}px solid; border-radius: ${px(6)}px; + box-shadow: inset 0 0 0 ${px(2)}px ${rgba(pal.bg, 0.9)}, inset 0 0 0 ${px(3)}px currentColor; overflow: hidden; -webkit-mask-image: ${INK}; mask-image: ${INK}; -webkit-mask-size: ${px(240)}px ${px(120)}px; mask-size: ${px(240)}px ${px(120)}px; } + .fr { height: 100%; display: flex; ${daysOn ? "flex-direction: row; align-items: stretch;" : "flex-direction: column; align-items: center; justify-content: center;"} } + .fc { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; } + .dc { position: relative; flex: none; width: ${px(76)}px; margin-left: ${px(6)}px; border-left: ${px(2)}px solid ${rgba(pal.fg, 0.18)}; } + .dy { position: absolute; inset: 0; visibility: hidden; opacity: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; } + .dyn { font-family: ${DISPLAY}; font-size: ${px(40)}px; line-height: ${px(40)}px; font-variant-numeric: tabular-nums; } + .dyl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; letter-spacing: 0.16em; text-transform: uppercase; color: ${pal.fg}; } + .bk { position: absolute; right: 0; top: 0; bottom: 0; width: ${px(step - 20)}px; display: flex; flex-direction: column; align-items: center; justify-content: center; } + .bl { font-family: ${DISPLAY}; text-transform: uppercase; letter-spacing: 0.03em; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; line-height: 1.05; } + .bd { font-family: 'DeckSansBold', sans-serif; font-size: ${px(14)}px; line-height: ${px(18)}px; color: ${pal.fg}; white-space: nowrap; font-variant-numeric: tabular-nums; } .lb { font-family: ${DISPLAY}; text-transform: uppercase; letter-spacing: 0.03em; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; } .sb { display: flex; align-items: baseline; justify-content: center; gap: ${px(8)}px; white-space: nowrap; max-width: 100%; } .dn { flex: none; font-family: 'DeckSansBold', sans-serif; font-size: ${px(14)}px; line-height: ${px(18)}px; letter-spacing: 0.14em; text-transform: uppercase; } diff --git a/umtool/report-to-video/chrome-runs-finale.mjs b/umtool/report-to-video/chrome-runs-finale.mjs @@ -0,0 +1,298 @@ +// THE FINALE'S DETAILED DIET RUNS (module `runs-finale`, `deck.finale.dietRuns`): +// the whole record of his diets drawn large in the finale -- the measure +// slice's `record` (diet-record.mjs), every run from the earliest row a bar in +// its diet's ink along a time axis, a stretch of years with nothing on record +// drawn as a break (compressed, marked), the rows that stopped a diet or named +// the medication as marks under the bars, his stated weights as a light line +// over them; the longest runs (and the one still going) labelled with the +// diet's word, its number when the cut showed it ("DIET #6", the shelf's), its +// dates and its days -- the open one "N days and counting" to the in-record +// date. It stands in the finale's timeline panel under the large rail (clear +// of the side video, the lower column's instruments and the promise clock that +// takes it over), sweeps in left to right over the finale's first seconds, +// then holds. +// +// PURE: a schedule and a render block in, `{ html, items }` out. +import { formatDeckDate } from "./attribution.mjs"; +import { finaleLayout } from "./chrome-finale.mjs"; +import { rgba } from "./chrome-deck.mjs"; +import { compileCues, cuePageHtml, esc, r4 } from "./chrome-cues.mjs"; +import { dietRunsOn, dietRunsWeights, FINALE_MOTION, resolveFinale } from "./finale.mjs"; +import { daysBetween, measureOf, shortDate } from "./measure-extras.mjs"; +import { DIET_COLORS, DIET_LABELS, MEASURE_RED, resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; + +/** A stretch with nothing on record longer than this is drawn as a break, days. */ +export const RUNS_BREAK_DAYS = 730; +/** The motion: in after the finale's grow, swept left to right, s. */ +export const RUNS_MOTION = Object.freeze({ delay: 0.2, sweep: 2.6, label: 0.3 }); +/** The panel's least height (1080p px) under the rail; less, and there is no room. */ +export const RUNS_MIN_HEIGHT = 100; + +const DESIGN = Object.freeze({ top: 5, weights: 34, barY: 36, barH: 18, rowA: 68, rowB: 95, rowH: 27, years: 12, brk: 44 }); +/** With the weight layer (`dietRuns.weights`): every weight he gave over the bars, on the dial's scale. */ +const LAYERED = Object.freeze({ ...DESIGN, top: 6, weights: 110, barY: 118, rowA: 152, rowB: 180 }); + +/** The record the slice carries, when the finale asks for it. */ +export const recordOf = (schedule) => { + const r = measureOf(schedule)?.record; + return r && Array.isArray(r.runs) && r.runs.length ? r : null; +}; + +/** + * Where it stands: the finale's timeline panel under the large rail's track, + * from the rail's left end to its right, down to the panel's foot -- or null + * when that is under RUNS_MIN_HEIGHT. + */ +export function runsFinaleGeometry(schedule, render) { + if (!schedule?.finale) return null; + const L = finaleLayout(schedule, render); + const kh = L.geo.H / 1080; + const y = Math.round(L.rail.track.y + 26 * kh); + const bottom = Math.round(L.rail.bottom - 4 * kh); + if (bottom - y < RUNS_MIN_HEIGHT * kh) return null; + const x = L.rail.track.x0; + const even = (v) => Math.round(v / 2) * 2; + return { x, y, width: even(L.rail.track.x1 - x), height: even(bottom - y) }; +} + +/** The in-record date at the finale: the latest date of anything the cut showed. */ +function recordDate(m) { + const ds = (m.events ?? []).map((e) => e.date).filter(Boolean).sort(); + return ds[ds.length - 1] ?? m.asOfRender ?? null; +} + +/** + * The time axis: dates to px, every stretch with nothing on record longer than + * RUNS_BREAK_DAYS squeezed to `brk` px and marked. `x(date)`, `breaks: [{ x, + * from, to }]`, the years' ticks. + */ +export function runsAxis(dates, width, { brk = DESIGN.brk, pad = 8 } = {}) { + const ds = [...new Set(dates.filter(Boolean))].sort(); + const spans = []; + for (let i = 1; i < ds.length; i += 1) spans.push({ a: ds[i - 1], b: ds[i], days: Math.max(0, daysBetween(ds[i - 1], ds[i]) ?? 0) }); + const broken = spans.filter((s) => s.days > RUNS_BREAK_DAYS); + const linear = spans.filter((s) => s.days <= RUNS_BREAK_DAYS).reduce((n, s) => n + s.days, 0); + const k = Math.max(0.01, (width - 2 * pad - broken.length * brk) / Math.max(1, linear)); + const stops = [{ date: ds[0], x: pad }]; + for (const s of spans) stops.push({ date: s.b, x: stops[stops.length - 1].x + (s.days > RUNS_BREAK_DAYS ? brk : s.days * k), broken: s.days > RUNS_BREAK_DAYS }); + const x = (d) => { + if (!d) return stops[stops.length - 1].x; + if (d <= stops[0].date) return stops[0].x; + for (let i = 1; i < stops.length; i += 1) { + if (d <= stops[i].date) { + const a = stops[i - 1], b = stops[i]; + if (b.broken) return a.x + (d === b.date ? b.x - a.x : Math.min(b.x - a.x, 6)); + return a.x + (daysBetween(a.date, d) ?? 0) * k; + } + } + return stops[stops.length - 1].x + (daysBetween(stops[stops.length - 1].date, d) ?? 0) * k; + }; + const breaks = stops.map((s, i) => (s.broken ? { x: r4((stops[i - 1].x + s.x) / 2), x0: stops[i - 1].x, x1: s.x, from: stops[i - 1].date, to: s.date } : null)).filter(Boolean); + const years = []; + const y0 = Number(String(ds[0]).slice(0, 4)), y1 = Number(String(ds[ds.length - 1]).slice(0, 4)); + for (let y = y0 + 1; y <= y1; y += 1) { + const d = `${y}-01-01`; + if (breaks.some((b) => d > b.from && d < b.to)) continue; + years.push({ year: y, x: r4(x(d)) }); + } + return { x, breaks, years, k }; +} + +/** The finale's detailed diet runs page over the finale's `window`: `{ html, items }`. */ +export function runsFinaleHtml(schedule, render, window, opts = {}) { + const m = measureOf(schedule); + const rec = recordOf(schedule); + const geo = runsFinaleGeometry(schedule, render); + if (!m || !rec || !geo) throw new Error("runs-finale: needs a finale, the measure slice's diet record (render.chrome.deck.finale.dietRuns) and room under the rail"); + const pal = render.palette; + // The weight layer (`dietRuns.weights`): every weight he gave, at the day it applied (or was said). + const layer = dietRunsWeights(resolveFinale(render).dietRuns); + const D = layer ? LAYERED : DESIGN; + const s = (render.width ?? 1920) / 1920; + const px = (v) => Math.max(1, Math.round(v * s)); + const cfg = resolveMeasureExtra("diet", render) ?? resolveMeasureExtra("diet", { chrome: { deck: {} } }); + const colors = { ...DIET_COLORS, ...(cfg?.colors ?? {}) }; + const labels = { ...DIET_LABELS, ...(cfg?.labels ?? {}) }; + const W = geo.width, H = geo.height; + const today = recordDate(m); + const points = Array.isArray(rec.points) ? rec.points : []; + const claims = layer && Array.isArray(rec.claims) ? rec.claims : []; + const dates = [rec.from, ...rec.runs.flatMap((r) => [r.since, r.end]), ...rec.marks.map((x) => x.date), ...rec.weights.map((w) => w.date), ...points.map((p) => p.date), + ...claims.flatMap((c) => [c.applied, c.said]), today].filter(Boolean); + const A = runsAxis(dates, W, { brk: px(D.brk), pad: px(layer ? 34 : 8) }); + // The number the cut gave a diet (the shelf's "DIET #6"): its state's, by regime and since. + const shownN = new Map(); + for (const st of m.state ?? []) if (st?.diet?.since) shownN.set(`${st.diet.regime}|${st.diet.since}`, st.diet.n); + const crossesBreak = (r) => A.breaks.some((b) => r.since <= b.from && (r.end ?? today) >= b.to); + const runs = rec.runs.map((r, i) => { + const end = r.end ?? today; + const x0 = A.x(r.since); + // A run across a break has no record of its end: drawn to the break, fading into it. + const brk = crossesBreak(r) ? A.breaks.find((b) => r.since <= b.from) : null; + const x1 = brk ? brk.x0 + px(4) : A.x(end); + const days = brk ? null : Math.max(0, daysBetween(r.since, end) ?? 0); + const word = (r.name ?? labels[r.key] ?? r.key).toUpperCase(); + const n = shownN.get(`${r.key}|${r.since}`) ?? null; + return { ...r, i, x0: r4(x0), x1: r4(Math.max(x0 + px(3), x1)), days, word, n, open: r.end === null, faded: !!brk, color: colors[r.key] ?? colors.other }; + }); + // THE LABELS: the run still going first, then the longest; each in the first of two rows under the bars where + // it meets no other (its words ~0.56 em a character), at its bar's middle, clamped to the panel. + const fs = px(13); + const est = (t, size, bold = 0.58) => t.length * size * bold; + const rows = [[], []]; + const placed = []; + const order = [...runs].sort((a, b) => (b.open - a.open) || ((b.days ?? 1e6) - (a.days ?? 1e6))); + for (const r of order) { + const l1 = `${r.word}${r.n !== null ? ` · DIET #${r.n}` : ""}`; + const from = formatDeckDate(r.since); + const l2 = r.days === null ? `from ${from}` : r.open ? `${shortDate(r.since, { year: true })} · ${r.days} days and counting` : `${shortDate(r.since, { year: true })} – ${shortDate(r.end, { year: true })} · ${r.days} day${r.days === 1 ? "" : "s"}`; + const w = Math.ceil(Math.max(est(l1, fs, 0.62), est(l2, px(12), 0.55))) + px(6); + if ((r.x1 - r.x0) < px(14) && !r.open) continue; + const mid = (r.x0 + r.x1) / 2; + const lx = Math.max(0, Math.min(W - w, Math.round(r.open ? r.x1 - w : mid - w / 2))); + const row = rows.findIndex((list) => list.every((o) => lx + w + px(10) <= o.x || o.x + o.w + px(10) <= lx)); + if (row < 0) continue; + rows[row].push({ x: lx, w }); + placed.push({ r, row, x: lx, w, l1, l2 }); + } + // THE WEIGHTS. Without the layer: a light line of his stated weights over the bars. With it (`weights`): + // EVERY weight he gave on the dial's scale -- at the day it applied ("applied") or was said ("said") -- the ones + // he gave at the time solid and joined (his claimed trajectory; a bound is no reading, so not joined), the ones told later hollow with a thin leader + // down to the day he said it, so a retold peak piles up at one period from its tellings; a bound (">") a caret + // over its point, an "about" (≈) a ring round it, a range a bar. + const ws = rec.weights.filter((w) => w.date); + const scale = m.scale ?? {}; + const vals = layer ? [...claims.map((c) => c.value), ...points.map((p) => p.value)] : [...ws.map((w) => w.value), ...points.map((p) => p.value)]; + const lo = layer ? Math.min(Number.isFinite(scale.min) ? scale.min : Infinity, ...vals) : Math.min(...vals); + const hi = layer ? Math.max(Number.isFinite(scale.max) ? scale.max : -Infinity, ...vals) : Math.max(...vals); + const wy = (v) => r4(px(D.top) + (hi > lo ? (hi - v) / (hi - lo) : 0.5) * px(D.weights - D.top - 4)); + const xOfClaim = (c) => r4(A.x(layer === "said" ? c.said : c.applied)); + const line = layer + ? claims.filter((c) => !c.retold && !["<", ">"].includes(c.qualifier)).map((c) => [xOfClaim(c), wy(c.value)]) + : ws.map((w) => [r4(A.x(w.date)), wy(w.value)]); + const pts = line; + const segs = []; + for (let i = 1; i < pts.length; i += 1) { + const broken = A.breaks.some((b) => pts[i - 1][0] <= b.x0 + 1 && pts[i][0] >= b.x1 - 1); + if (!broken) segs.push(`M${pts[i - 1][0]},${pts[i - 1][1]}L${pts[i][0]},${pts[i][1]}`); + } + const axisY = px(D.barY + D.barH + 1); + const grid = layer + ? [250, 300, 350, 400].filter((v) => v >= lo && v <= hi).map((v) => `<div class="gl" style="top:${wy(v)}px"></div><div class="gv" style="top:${r4(wy(v) - px(7))}px">${v}</div>`).join("") + : ""; + const claimSvg = layer + ? claims.map((c) => { + const x = xOfClaim(c); + const y = wy(c.value); + const leader = c.retold && layer === "applied" ? `<path d="M${x},${y}L${r4(A.x(c.said))},${axisY}" class="ldr"/><path d="M${r4(A.x(c.said))},${axisY - px(4)}V${axisY + px(3)}" class="said"/>` : ""; + const range = c.range ? `<path d="M${x},${wy(Math.max(...c.range))}V${wy(Math.min(...c.range))}" class="rg"/>` : ""; + const dot = c.retold ? `<circle cx="${x}" cy="${y}" r="${px(3.2)}" class="hol"/>` : `<circle cx="${x}" cy="${y}" r="${px(2.8)}" class="sol"/>`; + const q = c.qualifier === "≈" ? `<circle cx="${x}" cy="${y}" r="${px(6)}" class="apx"/>` + : c.qualifier === ">" ? `<path d="M${r4(x - px(4))},${r4(y - px(5))}L${x},${r4(y - px(9))}L${r4(x + px(4))},${r4(y - px(5))}" class="car"/>` + : c.qualifier === "<" ? `<path d="M${r4(x - px(4))},${r4(y + px(5))}L${x},${r4(y + px(9))}L${r4(x + px(4))},${r4(y + px(5))}" class="car"/>` : ""; + return `${leader}${range}${dot}${q}`; + }).join("") + : ""; + // The motion: the panel sweeps open left to right, each label coming in as the sweep reaches it. + const fps = schedule.fps ?? render.fps ?? 30; + const from = r4(Number(window.from)); + const dur = r4(Number(window.to) - from); + if (!(dur > 0)) throw new Error("runs-finale: the window is empty"); + const t0 = from + FINALE_MOTION.grow + RUNS_MOTION.delay; + const init = { rv: { width: 0 }, pn: { autoAlpha: 0 } }; + const ev = [ + { k: "pn", at: t0 - 0.1, dur: 0.25, to: { autoAlpha: 1 }, ease: "power1.out" }, + { k: "rv", at: t0, dur: RUNS_MOTION.sweep, to: { width: W }, ease: "none" }, + ]; + const items = []; + // THE MARKED WEIGHTS (`dietRuns.marks`, the low): a dot at the day it was his weight, his words and the month + // beside it -- THE peak in the needle's red, a size up; the low in the accent. + const pointHtml = points.map((p, j) => { + const key = `p${j}`; + const x = r4(A.x(p.date)); + const y = wy(p.value); + const text = `${p.label}${p.label ? " · " : ""}${shortDate(p.date, { year: true }).replace(/^\d+ /, "")}`; + const w = Math.ceil(text.length * px(p.kind === "peak" ? 13 : 12) * 0.56) + px(12); + const left = x + px(10) + w <= W ? x + px(10) : x - px(10) - w; + const top = Math.max(0, Math.min(px(D.weights) - px(14), Math.round(y - px(8)))); + init[key] = { autoAlpha: 0 }; + ev.push({ k: key, at: t0 + RUNS_MOTION.sweep * Math.min(1, x / W), dur: RUNS_MOTION.label, to: { autoAlpha: 1 }, ease: "power1.out" }); + const html = `<div class="pt ${p.kind}" data-k="${key}"><div class="pd" style="left:${x}px;top:${y}px"></div>` + + `<div class="pl" style="left:${r4(left)}px;top:${top}px;width:${w}px;${left < x ? "text-align:right;" : ""}"><span>${esc(text)}</span></div></div>`; + items.push({ key, gate: [key, "autoAlpha"], html }); + return html; + }); + const labelHtml = placed.map((p, j) => { + const key = `l${j}`; + init[key] = { autoAlpha: 0 }; + const at = t0 + RUNS_MOTION.sweep * Math.min(1, (p.r.x0 + p.r.x1) / 2 / W); + ev.push({ k: key, at, dur: RUNS_MOTION.label, to: { autoAlpha: 1 }, ease: "power1.out" }); + const top = px(p.row ? D.rowB : D.rowA); + const lead = Math.round((p.r.x0 + p.r.x1) / 2); + const html = `<div class="lb" data-k="${key}"><div class="ld" style="left:${lead}px;top:${px(D.barY + D.barH)}px;height:${top - px(D.barY + D.barH)}px;background:${p.r.color}"></div>` + + `<div class="lt" style="left:${p.x}px;top:${top}px;width:${p.w}px;${p.x + p.w >= W - 1 ? "text-align:right;" : ""}"><div class="l1" style="color:${p.r.color}">${esc(p.l1)}</div><div class="l2">${esc(p.l2)}</div></div></div>`; + items.push({ key, gate: [key, "autoAlpha"], html }); + return html; + }); + const bars = runs.map((r) => `<div class="bar${r.faded ? " fd" : ""}${r.open ? " op" : ""}" style="left:${r.x0}px;width:${r4(r.x1 - r.x0)}px;--c:${r.color}"></div>`).join(""); + const marks = rec.marks.map((x) => `<div class="mk ${x.kind}" style="left:${r4(A.x(x.date))}px"></div>`).join(""); + const years = A.years.map((y) => `<div class="yt" style="left:${y.x}px"></div><div class="yl" style="left:${r4(y.x + px(3))}px">${y.year}</div>`).join(""); + const breaks = A.breaks.map((b) => `<div class="bk" style="left:${r4(b.x0)}px;width:${r4(b.x1 - b.x0)}px"><span>${esc(String(b.from).slice(0, 4))}–${esc(String(b.to).slice(0, 4))}</span></div>`).join(""); + const css = ` + #pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + #rv { position: absolute; left: 0; top: 0; height: ${H}px; overflow: hidden; } + #rw { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; } + .bar { position: absolute; top: ${px(D.barY)}px; height: ${px(D.barH)}px; background: var(--c); border-radius: ${px(2)}px; + box-shadow: inset 0 ${px(-3)}px 0 rgba(0, 0, 0, 0.18); } + .bar.fd { background: linear-gradient(90deg, var(--c) 0%, var(--c) 55%, transparent 100%); } + .bar.op { box-shadow: 0 0 ${px(10)}px var(--c); } + .ax { position: absolute; left: 0; width: ${W}px; top: ${px(D.barY + D.barH + 1)}px; height: ${px(2)}px; background: ${pal.muted}; opacity: 0.45; } + .mk { position: absolute; top: ${px(D.barY + D.barH + 2)}px; width: ${px(2)}px; height: ${px(6)}px; margin-left: ${px(-1)}px; background: ${pal.muted}; } + .mk.med { background: ${colors.glp1 ?? "#B168C6"}; height: ${px(8)}px; } + .bk { position: absolute; top: ${px(D.barY - 4)}px; height: ${px(D.barH + 10)}px; display: flex; align-items: center; justify-content: center; + background: repeating-linear-gradient(115deg, transparent 0 ${px(5)}px, ${pal.muted}55 ${px(5)}px ${px(7)}px); } + .bk span { font-family: 'DeckSansBold', sans-serif; font-size: ${px(10)}px; color: ${pal.fg}; background: ${pal.bg}; padding: 0 ${px(3)}px; white-space: nowrap; } + .yt { position: absolute; top: ${px(D.barY - 4)}px; width: 1px; height: ${px(D.barH + 8)}px; background: ${pal.muted}; opacity: 0.5; } + .yl { position: absolute; top: ${px(D.barY + D.barH + 4)}px; font-size: ${px(D.years)}px; line-height: ${px(14)}px; color: ${pal.muted}; } + svg.wt { position: absolute; left: 0; top: 0; overflow: visible; } + svg.wt .sol { fill: ${pal.fg}; } + svg.wt .hol { fill: ${pal.bg}; stroke: ${pal.fg}; stroke-opacity: 0.75; stroke-width: ${px(1.5)}; } + svg.wt .apx { fill: none; stroke: ${pal.amber ?? pal.fg}; stroke-opacity: 0.8; stroke-width: ${px(1)}; } + svg.wt .car { fill: none; stroke: ${pal.amber ?? pal.fg}; stroke-width: ${px(1.5)}; } + svg.wt .ldr { stroke: ${pal.fg}; stroke-opacity: 0.22; stroke-width: ${px(1)}; fill: none; } + svg.wt .said { stroke: ${pal.fg}; stroke-opacity: 0.6; stroke-width: ${px(1.5)}; } + svg.wt .rg { stroke: ${pal.fg}; stroke-opacity: 0.6; stroke-width: ${px(2)}; } + .gl { position: absolute; left: ${px(30)}px; right: 0; height: 1px; background: ${pal.muted}; opacity: 0.18; } + .gv { position: absolute; left: 0; width: ${px(26)}px; text-align: right; font-size: ${px(11)}px; line-height: ${px(14)}px; color: ${pal.muted}; } + .pt { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + .pd { position: absolute; width: ${px(7)}px; height: ${px(7)}px; margin: ${px(-3.5)}px 0 0 ${px(-3.5)}px; border-radius: 50%; background: ${pal.fg}; + box-shadow: 0 0 0 ${px(2)}px ${pal.bg}; } + .pl { position: absolute; white-space: nowrap; font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(14)}px; color: ${pal.fg}; } + .pl span { background: ${rgba(pal.bg, 0.85)}; padding: 0 ${px(3)}px; border-radius: ${px(3)}px; } + .peak .pd { width: ${px(11)}px; height: ${px(11)}px; margin: ${px(-5.5)}px 0 0 ${px(-5.5)}px; background: ${MEASURE_RED}; box-shadow: 0 0 0 ${px(2)}px ${pal.bg}, 0 0 ${px(10)}px ${MEASURE_RED}; } + .peak .pl { font-size: ${px(13)}px; color: ${MEASURE_RED}; } + .low .pd { background: ${pal.accent}; } + .low .pl { color: ${pal.accent}; } + .lb { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + .ld { position: absolute; width: ${px(2)}px; margin-left: ${px(-1)}px; opacity: 0.7; } + .lt { position: absolute; white-space: nowrap; } + .l1 { font-family: 'DeckSansBold', sans-serif; font-size: ${fs}px; line-height: ${px(14)}px; letter-spacing: 0.06em; text-transform: uppercase; } + .l2 { font-size: ${px(12)}px; line-height: ${px(14)}px; color: ${pal.fg}; font-variant-numeric: tabular-nums; } +`; + const body = `<div id="pn" data-k="pn"> + <div id="rv" data-k="rv"><div id="rw"> + ${grid}<svg class="wt" width="${W}" height="${H}"><path d="${segs.join("")}" fill="none" stroke="${pal.fg}" stroke-opacity="${layer ? 0.7 : 0.45}" stroke-width="${px(2)}"/>${layer ? claimSvg : pts.map(([x, y]) => `<circle cx="${x}" cy="${y}" r="${px(2)}" fill="${pal.fg}" fill-opacity="0.7"/>`).join("")}</svg> + ${years}<div class="ax"></div>${bars}${marks}${breaks} + </div></div> + ${labelHtml.join("\n ")} + ${pointHtml.join("\n ")} + </div>`; + const { cues } = compileCues(init, ev); + return { + html: cuePageHtml({ id: "runs-finale", W, H, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css, body, init, cues, window: { from, dur } }), + items, + }; +} + +/** Is the detailed finale asked for (`deck.finale.dietRuns`)? */ +export const runsFinaleWanted = (render) => dietRunsOn(resolveFinale(render).dietRuns); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -58,7 +58,7 @@ import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStat import { fxOn, fxSchedule, validateFx } from "./fx.mjs"; import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs"; import { - aboveTop, FINALE_MOTION, FINALE_SHARE, finaleClaims, finaleClaimSlots, finaleGeometry, finaleRunOf, finaleRunProblems, + aboveTop, dietRunsPanel, FINALE_MOTION, FINALE_SHARE, finaleClaims, finaleClaimSlots, finaleGeometry, finaleRunOf, finaleRunProblems, railLabelLayout, railMarkerLayout, resolveFinale, textWidth as finaleTextWidth, validateFinaleSettings, } from "./finale.mjs"; import { @@ -2071,12 +2071,18 @@ function finaleRailAt(schedule, render, railBottom, textScale) { if (typeof f.timelineShare === "number") B = Math.round(H * f.timelineShare) - py(36); else B = Math.max(rail.bottom, Math.min(Math.round(H * FINALE_SHARE.auto) - py(36), want)); } + // The finale's diet record (`dietRuns`, chrome-runs-finale.mjs) stands under the track: the track stays where + // its labels put it, and ("auto") the timeline takes the room the record needs under it, up to FINALE_SHARE.max. + const runsPanel = dietRunsPanel(f.dietRuns); + if (runsPanel && !Number.isFinite(railBottom) && typeof f.timelineShare !== "number") { + B = Math.max(B, Math.min(Math.round(H * FINALE_SHARE.max) - py(36), Yneed + py(26 + runsPanel + 6))); + } const geo = B === rail.bottom ? base : geoAt(B); // The labels again, cut to the room under the track; the track moves down // by half of what they leave. labels = labelsAt(xs, { ...geo, rail: { ...geo.rail, y: Yneed } }); const low = lowOf(labels, Yneed, false); - const Y = Yneed + Math.max(0, Math.floor((B - low) / 2)); + const Y = runsPanel ? Yneed : Yneed + Math.max(0, Math.floor((B - low) / 2)); return { geo, x0, xs, pips, labels, marks, claims, Y, railBottom: B, want, textScale, lay, fxs, pipped, bigSize, bigV, footSize }; } diff --git a/umtool/report-to-video/diet-record.mjs b/umtool/report-to-video/diet-record.mjs @@ -0,0 +1,156 @@ +// THE DIET RECORD (the finale's detailed diet runs, `deck.finale.dietRuns`): +// the WHOLE record of his diets in scope -- every regime row, on camera or +// not, from the earliest -- as RUNS, with the rows that stopped one or named a +// medication as marks, and his stated weights along it. measure-slice.mjs +// writes it into the slice as `record` only when the finale asks for it, so a +// cut without it writes the slice it always did; chrome-runs-finale.mjs draws it. +// +// The runs follow the state's own rule (panel-model.mjs nextRegime: "on" keeps +// when a regime opened, "start" opens it again, an "off" closes only what it +// names; the track's off key is no diet): a new run at each change of regime, +// numbered as the state numbers its diets. A run is named by its opening row's +// own words when they name it otherwise ("Weight Watchers" for `calories`). +// +// Pure: rows and the schema in, plain data out. +import { chronological, dateKey } from "./ledger-shared.mjs"; +import { measureDisplay, plotDate } from "./measure-totals.mjs"; +import { CLOSING, nextRegime, offOf } from "./panel-model.mjs"; + +const GENERIC = /^(some diet|no diet|something unnamed)$/i; + +/** + * A run's own name from its opening row's words, or null when they only + * repeat the regime ("Keto", "Keto · 5 carbs a day", "off keto", "Some diet"). + */ +export function runName(display, regime) { + const d = String(display ?? "").trim(); + if (!d || GENERIC.test(d) || /^off\b/i.test(d) || /[·+]/.test(d)) return null; + const names = [regime?.key, regime?.label].filter(Boolean).map((x) => String(x).toLowerCase()); + if (names.some((n) => d.toLowerCase() === n || d.toLowerCase().startsWith(`${n} `))) return null; + return d; +} + +/** + * The record: `{ from, to, runs: [{ key, n, since, end, ended, name, row }], + * marks: [{ date, key, kind: "off" | "med", display, row }], weights: [{ date, + * value }] }` -- `end` null for the run still open; `from`/`to` the earliest and + * latest dates any of it has. + * + * @param {any[]} own his rows in scope + * @param {any} schema the resolved measure schema + * @param {string | null} regimeTrack the regime track's key + * @param {any[]} readings his weight rows (current and past) + */ +export function dietRecord(own, schema, regimeTrack, readings = [], opts = {}) { + if (!regimeTrack) return null; + const off = offOf(schema, regimeTrack)?.key ?? null; + const regimes = new Map((schema.regimes ?? []).map((r) => [r.key, r])); + const runs = []; + const marks = []; + let open = null; + let cur = null; + let n = 0; + for (const row of chronological(own.filter((r) => r.scope === regimeTrack))) { + open = nextRegime(open, row, schema); + const date = plotDate(row); + const key = open && open.key !== off ? open.key : null; + if (key !== (cur?.key ?? null)) { + if (cur) { cur.end = date; cur.ended = key ? "new" : "off"; } + cur = null; + if (key) { + n += 1; + cur = { key, n, since: open.since ?? date, end: null, ended: null, name: runName(measureDisplay(row, schema), regimes.get(key)), row: row.id }; + runs.push(cur); + } + } + const value = String(row.value ?? ""); + if (CLOSING.has(row.event)) marks.push({ date, key: value, kind: "off", display: measureDisplay(row, schema), row: row.id }); + else if (regimes.get(value)?.key === "glp1" && !(cur && cur.row === row.id)) marks.push({ date, key: value, kind: "med", display: measureDisplay(row, schema), row: row.id }); + } + const weights = readings + .filter((r) => r.population === "current" && Number.isFinite(Number(r.value))) + .map((r) => ({ date: plotDate(r), value: Number(r.value) })) + .filter((w) => w.date) + .sort((a, b) => dateKey(a.date).localeCompare(dateKey(b.date))); + const points = recordPoints(own, readings, opts); + const { claims, leftOut } = weightClaims(own); + const dates = [...runs.flatMap((r) => [r.since, r.end]), ...marks.map((m) => m.date), ...weights.map((w) => w.date), ...points.map((p) => p.date)] + .filter(Boolean).map(dateKey); + for (const c of claims) dates.push(dateKey(c.applied), dateKey(c.said)); + dates.sort(); + return { from: dates[0] ?? null, to: dates[dates.length - 1] ?? null, runs, marks, weights, points, claims, leftOut }; +} + +/** A claim told at least this many days after the day it applied is drawn as told later (a retelling). */ +export const RETOLD_DAYS = 30; + +/** + * EVERY weight he gave, at the day it APPLIED: each weight-scope row of his + * with a number that is a weight -- what he weighs now (`current`) and what he + * weighed (`past`) -- `{ row, value, applied, said, retold, qualifier, range, + * population }`, `applied` its asOf (else its date), `said` its date, `retold` + * when he said it RETOLD_DAYS or more after it applied. A loss or gain + * (`delta`) or "N over" (`overweight_by`) names no weight the ledger resolves, + * so it is left out and counted (`leftOut`, by population); goals and promises + * are not weights. + */ +export function weightClaims(own) { + const claims = []; + const leftOut = {}; + for (const r of own) { + if (r.scope !== "weight") continue; + const value = Number(r.value); + if (r.population === "current" || r.population === "past") { + const said = r.date ?? null; + const applied = r.asOf ?? r.date ?? null; + if (!Number.isFinite(value) || !applied) { leftOut[r.population] = (leftOut[r.population] ?? 0) + 1; continue; } + const late = said && applied && dateKey(applied) < dateKey(said) && (Date.parse(dateKey(said)) - Date.parse(dateKey(applied))) / 86400000 >= RETOLD_DAYS; + claims.push({ + row: r.id, value, applied: dateKey(applied), said: said ? dateKey(said) : dateKey(applied), retold: !!late, + qualifier: typeof r.qualifier === "string" ? r.qualifier : null, + range: Array.isArray(r.range) && r.range.length === 2 ? r.range.map(Number) : null, + population: r.population, + }); + } else if ((r.population === "delta" || r.population === "overweight_by") && Number.isFinite(value)) { + leftOut[r.population] = (leftOut[r.population] ?? 0) + 1; + } + } + claims.sort((a, b) => a.applied.localeCompare(b.applied) || a.said.localeCompare(b.said)); + return { claims, leftOut }; +} + +/** + * The annotated weights on the record's line (`deck.finale.dietRuns.marks`): + * each named row at the day it was his weight (its asOf, else its date) and its + * value, with the author's label -- his words -- `kind` "peak" for THE peak (the + * one marked `peak`, else the heaviest marked), "mark" else; and, unless `low` + * is false, the lowest weight he stated at the time, "low" (its label `low` + * when it is words, else "his low · <value>") -- never a bound ("over 240"), + * and of one weigh-in told twice the same day ("291." and "291.5") the fuller. + * A row the ledger lacks, or with no number, is left out. + * + * @returns {Array<{ row: string, date: string, value: number, label: string, kind: "peak" | "mark" | "low" }>} + */ +export function recordPoints(own, readings, { marks = [], low = true } = {}) { + const byId = new Map(own.map((r) => [r.id, r])); + const points = []; + for (const m of Array.isArray(marks) ? marks : []) { + const row = byId.get(String(m?.row ?? "")); + const value = Number(row?.value); + if (!row || !Number.isFinite(value) || !plotDate(row)) continue; + points.push({ row: row.id, date: plotDate(row), value, label: String(m.label ?? "").trim(), kind: m.peak === true ? "peak" : "mark" }); + } + if (points.length && !points.some((p) => p.kind === "peak")) points.reduce((a, b) => (b.value > a.value ? b : a)).kind = "peak"; + if (low !== false) { + // A weight he STATED, as measured: no bound ("over 240" is a floor, not a weigh-in). + const stated = readings.filter((r) => r.population === "current" && Number.isFinite(Number(r.value)) && plotDate(r) && !["<", ">"].includes(r.qualifier)); + let lo = stated.reduce((a, b) => (!a || Number(b.value) < Number(a.value) || (Number(b.value) === Number(a.value) && dateKey(plotDate(b)) > dateKey(plotDate(a))) ? b : a), null); + // One weigh-in told twice ("291." on X, "291.5" on stream, the same day): the reading he gave in full. + const fuller = lo && stated.find((r) => r !== lo && dateKey(plotDate(r)) === dateKey(plotDate(lo)) && Math.abs(Number(r.value) - Number(lo.value)) < 1 && !Number.isInteger(Number(r.value)) && Number.isInteger(Number(lo.value))); + if (fuller) lo = fuller; + if (lo && !points.some((p) => p.row === lo.id)) { + points.push({ row: lo.id, date: plotDate(lo), value: Number(lo.value), label: typeof low === "string" && low.trim() ? low.trim() : `his low · ${Number(lo.value)}`, kind: "low" }); + } + } + return points.sort((a, b) => dateKey(a.date).localeCompare(dateKey(b.date))); +} diff --git a/umtool/report-to-video/finale.mjs b/umtool/report-to-video/finale.mjs @@ -18,6 +18,10 @@ // "pips": true | false false: the finale's own clips get no pip on the rail // (footer or large) -- the rail is the record alone; their // titles and dates stay in their own area (default true) +// "dietRuns": true | false | { marks, low } the whole diet record drawn under the rail (module runs-finale, +// chrome-runs-finale.mjs; needs railLabels sections|none; default false): +// `marks` [{row, label, peak?}] dots on its weight line with his words, +// the heaviest THE peak; `low` the lowest stated weight marked (default on) // "claims": "rotate" | "all" the claim checks (deck.claims) on the large rail: // one at a time, each for an even share of the page's // time (default "rotate"; all at once when there is @@ -87,6 +91,7 @@ export const FINALE_DEFAULTS = Object.freeze({ timelineShare: "auto", claims: "rotate", pips: true, + dietRuns: false, }); /** @@ -140,6 +145,11 @@ export function validateFinaleSettings(f, where = "render.chrome.deck.finale") { } if (f.totals !== undefined && typeof f.totals !== "boolean") errors.push(`${where}.totals must be true or false`); if (f.pips !== undefined && typeof f.pips !== "boolean") errors.push(`${where}.pips must be true or false`); + if (f.dietRuns !== undefined && typeof f.dietRuns !== "boolean") errors.push(...dietRunsProblems(f.dietRuns, `${where}.dietRuns`)); + // The diet runs stand under the rail, where "all" and "nodes" put the pips' labels and dates. + if (dietRunsOn(f.dietRuns) && !["sections", "none"].includes(f.railLabels ?? FINALE_DEFAULTS.railLabels)) { + errors.push(`${where}.dietRuns draws under the rail, where railLabels "${f.railLabels ?? FINALE_DEFAULTS.railLabels}" puts the pips' words: set ${where}.railLabels "sections" or "none"`); + } if (f.statsTitle !== undefined && f.statsTitle !== null) { const p = lineProblem(f.statsTitle, FINALE_LIMITS.statsTitle, `${where}.statsTitle`); if (p) errors.push(p); @@ -168,6 +178,53 @@ export function validateFinaleSettings(f, where = "render.chrome.deck.finale") { return errors; } +/** The finale's diet runs' marks: how many, and a label's characters. */ +export const DIET_RUNS_LIMITS = Object.freeze({ marks: 8, label: 60 }); + +/** Is the finale's diet record on (`dietRuns`: true, or its object)? */ +export const dietRunsOn = (v) => v === true || isObj(v); + +/** Where the record's weights stand (`dietRuns.weights`): at the date each APPLIED, the date each was SAID, or none. */ +export const DIET_RUNS_WEIGHTS = Object.freeze(["applied", "said"]); + +/** The record's weight layer: "applied" (the default when the record is on), "said", or false. */ +export const dietRunsWeights = (v) => (!dietRunsOn(v) ? false : isObj(v) && v.weights !== undefined ? v.weights : "applied"); + +/** + * The design px the finale's diet record takes under the large rail's track + * (chrome-runs-finale.mjs): 0 off; with the weight layer, the layer over the + * bars and their labels; without it, the bars and their labels alone. + */ +export const dietRunsPanel = (v) => (!dietRunsOn(v) ? 0 : dietRunsWeights(v) ? 218 : 122); + +/** Why `deck.finale.dietRuns` (an object) cannot be drawn. */ +export function dietRunsProblems(v, where) { + if (!isObj(v)) return [`${where} must be true, false or { marks, low, weights }`]; + const errors = []; + for (const k of Object.keys(v)) if (!["marks", "low", "weights"].includes(k)) errors.push(`${where}.${k} is not a diet-runs setting (marks, low, weights)`); + if (v.weights !== undefined && v.weights !== false && !DIET_RUNS_WEIGHTS.includes(v.weights)) errors.push(`${where}.weights must be "applied", "said" or false`); + if (v.low !== undefined && typeof v.low !== "boolean") { + const p = typeof v.low === "string" ? lineProblem(v.low, DIET_RUNS_LIMITS.label, `${where}.low`) : `${where}.low must be true, false or its label`; + if (p) errors.push(p); + } + if (v.marks !== undefined) { + if (!Array.isArray(v.marks)) errors.push(`${where}.marks must be a list of { row, label, peak? }`); + else { + if (v.marks.length > DIET_RUNS_LIMITS.marks) errors.push(`${where}.marks has ${v.marks.length} (at most ${DIET_RUNS_LIMITS.marks})`); + v.marks.forEach((m, i) => { + const at = `${where}.marks[${i}]`; + if (!isObj(m)) { errors.push(`${at} must be { row, label, peak? }`); return; } + for (const k of Object.keys(m)) if (!["row", "label", "peak"].includes(k)) errors.push(`${at}.${k} is not a mark field (row, label, peak)`); + if (typeof m.row !== "string" || !m.row.trim()) errors.push(`${at}.row must name a ledger row`); + const p = lineProblem(m.label, DIET_RUNS_LIMITS.label, `${at}.label`); + if (p) errors.push(p); + if (m.peak !== undefined && typeof m.peak !== "boolean") errors.push(`${at}.peak must be true or false`); + }); + } + } + return errors; +} + /** The finale settings with every default filled in (the stats trimmed, a number value as text). */ export function resolveFinale(render) { const f = isObj(render?.chrome?.deck?.finale) ? render.chrome.deck.finale : {}; 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/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs @@ -27,7 +27,7 @@ // off-scope rule: this only draws state.diet). import { deckGeometry, feedGeometry, instrumentsGeometry } from "./deck.mjs"; import { chapterCover, chapterWindows } from "./chrome-story.mjs"; -import { MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs"; +import { dietTagWidth, MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs"; import { resolveShelf } from "./modules/shelf-settings.mjs"; const r4 = (v) => Math.round(v * 10000) / 10000; @@ -229,6 +229,7 @@ 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; n += 1; @@ -251,14 +252,22 @@ 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, - goalsSet: Array.isArray(s?.goals) ? s.goals.length : n, + ...(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, notes: shown.map((k) => { const x = notes.get(k); return { @@ -510,6 +519,34 @@ export function dietStates(schedule, render) { }); } +/** + * The diet's running day count (`diet.days`, on its front tag): `{ at, days, + * run }` wherever it changes -- the days on the current diet (dietRuns: its + * `since`, a new regime or diet number a new run) to the in-record date at the + * playhead (the running latest date of every event so far), the same number + * the streak chain's "Day N" reads; `run` null while no diet is on. + */ +export function dietDays(schedule, render) { + const m = measureOf(schedule); + const cfg = resolveMeasureExtra("diet", render); + if (!m || !cfg) return []; + const runs = dietRuns(m, cfg); + const out = []; + let date = null; + for (const { e } of stepsOf(m)) { + if (e.date) date = isoMax(date, e.date); + const t = e.t; + const run = runs.findIndex((r) => r.startT <= t + 1e-6 && (r.endT === null || r.endT > t + 1e-6)); + if (run < 0 && !out.length) continue; + const days = run >= 0 ? runDays(runs[run], isoMax(runs[run].start, date)) : null; + const last = out[out.length - 1]; + if (last && last.days === days && last.run === (run >= 0 ? run : null)) continue; + if (last && Math.abs(last.at - t) < 1e-6) out.pop(); + out.push({ at: r4(t), days, run: run >= 0 ? run : null }); + } + return out; +} + // --------------------------------------------------------------------------- // STREAK: a chain per run, cracked when it ends. // --------------------------------------------------------------------------- @@ -693,15 +730,41 @@ export const MEASURE_BOXES = Object.freeze({ /** One diet tag (`diet.form: "tags"`), design px: its width, the air between two, and the row's height. */ export const DIET_TAG = Object.freeze({ width: 220, gap: 12, height: 116 }); -/** The diet's row of `n` tags, design px. */ -export const dietTagsBox = (n) => ({ width: n * DIET_TAG.width + (n - 1) * DIET_TAG.gap, height: DIET_TAG.height }); +/** + * Where tag `i` (0 the newest) stands from the row's left, design px: side by + * side `gap` apart, or -- `overlap` above 0 -- fanned, each older one shifted + * right by the share of a tag that shows (`1 - overlap`). + */ +export const dietTagStep = (overlap = 0, days = false) => + (overlap > 0 ? Math.round(dietTagWidth(days) * (1 - overlap)) : dietTagWidth(days) + DIET_TAG.gap); + +/** The diet's row (or fan) of `n` tags, design px. */ +export const dietTagsBox = (n, overlap = 0, days = false) => ({ + width: dietTagWidth(days) + (n - 1) * dietTagStep(overlap, days), + height: DIET_TAG.height, +}); + +/** + * The goal stack ON THE SHELF (`goals.position: "shelf"`), design px: the + * count of goals set in a column at the left, then the notes fanned sideways + * like the diet's tags -- the newest in front -- each older one showing at + * least `back` (its goal's words), more when the shelf has width to give + * (shelfLayout). `natural` is that tightest fan, `widest` the notes side by side. + */ +export const GOALS_SHELF = Object.freeze({ count: 84, gap: 10, card: 250, back: 110, height: 116, step: 12 }); +export const goalsShelfWidth = (max, { widest = false } = {}) => + GOALS_SHELF.count + GOALS_SHELF.gap + GOALS_SHELF.card + (max - 1) * (widest ? GOALS_SHELF.card + GOALS_SHELF.step : GOALS_SHELF.back); -/** A module's design box: the promise clock's compact one in the column, the diet's row of tags. */ +/** A module's design box: the promise clock's compact one in the column, the diet's row of tags, the goals on the shelf. */ export function measureBox(id, render) { if (id === "promise" && resolveMeasureExtra("promise", render)?.slot === "column") return MEASURE_BOXES.promiseColumn; if (id === "diet") { const cfg = resolveMeasureExtra("diet", render); - if (cfg?.form === "tags") return dietTagsBox(cfg.tags ?? 3); + if (cfg?.form === "tags") return dietTagsBox(cfg.tags ?? 3, cfg.overlap ?? 0, cfg.days === true); + } + if (id === "goals") { + const cfg = resolveMeasureExtra("goals", render); + if (cfg?.position === SHELF_POSITION) return { width: goalsShelfWidth(cfg.max ?? 4), height: GOALS_SHELF.height }; } return MEASURE_BOXES[id]; } @@ -715,7 +778,9 @@ export const SHELF_NOTE_MIN = 160; * no shelf. Left to right in `items` order, `gap` apart: each measure extra on * it at its own design box scaled to the shelf's height (all of them a size * down together, centred in the height, when they would not fit its width); - * the note takes what width is left at its place (none under SHELF_NOTE_MIN). + * the goals' fan widens into what width is left (up to its notes side by + * side), then the note takes what is still left at its place (none under + * SHELF_NOTE_MIN). * An item that is off takes no slot. */ export function shelfLayout(render) { @@ -732,7 +797,17 @@ export function shelfLayout(render) { const fit = fixed > 0 ? Math.min(1, (rect.width - gaps) / fixed) : 1; const h = Math.max(2, evenDown(rect.height * fit)); const widths = boxes.map((b) => (b ? evenDown((b.width * h) / b.height) : 0)); - const rest = rect.width - widths.reduce((a, b) => a + b, 0) - gaps; + let rest = rect.width - widths.reduce((a, b) => a + b, 0) - gaps; + // The goals' fan takes the width left over, up to its notes side by side: its older notes show more of + // themselves rather than the shelf ending in a gap. (Then the note, in what is still left.) + const gi = items.indexOf("goals"); + if (gi >= 0 && rest > 0) { + const cfg = resolveMeasureExtra("goals", render); + const widest = evenDown((goalsShelfWidth(cfg.max ?? 4, { widest: true }) * h) / GOALS_SHELF.height); + const more = Math.max(0, Math.min(rest, widest - widths[gi])); + widths[gi] += evenDown(more); + rest -= evenDown(more); + } const noteW = items.includes("note") && rest >= SHELF_NOTE_MIN * k ? evenDown(rest) : 0; const slots = {}; let x = rect.x; diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs @@ -25,6 +25,8 @@ import { PROMISE_FORMS, boundAgrees, displayRange, measureDisplay, measureQualif 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"; export const MEASURE_SLICE_VERSION = 1; @@ -654,5 +656,9 @@ export function measureSlice(manifest, schedule, opts = {}) { hidden, state, 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(counted, s, regimeTrack, readings, isObj(manifest.render.chrome.deck.finale.dietRuns) ? manifest.render.chrome.deck.finale.dietRuns : {}) } + : {}), }; } diff --git a/umtool/report-to-video/modules/diet.mjs b/umtool/report-to-video/modules/diet.mjs @@ -8,7 +8,7 @@ import { dietHtml } from "../chrome-measure-extras.mjs"; import { dietStates } from "../measure-extras.mjs"; import { measureExtraModule } from "./measure-extras-module.mjs"; -import { DIET_FORMS, DIET_TAGS } from "./measure-extras-settings.mjs"; +import { DIET_BACK_MIN, DIET_FORMS, DIET_OVERLAP, DIET_TAGS, dietOverlapMax } from "./measure-extras-settings.mjs"; export default measureExtraModule({ id: "diet", @@ -23,6 +23,8 @@ export default measureExtraModule({ { key: "labels", type: "object", label: "Words per regime ({glp1: \"Ozempic\", …})" }, { key: "form", type: "enum", options: DIET_FORMS, label: "Drawn as (default: the stamp, the tags on the shelf)" }, { key: "tags", type: "number", min: DIET_TAGS[0], max: DIET_TAGS[1], step: 1, label: "Tags in the row", default: 3, when: { form: "tags" } }, + { key: "overlap", type: "number", min: DIET_OVERLAP[0], max: DIET_OVERLAP[1], step: 0.05, label: "Overlap (0: side by side; the share of each older tag behind the one in front)", default: 0, when: { form: "tags" } }, + { key: "days", type: "boolean", label: "Days on the diet, on the front tag", default: false, when: { form: "tags" } }, ], docs: { intro: "The diet he names as a rubber stamp in a corner of the footage box (`render.chrome.deck.diet`, measure-extras.mjs): at each change of the state's diet -- its regime or its diet number -- a new stamp slams on (in big and turned, onto the page, a shake), the regime's word in its ink and \"DIET #n\" under it with the ledger's words when they say more (\"Keto · 5 carbs a day\"); a change of words alone fades the new stamp in. A null diet after one fades to \"NO DIET\" in grey. It draws `state.diet` as the measure slice gives it -- the off-scope rule (\"off GLP-1\" while on keto is still keto) is the ledger's. The inks default to the quartering-diet regimes' (keto #E0913C, carnivore #C9534B, fasting #4E9BD8, calories #3FA9A0, glp1 #B168C6, other #8E97A8, off #98A29B).", @@ -31,6 +33,8 @@ export default measureExtraModule({ ["`deck.diet.position`, `.x`/`.y`, `.scale`", "an anchor in the footage box · design px · 0.5–2 · default `bottom-left`, unset, 1", "`umtool look <p> deck.diet.position=top-right`"], ["`deck.diet.hold`, `.finale`", "0 (up from the first diet on) or 2–600 s · `hide` `show` · default 0, `hide`", "`umtool look <p> deck.diet.hold=15`"], ["`deck.diet.form`, `.tags`", "`stamp` · `tags`: the last `tags` diets as a row of dated tags -- each a small stamp with the regime's word in its ink, \"DIET #n\" and the ledger's words (less the regime they open with: \"5 carbs a day\"), and the day he switched to it (`state.diet.since`, \"Mar 14, 2025\"; new words for the same diet keep that day); at each change the new tag slams in at the left, the older slide right and dim, the one past `tags` falls off; a change of words alone fades the new tag over the old; a null diet is a grey \"NO DIET\" tag with its date · 1–4 · default `stamp` (`tags` on the shelf), 3", "`umtool look <p> deck.diet.form=tags deck.diet.tags=2`"], + ["`deck.diet.overlap`", `${DIET_OVERLAP[0]}–${DIET_OVERLAP[1]}, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past \`tags\` slides off the back. The fan is narrower by what hides. An older tag's word and date need ${DIET_BACK_MIN} design px of it, so it is refused past ${dietOverlapMax(false)} (${dietOverlapMax(true)} with \`days\`)`, "`umtool look <p> deck.diet.overlap=0.5`"], + ["`deck.diet.days`", "`true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's \"Day N\"), in a column of its own -- the tag 300 design px wide · default `false`", "`umtool look <p> deck.diet.days=true`"], ["`deck.diet.colors`, `.labels`", "`{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names", "`umtool look <p> deck.diet.labels='{\"glp1\":\"Ozempic\"}'`"], ], }, diff --git a/umtool/report-to-video/modules/finale.mjs b/umtool/report-to-video/modules/finale.mjs @@ -36,12 +36,13 @@ export default defineModule({ { key: "pips", type: "boolean", label: "The finale's clips on the rail", default: true }, { key: "timelineShare", type: "number", min: 0.38, max: 0.6, step: 0.01, label: "Timeline share (auto when unset)" }, { key: "claims", type: "enum", options: ["rotate", "all"], label: "Claim checks", default: "rotate" }, + { key: "dietRuns", type: "boolean", label: "Every diet on record under the rail (railLabels sections or none)", default: false }, ], docs: { heading: "Finale", intro: "The full reference is [The finale](#the-finale-the-timeline-in-primary-view). It reads the counter's totals (`counter.totals`) and the rail's layout (`rail.layout`); the counter reads its window (`finale.window`): a mark that would stamp inside it counts as it opens.", rows: [ - ["`deck.finale`", "`{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims}`", "`umtool look <p> deck.finale='{…}'`"], + ["`deck.finale`", "`{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims, dietRuns}` -- `dietRuns`: the whole diet record under the rail ([Diet runs in the finale](#diet-runs-in-the-finale))", "`umtool look <p> deck.finale='{…}'`"], ["a clip's `layout`", "`finale` on one run of clips at the end", "`umtool set <p> <clip> layout=finale`"], ], }, diff --git a/umtool/report-to-video/modules/goals.mjs b/umtool/report-to-video/modules/goals.mjs @@ -28,6 +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.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/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -41,12 +41,13 @@ import goals from "./goals.mjs"; import promise from "./promise.mjs"; import streak from "./streak.mjs"; import shelf from "./shelf.mjs"; +import runsFinale from "./runs-finale.mjs"; export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS }; /** Every module, by z (stack order), then id. */ export const MODULES = Object.freeze( - [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale] + [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale, runsFinale] .sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)), ); diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs @@ -9,7 +9,7 @@ // render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown } // render.chrome.deck.peak { show, position, x, y, scale, hold, finale, title, color, values } // render.chrome.deck.promise { show, position, x, y, scale, hold, finale, label, verb, kept, broken, checks, speakers, claimVerb, claimColor } -// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags } +// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days } // render.chrome.deck.streak { show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels } // // Each is ON whenever the cut has a measure slice (the build writes one only @@ -70,6 +70,24 @@ export const DIET_FORMS = Object.freeze(["stamp", "tags"]); /** How many tags the diet's row keeps (`diet.tags`). */ export const DIET_TAGS = Object.freeze([1, 4]); +/** + * How much of each older tag hides behind the one in front (`diet.overlap`): + * 0 is the row of tags side by side; above it the tags fan sideways like the + * goal stack's notes, the newest in front at the left. The bounds a value is + * checked against; legibility caps it lower (dietOverlapMax: an older tag's + * regime word and date need DIET_BACK_MIN of it). + */ +export const DIET_OVERLAP = Object.freeze([0, 0.8]); + +/** The design px of an older tag that must show beside the one in front of it: its regime word and its date. */ +export const DIET_BACK_MIN = 110; + +/** A diet tag's width, design px: 220, or 300 with the running day count (`diet.days`) in a column of its own. */ +export const dietTagWidth = (days) => (days ? 300 : 220); + +/** The most overlap that keeps an older tag's regime word and date in view. */ +export const dietOverlapMax = (days) => Math.floor((1 - DIET_BACK_MIN / dietTagWidth(days)) * 100) / 100; + /** The diet regimes the ledger names (ledgerSchema.regimes), and what the badge calls each. */ export const DIET_LABELS = Object.freeze({ keto: "Keto", carnivore: "Carnivore", fasting: "Fasting", calories: "Counting calories", @@ -116,7 +134,7 @@ export const MEASURE_DEFAULTS = Object.freeze({ speakers: Object.freeze({}), claimVerb: "paid", claimColor: "#E37AB8", slot: "auto" }), // The diet badge: up from the first diet on, re-stamped at every change. // `form` "tags" (the default on the shelf): the last `tags` diets as dated tags, the newest slammed in at the left. - diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3 }), + diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3, overlap: 0, days: false }), // The streak chain: bottom-centre, between the diet badge and the goal // stack, so either or both can run. `title` null is the source's own word. streak: Object.freeze({ ...COMMON, position: "bottom-center", source: "diet", axis: "date", title: null, color: null, colors: Object.freeze({}), labels: Object.freeze({}) }), @@ -168,6 +186,8 @@ export function resolveMeasureExtra(id, render) { if (shelf && SHELF_EXTRAS.includes(id) && (shelf.items.includes(id) || own.position === SHELF_POSITION)) { out.position = SHELF_POSITION; out.finale = shelf.finale; + // The shelf is a HUD: what stands on it stays up from its first event (`hold` unset), the goals too. + if (own.hold === undefined) out.hold = null; if (id === "diet" && own.form === undefined) out.form = "tags"; } else if (out.position === SHELF_POSITION) { // No shelf to stand on (validateMeasureExtra says so): its default anchor, so a stray key draws something. @@ -279,6 +299,14 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`, if (v.tags !== undefined && !(Number.isInteger(v.tags) && numIn(v.tags, DIET_TAGS[0], DIET_TAGS[1]))) { errors.push(`${where}.tags must be a whole number from ${DIET_TAGS[0]} to ${DIET_TAGS[1]}`); } + if (v.days !== undefined && typeof v.days !== "boolean") errors.push(`${where}.days must be true or false`); + if (v.overlap !== undefined) { + const max = dietOverlapMax(v.days === true); + if (!numIn(v.overlap, DIET_OVERLAP[0], DIET_OVERLAP[1])) errors.push(`${where}.overlap must be from ${DIET_OVERLAP[0]} to ${DIET_OVERLAP[1]}`); + else if (v.overlap > max) { + errors.push(`${where}.overlap ${v.overlap} hides an older tag's regime word and date: they need ${DIET_BACK_MIN} of its ${dietTagWidth(v.days === true)} design px (overlap at most ${max}${v.days === true ? "" : `, or ${dietOverlapMax(true)} with days`})`); + } + } } if (id === "diet" || id === "streak") { for (const k of ["colors", "labels"]) { diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs @@ -49,7 +49,7 @@ test("the registry: unique ids and regions, sorted by z, the deck's overlays in // The order the build has always laid them in, the measure's instruments beside the side panel; the // finale over all of them but the dial's finale and the promise clock, drawn over it (z 95 both); the shelf's // note page under the measure extras (it never meets them: they stand in slots of their own beside it). - assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "chat", "stats", "pair", "status", "fx", "shelf", "streak", "diet", "peak", "goals", "threads", "dial", "odometer", "trail", "flips", "chapter", "finale", "dial-finale", "promise"]); + assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "chat", "stats", "pair", "status", "fx", "shelf", "streak", "diet", "peak", "goals", "threads", "dial", "odometer", "trail", "flips", "chapter", "finale", "runs-finale", "dial-finale", "promise"]); assert.equal(moduleOfRegion("deck").id, "shell"); assert.equal(regionModule("posts").id, "popup-posts"); assert.throws(() => regionModule("nope"), /unknown chrome region: nope/); @@ -153,7 +153,7 @@ test("play: a live-preview contract only an overlay with a page and regions decl assert.throws(() => defineModule({ ...base, play: { clock: "cut", ready: "x" } }), /play must be/); assert.throws(() => defineModule({ ...base, page: undefined, play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); assert.throws(() => defineModule({ ...base, kind: "segment", play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); - assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "shelf", "streak", "diet", "peak", "goals", "threads", "dial", "odometer", "trail", "flips", "chapter", "dial-finale", "promise"]); + assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "shelf", "streak", "diet", "peak", "goals", "threads", "dial", "odometer", "trail", "flips", "chapter", "runs-finale", "dial-finale", "promise"]); for (const m of playModules()) assert.equal(m.play.ready, `${m.region}:ready`, m.id); }); diff --git a/umtool/report-to-video/modules/runs-finale.mjs b/umtool/report-to-video/modules/runs-finale.mjs @@ -0,0 +1,71 @@ +// THE FINALE'S DETAILED DIET RUNS (module `runs-finale`, region `runs-finale`): +// with `deck.finale.dietRuns: true`, the whole record of his diets drawn large +// in the finale's timeline panel under the rail -- every run from the earliest +// row, the empty years a marked break, the stops and the medication marked, +// his stated weights over it, the longest runs and the one still going +// labelled (chrome-runs-finale.mjs, the measure slice's `record`). A window over +// the finale's, laid over it; off by default. +import path from "node:path"; + +import { snapWindow } from "../deck.mjs"; +import { recordOf, runsFinaleGeometry, runsFinaleHtml, runsFinaleWanted } from "../chrome-runs-finale.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +const drawn = (schedule, render) => !!schedule?.finale && runsFinaleWanted(render) && !!recordOf(schedule) && !!runsFinaleGeometry(schedule, render); + +export default defineModule({ + id: "runs-finale", + version: 1, + z: 94, + kind: "overlay-window", + slot: "full", + title: "Diet runs in the finale", + summary: "The finale's detailed diet record: every run from the first row a bar in its diet's ink, the empty years a break, the stops and medication marked, his weights over it, the long runs and the open one labelled.", + docs: { + heading: "Diet runs in the finale", + intro: "With `deck.finale.dietRuns: true` (and a measure ledger with a regime track), the finale's timeline panel -- under the large rail's track, the rail's width, down to the panel's foot: with the weight layer (120, 202) 1704×220 at 1080p, the track staying where its labels put it and the timeline taking the room under it (up to `FINALE_SHARE.max`); without it 1704×122 -- carries the WHOLE record of his diets (the measure slice's `record`, diet-record.mjs: every regime row in scope, on camera or not, through the state's own rule): each run a bar in its diet's ink on a time axis from the earliest row; a stretch of more than two years with nothing on record squeezed to a marked break (\"2013–2018\"), and a run whose end the record does not have fading into it; a row that stopped a diet a grey tick under the bars, one naming the medication (GLP-1) a purple one; his stated weights a light line over the bars, the weights the video marks (`marks`: his heaviest as THE peak) and his low as labelled dots on it; the run still going and the longest ones labelled in two rows under the bars where they fit -- the diet's word (the run's own name when its row gives one: \"WEIGHT WATCHERS\"), its number when the cut showed it (\"DIET #6\", the shelf's), its dates and its days, the open one \"N days and counting\" to the in-record date. It sweeps in left to right over 2.6 s after the finale's grow, each label as the sweep reaches it, then holds; it stands clear of the side video, the lower column's instruments and the promise clock. It needs `deck.finale.railLabels` `sections` or `none` (the pips' labels and dates use that space) and at least 100 px under the rail.", + rows: [ + ["`deck.finale.dietRuns`", "`true` · `false` · `{weights, marks, low}` · default `false`", "`umtool look <p> deck.finale.dietRuns=true`"], + ["`deck.finale.dietRuns.weights`", "`applied` · `said` · `false` · default `applied`: the WEIGHT LAYER over the bars on the dial's scale (the panel 218 design px, the finale's timeline taking that room under the track) -- every weight he gave (a `current` or `past` row with a number) at the day it APPLIED (its asOf, else its date; `said`: the day he said it). Given at the time: solid, joined -- his claimed trajectory (a bound like \"over 240\" is a point, not joined). Told 30 days or more after it applied: hollow, with a thin leader to a tick at the day he said it, so a retold weight piles up at one period from its tellings. `>`/`<` a caret, `≈` a ring, a range a bar. A loss or gain (`delta`) and \"N over\" (`overweight_by`) name no weight the ledger resolves: left out (the record counts them, `record.leftOut`). `false`: the light line of his stated weights alone", "`umtool look <p> deck.finale.dietRuns='{\"weights\":\"said\"}'`"], + ["`deck.finale.dietRuns.marks`", "up to 8 `{row, label, peak?}`: a dot on the weight line at the row's day (its asOf, else its date) and value, the label -- his words, at most 60 characters -- and the month beside it; THE peak (the one marked `peak`, else the heaviest marked) a size up in the needle's red. A row the ledger lacks is left out", "`umtool look <p> deck.finale.dietRuns='{\"marks\":[{\"row\":\"w21\",\"label\":\"his heaviest · \\\"almost 400\\\"\"}]}'`"], + ["`deck.finale.dietRuns.low`", "`true` · `false` · its label · default `true`: the lowest weight he stated (never a bound like \"over 240\"; of one weigh-in told twice the same day, the fuller: 291.5 over \"291.\") marked in the accent, \"his low · 291.5\"", "`umtool look <p> deck.finale.dietRuns='{\"low\":false}'`"], + ], + }, + region: "runs-finale", + workers: "narrow", + noun: "the finale's diet runs'", + on: drawn, + check: (schedule, render) => { + if (!schedule?.finale) return "the finale's diet runs need a schedule with a finale (a clip with layout \"finale\")"; + if (!runsFinaleWanted(render)) return "the finale's diet runs are off (render.chrome.deck.finale.dietRuns)"; + if (!recordOf(schedule)) return "the finale's diet runs need the measure slice's diet record (a measure ledger with a regime track, and render.chrome.deck.measure)"; + if (!runsFinaleGeometry(schedule, render)) return "the finale's diet runs need 100 px under the large rail (a larger deck.finale.timelineShare)"; + return null; + }, + window: (schedule, { fps, total }) => snapWindow({ segment: "runs-finale", from: schedule.finale.from, to: schedule.finale.to }, { fps, total }), + names: ({ preview }) => ({ project: `runs-finale${preview ? "-preview" : ""}`, stem: "runs-finale" }), + async page(ctx) { + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + return runsFinaleHtml(ctx.schedule, ctx.render, ctx.window, { fonts }); + }, + /** Over the finale's window, laid at its own second. */ + regions(schedule, { render, outDir, shift = 0, clip = null }) { + const f = schedule?.finale; + if (!f || !drawn(schedule, render)) return []; + const g = runsFinaleGeometry(schedule, render); + const fps = Number(schedule.fps ?? render.fps); + const s = snapWindow({ segment: "runs-finale", from: f.from, to: f.to }, { fps, total: schedule.total }); + if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return []; + return [assertRegion({ + name: "runs-finale", + frames: path.join(outDir, "chrome", "runs-finale-frames"), + ...g, + offset: s.from - shift, + frameCount: s.frames, + window: s, + }, "window")]; + }, + play: { clock: "cut", ready: "runs-finale:ready" }, + // A window of the cut, as the finale's: its frame n is cut time `from` + n / fps. + frameKeys: { data: "runs-finale-data", omit: ["init", "cues", "from", "dur"], offset: "from" }, +}); diff --git a/umtool/report-to-video/modules/shelf.mjs b/umtool/report-to-video/modules/shelf.mjs @@ -35,7 +35,7 @@ export default defineModule({ ], docs: { heading: "Shelf", - intro: `A strip of the frame cleared beside the footage (\`render.chrome.deck.shelf\`, shelf-settings.mjs): the footage moves to the frame's top, \`railGap\` (24 px) in (\`side: "below"\`), or down onto the deck (\`"above"\`), and what it leaves -- as wide as the footage, 24 px clear of it and of the frame's edge or the deck -- is the shelf (beside the instruments' column, 1248×116 at (24, 750)). Everything that reads the footage box (the instruments, the posts, the chapter band, the finale, Play) follows it. Its occupants stand in it left to right in \`items\` order, \`gap\` apart, each at its own width scaled to the shelf's height (all a size down together when they would not fit): the measure extras that take \`position: "shelf"\` -- \`diet\` (its dated tags by default: \`deck.diet.form\`), \`streak\`, \`goals\`, \`peak\` -- and \`note\`, an entry's \`shelfNote\` in the width left (a chip that comes and goes with its entry; at least 160 px). Nothing covers the shelf, so its occupants never dodge a post card or a chapter band (an entry's \`hideModules\` still hides one). It needs ${SHELF_MIN} px of room or the deck refuses, naming the way out (a smaller \`footageScale\`, or \`subtitle.lines 1\`): with the instruments' column it is 116 px, 77 with \`subtitle.lines: 2\`; full-width footage at the default 0.82 leaves none. Off (absent, \`false\`), the footage stands where it always did.`, + intro: `A strip of the frame cleared beside the footage (\`render.chrome.deck.shelf\`, shelf-settings.mjs): the footage moves to the frame's top, \`railGap\` (24 px) in (\`side: "below"\`), or down onto the deck (\`"above"\`), and what it leaves -- as wide as the footage, 24 px clear of it and of the frame's edge or the deck -- is the shelf (beside the instruments' column, 1248×116 at (24, 750)). Everything that reads the footage box (the instruments, the posts, the chapter band, the finale, Play) follows it. Its occupants stand in it left to right in \`items\` order, \`gap\` apart, each at its own width scaled to the shelf's height (all a size down together when they would not fit; a goal stack on it takes the width left over, its notes fanning wider, so the shelf does not end in a gap): the measure extras that take \`position: "shelf"\` -- \`diet\` (its dated tags by default: \`deck.diet.form\`), \`streak\`, \`goals\`, \`peak\` -- and \`note\`, an entry's \`shelfNote\` in the width left (a chip that comes and goes with its entry; at least 160 px). Nothing covers the shelf, so its occupants never dodge a post card or a chapter band (an entry's \`hideModules\` still hides one). It needs ${SHELF_MIN} px of room or the deck refuses, naming the way out (a smaller \`footageScale\`, or \`subtitle.lines 1\`): with the instruments' column it is 116 px, 77 with \`subtitle.lines: 2\`; full-width footage at the default 0.82 leaves none. Off (absent, \`false\`), the footage stands where it always did.`, rows: [ ["`deck.shelf`", "`true` · `false` · `{show, side, items, gap, finale}` · default off", "`umtool look <p> deck.shelf=true deck.diet.position=shelf deck.streak.position=shelf`"], ["`deck.shelf.side`", "`below` (the footage at the top) · `above` (the footage on the deck) · default `below`", "`umtool look <p> deck.shelf.side=above`"], diff --git a/umtool/report-to-video/runs-finale.test.mjs b/umtool/report-to-video/runs-finale.test.mjs @@ -0,0 +1,163 @@ +// The finale's detailed diet runs (`deck.finale.dietRuns`; diet-record.mjs, +// chrome-runs-finale.mjs, modules/runs-finale.mjs): the whole diet record from +// its earliest row, an empty stretch a break, the stops and the medication +// marked, in the finale's panel under the rail -- and nothing of it unless asked. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { dietRecord, runName } from "./diet-record.mjs"; +import { RUNS_BREAK_DAYS, runsAxis, runsFinaleGeometry, runsFinaleHtml } from "./chrome-runs-finale.mjs"; +import { validateFinaleSettings } from "./finale.mjs"; +import { measureSchema } from "./measure-totals.mjs"; +import { measureSlice } from "./measure-slice.mjs"; +import { moduleById } from "./modules/index.mjs"; + +const SCHEMA = { + kind: "measure", unit: "lb", yMin: 210, yMax: 400, bandGapDays: 60, + tracks: [ + { key: "weight", role: "value", label: "Weight" }, + { key: "regime", role: "regime", label: "Diet", regimes: ["keto", "carnivore", "calories", "glp1", "off"], offKey: "off" }, + ], + forms: ["current", "past", "delta", "goal", "goal_loss", "overweight_by", "status"], + regimes: [ + { key: "keto", label: "Keto" }, { key: "carnivore", label: "Carnivore" }, { key: "calories", label: "Counting calories" }, + { key: "glp1", label: "GLP-1" }, { key: "off", label: "No diet" }, + ], +}; +const row = (o) => ({ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o }); +const LEDGER = [ + // 2013 (MeVsMe): Weight Watchers, three weights -- then nothing until 2018. + row({ id: "r105", date: "2013-02-22", scope: "regime", population: "status", value: "calories", event: "start", display: "Weight Watchers" }), + row({ id: "w127", date: "2013-03-09", asOf: "2013-03-02", population: "current", value: 345, display: "345 lb" }), + row({ id: "w130", date: "2013-03-21", population: "current", value: 342.9, display: "342.9 lb" }), + row({ id: "r07", date: "2021-09-14", scope: "regime", population: "status", value: "keto", event: "start", display: "Keto", entryId: "c1" }), + row({ id: "r11", date: "2022-07-27", scope: "regime", population: "status", value: "keto", event: "off", display: "off Keto" }), + row({ id: "r14", date: "2022-12-30", scope: "regime", population: "status", value: "carnivore", event: "on", display: "Carnivore", entryId: "c2" }), + row({ id: "r40", date: "2024-04-25", scope: "regime", population: "status", value: "glp1", event: "off", display: "off GLP-1" }), + row({ id: "w50", date: "2024-05-01", population: "current", value: 330, display: "330 lb", entryId: "c2" }), +]; +const TIMELINE = [ + { type: "clip", id: "c1", video: "v1", start: 0, end: 10, quoteStart: 1 }, + { type: "clip", id: "c2", video: "v2", start: 0, end: 10, quoteStart: 1, layout: "finale" }, +]; +const SEGMENTS = [{ id: "c1", start: 0, duration: 10 }, { id: "c2", start: 10, duration: 10 }]; +const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" }; +const renderOf = (finale = { railLabels: "sections", dietRuns: true }) => ({ + width: 1920, height: 1080, fps: 30, transition: 0, palette: PALETTE, + chrome: { engine: "hyperframes", layout: "deck", deck: { measure: { scopes: ["weight", "regime"], scale: { min: 220, max: 400 } }, finale } }, +}); +const manifest = (render = renderOf()) => ({ ledgerSchema: SCHEMA, ledger: LEDGER, timeline: TIMELINE, render }); + +test("the record: every regime row from the earliest, runs by the state's rule, named by their own words; stops and medication marked", () => { + const own = LEDGER; + const readings = LEDGER.filter((r) => r.scope === "weight"); + const rec = dietRecord(own, measureSchema(SCHEMA), "regime", readings); + assert.equal(rec.from, "2013-02-22"); + assert.deepEqual(rec.runs.map((r) => [r.n, r.key, r.since, r.end, r.ended, r.name]), [ + [1, "calories", "2013-02-22", "2021-09-14", "new", "Weight Watchers"], + [2, "keto", "2021-09-14", "2022-07-27", "off", null], + [3, "carnivore", "2022-12-30", null, null, null], + ]); + assert.deepEqual(rec.marks.map((m) => [m.row, m.kind]), [["r11", "off"], ["r40", "off"]]); + assert.deepEqual(rec.weights.map((w) => [w.date, w.value]), [["2013-03-02", 345], ["2013-03-21", 342.9], ["2024-05-01", 330]], "by the day it was his weight"); + assert.equal(runName("Keto · 5 carbs a day", { key: "keto", label: "Keto" }), null); + assert.equal(runName("off GLP-1", { key: "glp1", label: "GLP-1" }), null); +}); + +test("the slice carries the record only when the finale asks for it", () => { + const off = measureSlice(manifest(renderOf({ railLabels: "sections" })), { segments: SEGMENTS }, { asOf: "2026-11-03" }); + assert.equal("record" in off, false, "a cut without it writes the slice it always did"); + const on = measureSlice(manifest(), { segments: SEGMENTS }, { asOf: "2026-11-03" }); + assert.equal(on.record.runs.length, 3); +}); + +test("the axis: an empty stretch past two years squeezed to a marked break; the years on the rest", () => { + const A = runsAxis(["2013-02-22", "2013-03-21", "2021-09-14", "2022-07-27", "2024-05-01"], 1704, { brk: 44, pad: 8 }); + assert.equal(A.breaks.length, 1); + assert.deepEqual([A.breaks[0].from, A.breaks[0].to], ["2013-03-21", "2021-09-14"]); + assert.equal(Math.round(A.breaks[0].x1 - A.breaks[0].x0), 44); + assert.ok(A.x("2024-05-01") <= 1704 - 8 + 1e-6); + assert.deepEqual(A.years.map((y) => y.year), [2022, 2023, 2024], "no year ticks inside the break"); + assert.ok(RUNS_BREAK_DAYS === 730); +}); + +test("validation and the page: railLabels must leave the space; the page labels the open run 'and counting'", () => { + assert.match(validateFinaleSettings({ dietRuns: true }).join(), /dietRuns draws under the rail, where railLabels "all" puts the pips' words: set render\.chrome\.deck\.finale\.railLabels "sections" or "none"/); + assert.deepEqual(validateFinaleSettings({ dietRuns: true, railLabels: "none" }), []); + assert.match(validateFinaleSettings({ dietRuns: "yes" }).join(), /dietRuns must be true, false or \{ marks, low, weights \}/); + const r = renderOf(); + const m = measureSlice(manifest(r), { segments: SEGMENTS }, { asOf: "2026-11-03" }); + const schedule = { kind: "deck", fps: 30, total: 20, transition: 0, segments: SEGMENTS.map((s) => ({ ...s, end: s.start + s.duration, type: "clip", title: "", subtitle: "" })), finale: { segments: ["c2"], from: 10.5, to: 20, video: "side", motion: "grow", grow: 0.8 }, measure: m }; + const g = runsFinaleGeometry(schedule, r); + assert.ok(g && g.x === 120 && g.y > 200 && g.height >= 100, JSON.stringify(g)); + const { html, items } = runsFinaleHtml(schedule, r, { from: 10.5, to: 20 }, { fonts: {} }); + assert.match(html, /CARNIVORE/); + assert.match(html, /days and counting/); + assert.match(html, /WEIGHT WATCHERS/); + assert.match(html, /2013–2021/, "the break says what it spans"); + assert.ok(items.length >= 2); + const mod = moduleById("runs-finale"); + assert.equal(mod.on(schedule, r), true); + assert.equal(mod.on(schedule, renderOf({ railLabels: "sections" })), false, "off by default"); +}); + +test("marks on the weight line: the author's rows with his words, the heaviest THE peak; the low by default, never a bound", async () => { + const { recordPoints } = await import("./diet-record.mjs"); + const rows = [ + ...LEDGER, + row({ id: "w21", date: "2023-09-29", asOf: "2023-02-24", population: "past", value: 390, qualifier: "≈", display: "390 lb" }), + row({ id: "w07", date: "2022-06-15", population: "current", value: 240, qualifier: ">", display: "over 240" }), + row({ id: "w117", date: "2026-10-23", population: "current", value: 291, display: "291." }), + row({ id: "w118", date: "2026-10-26", asOf: "2026-10-23", population: "current", value: 291.5, display: "291.5 lb" }), + ]; + const readings = rows.filter((r) => r.scope === "weight"); + const pts = recordPoints(rows, readings, { marks: [{ row: "w21", label: "his heaviest · \"almost 400\"" }, { row: "w127", label: "2013 · 345" }, { row: "nope", label: "x" }] }); + assert.deepEqual(pts.map((p) => [p.row, p.date, p.value, p.kind]), [ + ["w127", "2013-03-02", 345, "mark"], + ["w21", "2023-02-24", 390, "peak"], + ["w118", "2026-10-23", 291.5, "low"], + ], "by the day it was his weight; the heaviest the peak; the low not 'over 240', and 291.5 over the same day's '291.'"); + assert.equal(pts[2].label, "his low · 291.5"); + assert.deepEqual(recordPoints(rows, readings, { low: false }), []); + assert.equal(recordPoints(rows, readings, { marks: [{ row: "w127", label: "a", peak: true }, { row: "w21", label: "b" }] })[0].kind, "peak", "the one marked peak"); + assert.deepEqual(validateFinaleSettings({ railLabels: "sections", dietRuns: { marks: [{ row: "w21", label: "his heaviest" }], low: "his low" } }), []); + assert.match(validateFinaleSettings({ railLabels: "sections", dietRuns: { marks: [{ row: "w21" }], lowest: true } }).join(), /dietRuns\.lowest is not a diet-runs setting.*marks\[0\]\.label/s); + const on = measureSlice({ ...manifest(renderOf({ railLabels: "none", dietRuns: { marks: [{ row: "w127", label: "2013" }] } })), ledger: rows }, { segments: SEGMENTS }, { asOf: "2026-11-03" }); + assert.deepEqual(on.record.points.map((p) => p.kind), ["peak", "low"]); +}); + +test("the weight layer: every weight he gave at the day it applied, the retold ones apart; losses and 'N over' left out and counted", async () => { + const { weightClaims } = await import("./diet-record.mjs"); + const rows = [ + ...LEDGER, + row({ id: "w21", date: "2023-09-29", asOf: "2023-02-24", population: "past", value: 390, qualifier: "≈", display: "390 lb" }), + row({ id: "w07", date: "2022-06-15", population: "current", value: 240, qualifier: ">", display: "over 240" }), + row({ id: "d1", date: "2024-02-01", population: "delta", value: -19.4, display: "-19.4" }), + row({ id: "o1", date: "2023-08-18", population: "overweight_by", value: 100, display: "100 over" }), + row({ id: "g1", date: "2023-08-18", population: "goal_loss", value: -100, display: "lose 100" }), + ]; + const { claims, leftOut } = weightClaims(rows); + assert.deepEqual(claims.map((c) => [c.row, c.applied, c.said, c.retold, c.qualifier]), [ + ["w127", "2013-03-02", "2013-03-09", false, null], + ["w130", "2013-03-21", "2013-03-21", false, null], + ["w07", "2022-06-15", "2022-06-15", false, ">"], + ["w21", "2023-02-24", "2023-09-29", true, "≈"], + ["w50", "2024-05-01", "2024-05-01", false, null], + ], "a week's asOf is still his weight then; seven months on is a retelling"); + assert.deepEqual(leftOut, { delta: 1, overweight_by: 1 }); + assert.match(validateFinaleSettings({ railLabels: "none", dietRuns: { weights: "both" } }).join(), /weights must be "applied", "said" or false/); + const r = renderOf({ railLabels: "sections", dietRuns: { weights: "applied" } }); + const m = measureSlice({ ...manifest(r), ledger: rows }, { segments: SEGMENTS }, { asOf: "2026-11-03" }); + const schedule = { kind: "deck", fps: 30, total: 20, transition: 0, segments: SEGMENTS.map((s) => ({ ...s, end: s.start + s.duration, type: "clip", title: "", subtitle: "" })), finale: { segments: ["c2"], from: 10.5, to: 20, video: "side", motion: "grow", grow: 0.8 }, measure: m }; + const g = runsFinaleGeometry(schedule, r); + assert.ok(g.height >= 200, `the layer has its room under the track (${g.height})`); + const { html } = runsFinaleHtml(schedule, r, { from: 10.5, to: 20 }, { fonts: {} }); + assert.match(html, /class="hol"/, "a retold weight hollow"); + assert.match(html, /class="ldr"/, "its leader to the day he said it"); + assert.match(html, /class="car"/, "a bound's caret"); + assert.match(html, /class="apx"/, "an about's ring"); + const off = runsFinaleHtml(schedule, renderOf({ railLabels: "sections", dietRuns: { weights: false } }), { from: 10.5, to: 20 }, { fonts: {} }).html; + assert.doesNotMatch(off, /class="hol"/); +}); diff --git a/umtool/report-to-video/shelf.test.mjs b/umtool/report-to-video/shelf.test.mjs @@ -10,10 +10,10 @@ import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { dietHtml, tagWords, tagWordSize } from "./chrome-measure-extras.mjs"; +import { dietHtml, goalsHtml, tagWords, tagWordSize } from "./chrome-measure-extras.mjs"; import { shelfHtml, shelfNoteGeometry } from "./chrome-shelf.mjs"; import { deckGeometry, entryShelfNotes, estimateSchedule, instrumentsGeometry, parseShelfNote, validateChrome } from "./deck.mjs"; -import { dietStates, measureExtraGeometry, measurePlacements, shelfLayout } from "./measure-extras.mjs"; +import { dietDays, dietStates, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs"; import { slotRect } from "./modules/layout.mjs"; import { moduleById, moduleProblems, scheduleSlices } from "./modules/index.mjs"; import { resolveMeasureExtra, validateMeasureExtra } from "./modules/measure-extras-settings.mjs"; @@ -202,3 +202,81 @@ test("the shelf's note: an entry's shelfNote over its span, only with the shelf assert.match(html, /Weighed in on camera/); assert.match(mod.check(s, renderOf(INSTRUMENTS)), /shelf region is off/); }); + +// --------------------------------------------------------------------------- +// THE FAN (operator, 6 Nov: "overlap cards like the goals do but to the side, we can keep the cards the same +// color ... a 'x days' number showing on the diet card"; "put the goal alongside this new diet hud space"). +// --------------------------------------------------------------------------- + +const FAN = { ...INSTRUMENTS, shelf: { items: ["diet", "goals"] }, diet: { position: "shelf", overlap: 0.6, days: true }, goals: { position: "shelf" }, streak: false }; + +test("overlap: the tags fan sideways, the width shrinking by what hides; capped where an older tag's word and date still show", () => { + assert.deepEqual(dietTagsBox(3), { width: 684, height: 116 }, "0: the row as it was"); + assert.deepEqual(dietTagsBox(3, 0.5), { width: 220 + 2 * 110, height: 116 }); + assert.deepEqual(dietTagsBox(3, 0.6, true), { width: 300 + 2 * 120, height: 116 }, "with the day count a tag is 300 wide"); + assert.match(validateMeasureExtra("diet", { overlap: 0.6 }).join(), /overlap 0\.6 hides an older tag's regime word and date: they need 110 of its 220 design px \(overlap at most 0\.5, or 0\.63 with days\)/); + assert.deepEqual(validateMeasureExtra("diet", { overlap: 0.6, days: true }), []); + assert.match(validateMeasureExtra("diet", { overlap: 0.9, days: true }).join(), /overlap must be from 0 to 0\.8/); + assert.match(validateMeasureExtra("diet", { days: "yes" }).join(), /days must be true or false/); + assert.deepEqual(validateChrome(renderOf(FAN).chrome, renderOf(FAN)), []); +}); + +test("the page: older tags behind the newest, their own colours (no dim), each with its strip; the newest lands like a goal note", () => { + const r = renderOf(FAN); + const { html, items } = dietHtml(schedule(), r, { fonts: {} }); + assert.match(html, /class="tg" data-k="t3" style="z-index:13"/, "the newer, the nearer"); + assert.match(html, /<div class="bk" data-k="t0\.b">/, "the strip an older tag shows"); + assert.ok(!/"k":"t\d+\.d","at":[\d.]+,"dur":[\d.]+,"from":\{"opacity":1\},"to":\{"opacity":0\.45/.test(html), "nothing dims"); + assert.match(html, /"to":\{"x":0,"y":-?\d+,"rotation":-?[\d.]+,"scale":1,"autoAlpha":1\},"ease":"back\.out\(1\.3\)"/, "the goal note's landing"); + assert.ok(items.length > 0); + // The region is the fan's, at the shelf's height. + assert.deepEqual(measureExtraGeometry("diet", r), { x: 24, y: 750, width: 540, height: 116 }); +}); + +test("days: the front tag's running count is the streak chain's day count, to the in-record date at the playhead", () => { + const withStreak = renderOf({ ...FAN, streak: { position: "bottom-center" } }); + const days = dietDays(schedule(), withStreak); + const { states } = streakStates(schedule(), withStreak); + for (const st of states.filter((x) => x.live)) { + const d = [...days].reverse().find((x) => x.at <= st.at + 1e-6); + assert.equal(d.days, st.live.days, `at ${st.at}`); + } + const { html } = dietHtml(schedule(), renderOf(FAN), { fonts: {} }); + assert.match(html, /<div class="dy" data-k="t\d+\.y\d+"><div class="dyn">\d+<\/div><div class="dyl">days?<\/div><\/div>/); + // Off (the default): no count, the tag as it was. + assert.doesNotMatch(dietHtml(schedule(), renderOf(SHELF), { fonts: {} }).html, /class="dy"/); +}); + +test("goals on the shelf: the count and the fanned notes, the fan taking the shelf's spare width", () => { + const r = renderOf(FAN); + assert.equal(goalsShelfWidth(4), GOALS_SHELF.count + GOALS_SHELF.gap + 250 + 3 * 110); + const L = shelfLayout(r); + assert.deepEqual(L.slots.diet, { x: 24, y: 750, width: 540, height: 116 }); + assert.deepEqual(L.slots.goals, { x: 24 + 540 + 16, y: 750, width: 1248 - 540 - 16, height: 116 }, "no gap at the shelf's end"); + assert.equal(resolveMeasureExtra("goals", r).hold, null, "on the shelf it stays up"); + const { html, items } = goalsHtml(schedule(), r, { fonts: {} }); + 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); + // 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", () => { + 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"); + 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); +});