// CLAIM GROUPS (lane L4, 2 Nov 2026): runs of clips inside a section that make // ONE claim -- "One of the ladies: 'I'm not a man'" is ow1 a01 b01 -- kept in // the manifest beside the timeline: // // "groups": [{ "id": "g7", "section": 1, "claim": "…", "ids": ["ow1", "a01", "b01"] }] // // The rules, each refused in words (validateGroups, one of structural()'s // checks) rather than repaired silently: // - a group's clips stand together: no other clip between them (a card // between two of them does not break the run); // - it sits in ONE section -- `section` is the index of the deck section // its clips are in (sectionEdit.mjs sectionModel; a subsection counts as a // section), never spanning a boundary; // - a clip is in at most one group; an id names a clip of the cut. // // The render never reads them: a manifest with `groups` builds exactly as the // same manifest without, until a group is PROMOTED (a level-2 marker at its // first clip, titled with its claim). A manifest without `groups` is never // touched by anything here. // // How the structure edits keep them (syncGroups, run by applyStructural after // every structural mutation, so every writer -- the Cut tab, Play's strip, the // CLI, a take's walk -- keeps the same rules): // - a clip REMOVED from the cut leaves its group, and a group left with no // clip goes (reanchorAfterRemove says so); // - a clip MOVED out of its group's run (not landing inside or at the edge // of the clips of its group that stayed) is detached from the group; // - a clip moved ALONE into the MIDDLE of a group's run -- strictly between // two of its clips -- JOINS that group (it stands inside the claim now; a // move to the edge of a run joins nothing). We chose joining over // refusing: a drag into a run is the gesture for "this belongs here too", // and a refusal would leave no way to say it but `groups set`; // - a WHOLE group moved (all its clips together: `groups move`, a group // bar's drag) keeps its clips; landing in the middle of another group is // refused ("…'s clips are not together"), never a merge; // - `section` follows the markers after every edit. // What moved is what the op says it moved (its result's `ids` or `id`), else // what is not in the longest common subsequence of the clip order before and // after. // // Pure: everything here mutates the manifest it is handed and returns words. // manifest.mjs runs the writers inside a structural write (the lock, the token, // the build's checks, the undo point). import { MARKER_LIMITS } from "umtool-report-to-video/marker-limits"; import { addSectionIn, reanchorMarkers, sectionModel, sectionWords } from "./sectionEdit.mjs"; /** A claim's characters, at most (one sentence: the bar shows it whole). */ export const GROUP_CLAIM_MAX = 160; /** The keys a group carries, and nothing else. */ export const GROUP_KEYS = Object.freeze(["id", "section", "claim", "ids"]); const GROUP_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); // A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows. const isClip = (e) => !!e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); const quoted = (s, n = 48) => { const t = String(s ?? ""); return `"${t.length > n ? `${t.slice(0, n - 1)}…` : t}"`; }; /** `g7 ("One of the ladies…")` -- how a sentence names a group. */ export const groupWords = (g) => `${g?.id ?? "a group"}${typeof g?.claim === "string" && g.claim ? ` (${quoted(g.claim)})` : ""}`; /** Does this manifest carry groups at all? (`[]` counts: the key is there.) */ export const hasGroups = (m) => Array.isArray(m?.groups); /** The cut's clip ids in order, each once (a variant twin counts where it first stands, as sectionModel does). */ export function clipOrder(m) { const seen = new Set(); const out = []; for (const e of Array.isArray(m?.timeline) ? m.timeline : []) { if (!isClip(e) || typeof e.id !== "string" || seen.has(e.id)) continue; seen.add(e.id); out.push(e.id); } return out; } /** An id not yet a group's: `g`. */ export function freshGroupId(groups) { const ids = new Set((groups ?? []).map((g) => g?.id)); for (let n = 1; ; n += 1) if (!ids.has(`g${n}`)) return `g${n}`; } /** * Every reason the cut's groups are wrong, in sentences ([] without `groups`). * One of structural()'s checks (manifest.mjs structureErrors): an edit is * refused only for what it breaks. * * @param {Record} m * @returns {string[]} */ export function validateGroups(m) { if (m?.groups === undefined) return []; if (!Array.isArray(m.groups)) return ["groups must be a list of {id, section, claim, ids}"]; const errors = []; const order = clipOrder(m); const pos = new Map(order.map((id, k) => [id, k])); const model = sectionModel(m); const owner = new Map(); const ids = new Set(); m.groups.forEach((g, k) => { const W = `groups[${k}]`; if (!isObj(g)) { errors.push(`${W} must be {id, section, claim, ids}`); return; } const name = typeof g.id === "string" ? groupWords(g) : W; const extra = Object.keys(g).filter((x) => !GROUP_KEYS.includes(x)); if (extra.length) errors.push(`${name}: unknown key${extra.length === 1 ? "" : "s"} ${extra.join(", ")} (a group is ${GROUP_KEYS.join(", ")})`); if (typeof g.id !== "string" || !GROUP_ID_RE.test(g.id)) errors.push(`${W}.id must be letters, digits, - or _ (at most 64)`); else if (ids.has(g.id)) errors.push(`group id ${g.id} is used twice`); else ids.add(g.id); if (typeof g.claim !== "string" || !g.claim.trim()) errors.push(`${name} needs its claim, in words`); else if ([...g.claim].length > GROUP_CLAIM_MAX) errors.push(`${name}: a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...g.claim].length})`); if (!Array.isArray(g.ids) || !g.ids.length) { errors.push(`${name} needs its clips (ids, at least one)`); return; } const mine = []; for (const id of g.ids) { if (typeof id !== "string" || !id) { errors.push(`${name}: every id is a clip's id`); continue; } if (!pos.has(id)) { errors.push(`${name} names ${id}, which is not a clip of the cut`); continue; } if (owner.has(id)) { errors.push(`${id} is in two groups: ${owner.get(id)} and ${g.id}`); continue; } owner.set(id, g.id); mine.push(id); } if (!mine.length) return; const at = mine.map((id) => pos.get(id)).sort((a, b) => a - b); const lo = at[0]; const hi = at[at.length - 1]; if (hi - lo + 1 !== at.length) { const between = order.slice(lo, hi + 1).filter((id) => !mine.includes(id)); errors.push(`${name}'s clips are not together: ${between.join(", ")} stand${between.length === 1 ? "s" : ""} between ${order[lo]} and ${order[hi]}`); return; } const secs = [...new Set(mine.map((id) => model.sectionOf.get(id)))].sort((a, b) => a - b); if (secs.length > 1) { errors.push(`${name} spans ${secs.map((s) => sectionWords(model.sections[s])).join(" and ")}: a group never crosses a section boundary`); return; } if (g.section !== secs[0]) { errors.push(`${name}'s section is ${JSON.stringify(g.section ?? null)}, but its clips are in ${sectionWords(model.sections[secs[0]])}`); } }); return errors; } /** * The ids that kept their order: the longest common subsequence of two id * lists, a group's clip counting a little more than a loose one -- so when a * loose clip and a grouped one could each be the one that moved (a swap), the * loose one moved. Past ~4 million cells nothing is called moved. */ function lcsKept(a, b, member) { const n = a.length; const m = b.length; if (n * m > 4_000_000) return new Set(a); const w = (id) => (member.has(id) ? 1001 : 1000); const L = Array.from({ length: n + 1 }, () => new Float64Array(m + 1)); for (let i = n - 1; i >= 0; i -= 1) { for (let j = m - 1; j >= 0; j -= 1) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + w(a[i]) : Math.max(L[i + 1][j], L[i][j + 1]); } const kept = new Set(); for (let i = 0, j = 0; i < n && j < m; ) { if (a[i] === b[j]) { kept.add(a[i]); i += 1; j += 1; } else if (L[i + 1][j] >= L[i][j + 1]) i += 1; else j += 1; } return kept; } /** * After a structural edit: the groups follow the cut (the rules at the top). * `before` is the clip order before the edit (clipOrder); `moved`, when the op * says, the ids it moved (else the ones out of the longest common * subsequence). `rebuilt`: the op wrote the groups itself (import, set, …): * only `section` and the order of each group's ids are recomputed. Mutates * `m`; returns one sentence per change. A manifest without `groups` is never * touched. * * @param {Record} m * @param {string[]} before * @param {{ moved?: Iterable | null, rebuilt?: boolean }} [opts] * @returns {string[]} */ export function syncGroups(m, before, { moved = null, rebuilt = false } = {}) { if (!hasGroups(m)) return []; const notes = []; const order = clipOrder(m); const pos = new Map(order.map((id, k) => [id, k])); const valid = m.groups.filter((g) => isObj(g) && Array.isArray(g.ids)); if (!rebuilt) { const was = new Set(before); let mv; if (moved) { mv = new Set([...moved].filter((id) => pos.has(id))); } else { const member = new Set(valid.flatMap((g) => g.ids)); const kept = lcsKept(before.filter((id) => pos.has(id)), order.filter((id) => was.has(id)), member); mv = new Set(order.filter((id) => was.has(id) && !kept.has(id))); } for (const id of order) if (!was.has(id)) mv.add(id); // A clip that left the cut leaves its group (reanchorAfterRemove already said so for a removal). for (const g of valid) { const gone = g.ids.filter((id) => typeof id === "string" && !pos.has(id)); if (gone.length) { g.ids = g.ids.filter((id) => !gone.includes(id)); notes.push(`group ${groupWords(g)}: ${gone.join(", ")} left the cut`); } } const ownerOf = new Map(); for (const g of valid) for (const id of g.ids) ownerOf.set(id, g); // A whole group moved: every clip it has moved with the edit. const wholeMoved = new Set(valid.filter((g) => g.ids.length && g.ids.every((id) => mv.has(id)))); // JOIN: a clip moved alone that lands strictly between two clips of a group that stayed. for (const id of order) { if (!mv.has(id)) continue; const own = ownerOf.get(id); if (own && wholeMoved.has(own)) continue; const p = pos.get(id); for (const g of valid) { if (g === own || wholeMoved.has(g)) continue; const stay = g.ids.filter((x) => !mv.has(x)).map((x) => pos.get(x)); if (stay.length < 2 || !(Math.min(...stay) < p && p < Math.max(...stay))) continue; if (own) { own.ids = own.ids.filter((x) => x !== id); notes.push(`${id} left group ${groupWords(own)}`); } g.ids.push(id); ownerOf.set(id, g); notes.push(`${id} joined group ${groupWords(g)}: it was moved into the middle of its run`); break; } } // DETACH: a moved clip that is no longer with the clips of its group that stayed. for (const g of valid) { if (!g.ids.length) continue; const at = (x) => pos.get(x); const stay = g.ids.filter((x) => !mv.has(x)); let keep; if (!stay.length) { // The whole group moved: its largest run of clips together is the group. const runs = runsOf(g.ids.map(at).sort((a, b) => a - b)); keep = new Set(runs.sort((a, b) => b.length - a.length)[0].map((k) => order[k])); } else { const s = stay.map(at).sort((a, b) => a - b); let lo = s[0]; let hi = s[s.length - 1]; const mine = new Set(g.ids.map(at)); // The stayed clips' span, grown by the moved ones that stand right at its edges. while (mine.has(lo - 1)) lo -= 1; while (mine.has(hi + 1)) hi += 1; keep = new Set(g.ids.filter((x) => at(x) >= lo && at(x) <= hi)); } const off = g.ids.filter((x) => !keep.has(x)); if (off.length) { g.ids = g.ids.filter((x) => keep.has(x)); notes.push(`${off.join(", ")} ${off.length === 1 ? "was" : "were"} moved out of group ${groupWords(g)}'s run: detached from it`); } } } // An emptied group goes; each group's ids in cut order; its section from the markers. const model = sectionModel(m); m.groups = m.groups.filter((g) => { if (!isObj(g) || !Array.isArray(g.ids)) return true; if (g.ids.length) return true; notes.push(`group ${groupWords(g)} dropped: no clip of it is left`); return false; }); for (const g of m.groups) { if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) continue; if (g.ids.every((id) => pos.has(id))) g.ids.sort((a, b) => pos.get(a) - pos.get(b)); const first = g.ids.find((id) => pos.has(id)); const s = first === undefined ? undefined : model.sectionOf.get(first); if (s !== undefined) g.section = s; } return notes; } /** Maximal runs of consecutive integers in a sorted list. */ function runsOf(sorted) { const runs = []; for (const k of sorted) { const r = runs[runs.length - 1]; if (r && r[r.length - 1] === k - 1) r.push(k); else runs.push([k]); } return runs; } /** * Clip `id` left the cut: it leaves its group, and a group with no clip left * goes. Returns one sentence per change (reanchorAfterRemove's). */ export function dropFromGroups(m, id) { if (!hasGroups(m)) return []; const notes = []; m.groups = m.groups.filter((g) => { if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.includes(id)) return true; g.ids = g.ids.filter((x) => x !== id); if (g.ids.length) { notes.push(`group ${groupWords(g)}: ${id} dropped from it`); return true; } notes.push(`group ${groupWords(g)} dropped: ${id} was its only clip`); return false; }); return notes; } /** After a split of `firstId`: the second half is in the first half's group too. */ export function followSplitGroups(m, firstId, secondId) { if (!hasGroups(m)) return []; const g = m.groups.find((x) => isObj(x) && Array.isArray(x.ids) && x.ids.includes(firstId)); if (!g) return []; g.ids.splice(g.ids.indexOf(firstId) + 1, 0, secondId); return [`${secondId} is in group ${groupWords(g)}, as ${firstId} is`]; } /** * The groups as the Cut tab, the strip and `groups ls` show them, in cut * order: `{ id, claim, ids, section, words (the section's), index, first, * last, at (the first clip's index in the timeline), promoted }` -- * `promoted` when a level-2 marker opens at its first clip (its claim a * subsection's title). * * @param {Record} m */ export function groupModel(m) { if (!hasGroups(m)) return []; const model = sectionModel(m); const tl = Array.isArray(m.timeline) ? m.timeline : []; const at = new Map(); tl.forEach((e, i) => { if (isClip(e) && !at.has(e.id)) at.set(e.id, i); }); const opensAt = new Map(model.sections.filter((s) => s.marker !== null).map((s) => [s.first, s])); return m.groups .filter((g) => isObj(g) && Array.isArray(g.ids) && g.ids.some((id) => at.has(id))) .map((g) => { const ids = g.ids.filter((id) => at.has(id)); const first = ids.reduce((a, b) => (at.get(b) < at.get(a) ? b : a)); const last = ids.reduce((a, b) => (at.get(b) > at.get(a) ? b : a)); const s = model.sectionOf.get(first) ?? 0; const opens = opensAt.get(first); return { id: String(g.id), claim: typeof g.claim === "string" ? g.claim : "", ids, section: s, words: sectionWords(model.sections[s] ?? model.sections[0]), first, last, at: at.get(first), promoted: !!opens && opens.level === 2 && opens.index === s, }; }) .sort((a, b) => a.at - b.at) .map((g, index) => ({ ...g, index })); } // ---- the writers (each run inside a structural write by manifest.mjs) ----- // // Each returns `{ …, groupsWritten: true }` when it wrote the groups itself, // so syncGroups only recomputes their sections after it. function needGroup(m, gid) { const g = hasGroups(m) ? m.groups.find((x) => isObj(x) && x.id === gid) : null; if (!g) throw new Error(`no group ${gid}${hasGroups(m) && m.groups.length ? ` (${m.groups.map((x) => x?.id).join(", ")})` : " (the cut has no groups)"}`); return g; } const claimOf = (v) => { const c = typeof v === "string" ? v.trim().replace(/\s+/g, " ") : ""; if (!c) throw new Error("a group needs its claim, in words"); if ([...c].length > GROUP_CLAIM_MAX) throw new Error(`a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...c].length})`); return c; }; /** * SET: group `gid` is clips `ids` now (a new group when there is none by that * id, or `gid` null/"-": a fresh `g`). The clips must already stand * together in one section -- reorder first (`order`, `place`); a clip in * another group leaves it (that group must stay together, or it is refused). * * @param {Record} m * @param {string | null} gid * @param {string[]} ids * @param {{ claim?: string | null }} [opts] */ export function setGroupIn(m, gid, ids, { claim = null } = {}) { if (!hasGroups(m)) m.groups = []; const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))]; if (!want.length) throw new Error("name the group's clips"); const order = clipOrder(m); for (const id of want) if (!order.includes(id)) throw new Error(`${id} is not a clip of the cut`); const fresh = !gid || gid === "-" ? freshGroupId(m.groups) : String(gid).trim(); if (!GROUP_ID_RE.test(fresh)) throw new Error("a group id is letters, digits, - or _ (at most 64)"); let g = m.groups.find((x) => isObj(x) && x.id === fresh); const created = !g; if (!g) { g = { id: fresh, section: 0, claim: claimOf(claim), ids: [] }; m.groups.push(g); } else if (claim !== null && claim !== undefined) g.claim = claimOf(claim); const notes = []; for (const o of m.groups) { if (o === g || !isObj(o) || !Array.isArray(o.ids)) continue; const taken = o.ids.filter((x) => want.includes(x)); if (!taken.length) continue; o.ids = o.ids.filter((x) => !want.includes(x)); notes.push(`${taken.join(", ")} left group ${groupWords(o)}`); } const was = g.ids.slice(); g.ids = want; m.groups = m.groups.filter((o) => { if (o === g || !isObj(o) || !Array.isArray(o.ids) || o.ids.length) return true; notes.push(`group ${groupWords(o)} dropped: no clip of it is left`); return false; }); return { id: g.id, created, ids: g.ids.slice(), was, claim: g.claim, notes, groupsWritten: true }; } /** LABEL: group `gid`'s claim. */ export function labelGroupIn(m, gid, claim) { const g = needGroup(m, gid); const was = g.claim; g.claim = claimOf(claim); if (was === g.claim) throw new Error(`${gid}'s claim is already ${quoted(g.claim)}`); return { id: g.id, claim: g.claim, was, groupsWritten: true }; } /** REMOVE (ungroup): group `gid` goes; its clips stay where they are. */ export function removeGroupIn(m, gid) { const g = needGroup(m, gid); m.groups = m.groups.filter((x) => x !== g); return { id: g.id, removed: { ...g }, groupsWritten: true }; } /** * MOVE A WHOLE GROUP: its clips, together, to another place among the groups * -- `to` its index among the groups AFTER the move (0 first: right before the * group now at that index, in its section; the number of the others: after the * last), or `after` another group (right after its last clip, in its section). * The markers follow so every other clip keeps its section (sectionEdit.mjs * placeIn); a section left with no clip is refused. * * @param {Record} m * @param {string} gid * @param {{ to?: number | null, after?: string | null }} where * @param {(m: Record, ids: string[], o: { before: string | null, section: number | null }) => Record} place sectionEdit.mjs placeIn */ export function moveGroupIn(m, gid, { to = null, after = null } = {}, place) { needGroup(m, gid); const all = groupModel(m); const me = all.find((g) => g.id === gid); if (!me) throw new Error(`group ${gid} names no clip of the cut`); const others = all.filter((g) => g.id !== gid); const tl = m.timeline; const after1 = (clipId) => { // The entry right after `clipId` that is not one of the group's own. const i = tl.findIndex((e) => e?.id === clipId); const next = tl.slice(i + 1).find((e) => !me.ids.includes(e?.id)); return next ? next.id : null; }; let before; let section; let words; if (after !== null && after !== undefined && after !== "") { const o = others.find((g) => g.id === after); if (!o) throw new Error(after === gid ? `${gid} cannot go after itself` : `no other group ${after}`); before = after1(o.last); section = o.section; words = `after ${groupWords(o)}`; } else { const k = Number(to); if (!Number.isInteger(k) || k < 0 || k > others.length) throw new Error(`--to is a group's place, 0–${others.length} (\`groups ls\` lists them)`); if (k === others.length) { const o = others[others.length - 1]; if (!o) throw new Error("there is no other group to move it among"); before = after1(o.last); section = o.section; words = `after ${groupWords(o)}, the last`; } else { const o = others[k]; before = o.first; section = o.section; words = `before ${groupWords(o)}`; } } const r = place(m, me.ids, { before, section: deckSections(m) ? section : null }); return { id: gid, ids: me.ids, words, section: r.section, before: r.before, reanchored: r.reanchored ?? [], from: me.index }; } const deckSections = (m) => isObj(m?.render?.chrome); /** * PROMOTE: the group opens a SUBSECTION -- a level-2 marker right before its * first clip (after the clip before it), titled with its claim (`label`, when * the claim is longer than a marker's label may be). The render changes from * here on: the rail gets the subsection's tick, the section title its * "Section › claim". Refused when no clip comes before it, when a section * already opens there, and by the deck's own checks (the cut's first marker * must be a section: a group in §0 opens none). * * @param {Record} m * @param {string} gid * @param {{ label?: string | null }} [opts] */ export function promoteGroupIn(m, gid, { label = null } = {}) { const g = needGroup(m, gid); const me = groupModel(m).find((x) => x.id === gid); if (!me) throw new Error(`group ${gid} names no clip of the cut`); const text = typeof label === "string" && label.trim() ? label.trim() : String(g.claim ?? "").trim(); if ([...text].length > MARKER_LIMITS.label) { throw new Error(`${groupWords(g)}: a marker's label is at most ${MARKER_LIMITS.label} characters and ${label ? "this one" : "the claim"} is ${[...text].length} — give the subsection a shorter title (--label)`); } const tl = m.timeline; const i = tl.findIndex((e) => e?.id === me.first); const prev = [...tl.slice(0, i)].reverse().find(isClip); if (!prev) throw new Error(`${groupWords(g)} opens the cut: no clip before it for a marker to follow`); if (me.promoted) throw new Error(`${groupWords(g)} already opens a subsection`); const model = sectionModel(m); const opens = model.sections.find((s) => s.marker !== null && s.first === me.first); if (opens) throw new Error(`${groupWords(g)} already opens ${sectionWords(opens)}: a marker is there`); const r = addSectionIn(m, prev.id, { label: text, level: 2 }); return { id: gid, marker: r.marker, after: prev.id, label: text, opens: me.first, within: sectionWords(model.sections[me.section]) }; } // ---- import (the shape of a claim-groups.json) and order -------------------- const norm = (s) => String(s ?? "").normalize("NFKC").toLowerCase().replace(/[‐-―]/g, "-").replace(/\s+/g, " ").trim(); /** * A claim-groups file: `{ sections: [{ label, groups: [{ claim, ids[] }] }] }`. * Checked, never repaired: the shape, every claim, every id once. * * @param {unknown} doc * @returns {{ sections: Array<{ label: string | null, groups: Array<{ claim: string, ids: string[] }> }> }} */ export function parseGroupsDoc(doc) { if (!isObj(doc) || !Array.isArray(doc.sections)) throw new Error("a groups file is {sections: [{label, groups: [{claim, ids}]}]}"); const seen = new Map(); const sections = doc.sections.map((s, k) => { if (!isObj(s) || !Array.isArray(s.groups)) throw new Error(`sections[${k}] is {label, groups: [{claim, ids}]}`); const label = typeof s.label === "string" && s.label.trim() ? s.label.trim() : null; const groups = s.groups.map((g, j) => { const W = `sections[${k}].groups[${j}]`; if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) throw new Error(`${W} is {claim, ids: [clip ids]}`); let claim; try { claim = claimOf(g.claim); } catch (e) { throw new Error(`${W}: ${e instanceof Error ? e.message : e}`); } const ids = g.ids.map((x) => String(x ?? "").trim()); for (const id of ids) { if (!id) throw new Error(`${W}: an empty id`); if (seen.has(id)) throw new Error(`${id} is named twice in the file (${seen.get(id)} and ${W})`); seen.set(id, W); } return { claim, ids }; }); return { label, groups }; }); return { sections }; } /** * IMPORT a claim-groups file in ONE edit: the timeline re-ordered to the * file's, its groups the cut's groups (the old ones replaced), the markers * re-anchored around the new order. * * Each of the file's sections is one of the deck's: the section of the same * name (case and dashes aside), else -- a file section the deck has no name * for ("As a woman" inside the opening) -- the section most of its clips are * in now, kept in order between its neighbours. Several file sections may be * one deck section; they never come out of order (refused). A clip the file * does not name stays in its section, after the file's clips. Refused unless * told otherwise: an id the cut does not have (`skipMissing`: left out, and * said), a section left with no clip (`dropEmpty`: its marker removed, and * said; the opening, which has no marker, is never dropped). * * @param {Record} m * @param {unknown} doc * @param {{ skipMissing?: boolean, dropEmpty?: boolean }} [opts] */ export function importGroupsIn(m, doc, { skipMissing = false, dropEmpty = false } = {}) { const file = parseGroupsDoc(doc); const tl = Array.isArray(m.timeline) ? m.timeline : (m.timeline = []); const present = new Set(clipOrder(m)); const named = file.sections.flatMap((s) => s.groups.flatMap((g) => g.ids)); const missing = named.filter((id) => !present.has(id)); if (missing.length && !skipMissing) { throw new Error(`the file names ${missing.length} clip${missing.length === 1 ? "" : "s"} the cut does not have: ${missing.join(", ")} — pass --skip-missing to leave ${missing.length === 1 ? "it" : "them"} out`); } const notes = []; if (missing.length) notes.push(`left out (not clips of the cut): ${missing.join(", ")}`); const model = sectionModel(m); const deck = model.sections; // ---- each file section to a deck section ---- const live = file.sections.map((s) => ({ ...s, groups: s.groups.map((g) => ({ ...g, ids: g.ids.filter((id) => present.has(id)) })).filter((g) => g.ids.length) })); const byLabel = (label, from) => (label === null ? -1 : deck.findIndex((d, k) => k >= from && d.label !== null && norm(d.label) === norm(label))); const mapped = live.map(() => /** @type {number | null} */ (null)); let floor = 0; live.forEach((s, k) => { if (!s.groups.length) return; const hit = byLabel(s.label, floor); if (hit < 0) { const earlier = byLabel(s.label, 0); if (earlier < 0) return; const prevK = mapped.findLastIndex((x) => x !== null && x > earlier); throw new Error(`the file's sections are out of the cut's order: "${s.label}" (${sectionWords(deck[earlier])}) comes after "${live[prevK]?.label}" (${sectionWords(deck[mapped[prevK]])})`); } mapped[k] = hit; floor = hit; }); live.forEach((s, k) => { if (!s.groups.length || mapped[k] !== null) return; const lo = mapped.slice(0, k).reduce((a, x) => (x === null ? a : x), 0); const hiK = mapped.findIndex((x, j) => j > k && x !== null); const hi = hiK < 0 ? deck.length - 1 : mapped[hiK]; const count = new Map(); for (const g of s.groups) for (const id of g.ids) count.set(model.sectionOf.get(id), (count.get(model.sectionOf.get(id)) ?? 0) + 1); const most = [...count.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0]; const at = Math.min(hi, Math.max(lo, most)); mapped[k] = at; notes.push(`"${s.label ?? `section ${k + 1}`}" → ${sectionWords(deck[at])}: the deck has no section of that name; ${at === most ? "most of its clips are there" : "the nearest in order to where its clips are"}`); }); // ---- each deck section's clips: the file's (in its order), then the ones it does not name ---- const fileIds = new Set(named.filter((id) => present.has(id))); const into = deck.map(() => /** @type {string[]} */ ([])); live.forEach((s, k) => { for (const g of s.groups) into[mapped[k]].push(...g.ids); }); const unnamed = clipOrder(m).filter((id) => !fileIds.has(id)); for (const id of unnamed) into[model.sectionOf.get(id)].push(id); if (unnamed.length) notes.push(`not in the file, kept at the end of their sections: ${unnamed.join(", ")}`); const empty = deck.filter((d) => !into[d.index].length); if (empty.some((d) => d.index === 0)) throw new Error(`the opening (§0) would have no clip: the file's first section is ${sectionWords(deck[mapped.find((x) => x !== null) ?? 0])} — the opening has no marker to remove`); if (empty.length && !dropEmpty) { throw new Error(`the file leaves ${empty.map((d) => sectionWords(d)).join(", ")} with no clip (the file has no section of that name, and puts its clips in others) — pass --drop-empty to remove ${empty.length === 1 ? "its marker" : "their markers"}`); } // ---- the new timeline: the clips in that order, a card after the clip it followed ---- const newClips = into.flat(); const byId = new Map(); const cardsAfter = new Map(); let lead = []; let lastClip = null; for (const e of tl) { if (isClip(e) && !byId.has(e.id)) { byId.set(e.id, [e]); lastClip = e.id; } else if (isClip(e)) byId.get(e.id).push(e); else if (lastClip === null) lead.push(e); else cardsAfter.set(lastClip, [...(cardsAfter.get(lastClip) ?? []), e]); } const before = tl.map((e) => e?.id).join("\n"); const next = [...lead]; for (const id of newClips) next.push(...byId.get(id), ...(cardsAfter.get(id) ?? [])); tl.splice(0, tl.length, ...next); // ---- the markers: each kept section opens after the last clip of the kept one before it ---- const markers = m.render?.chrome?.deck?.markers; const moved = []; if (Array.isArray(markers)) { const kept = deck.filter((d) => into[d.index].length); for (let k = 1; k < kept.length; k += 1) { const mk = markers[kept[k].marker]; const after = into[kept[k - 1].index][into[kept[k - 1].index].length - 1]; if (mk.after !== after) { moved.push(`marker ${kept[k].marker}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${mk.after} to after ${after}`); mk.after = after; } } const drop = new Set(empty.map((d) => markers[d.marker])); for (const d of empty) notes.push(`${sectionWords(d)} removed: the file has no section of that name and puts all its clips in others`); m.render.chrome.deck.markers = markers.filter((mk) => !drop.has(mk)); } // ---- the groups: the file's, in its order ---- const old = hasGroups(m) ? m.groups.length : 0; const groups = []; for (const s of live) for (const g of s.groups) groups.push({ id: `g${groups.length + 1}`, section: 0, claim: g.claim, ids: g.ids }); m.groups = groups; const skippedGroups = file.sections.reduce((n, s) => n + s.groups.length, 0) - groups.length; if (skippedGroups) notes.push(`${skippedGroups} group${skippedGroups === 1 ? "" : "s"} left out: none of ${skippedGroups === 1 ? "its" : "their"} clips is in the cut`); return { groups: groups.length, replaced: old, // Each file section's deck section, numbered as the cut is now (after any section dropped). sections: live.map((s, k) => ({ label: s.label, section: mapped[k] === null ? null : mapped[k] - empty.filter((d) => d.index < mapped[k]).length, groups: s.groups.length })), moved: before !== tl.map((e) => e?.id).join("\n"), missing, dropped: empty.map((d) => ({ index: d.index, label: d.label })), reanchored: moved, notes, groupsWritten: true, }; } /** * ORDER: the named entries take the places the named entries hold now, in the * order given; every other entry stays where it is (name them all for the * whole order). Each clip keeps its section -- the markers are re-anchored -- * so an order that puts a clip among another section's is refused (move it * across with `place` or `section-move`). The groups follow (syncGroups). * * @param {Record} m * @param {string[]} ids */ export function orderIn(m, ids) { const tl = Array.isArray(m.timeline) ? m.timeline : []; const want = (Array.isArray(ids) ? ids : []).map((x) => String(x ?? "").trim()).filter(Boolean); if (!want.length) throw new Error("order needs the entries' ids, in their new order"); const seen = new Set(); for (const id of want) { if (seen.has(id)) throw new Error(`${id} is named twice`); seen.add(id); const n = tl.filter((e) => e?.id === id).length; if (!n) throw new Error(`no timeline entry with id ${id}`); if (n > 1) throw new Error(`${id} is in the timeline ${n} times — order one twin with \`timeline move\``); } const slots = []; tl.forEach((e, i) => { if (seen.has(e?.id)) slots.push(i); }); const byId = new Map(tl.map((e) => [e?.id, e])); const before = tl.map((e) => e?.id).join("\n"); const next = tl.slice(); slots.forEach((slot, k) => { next[slot] = byId.get(want[k]); }); const model = sectionModel(m); let reanchored = []; if (Array.isArray(m.render?.chrome?.deck?.markers) && model.sections.length > 1) { // Every clip in its own section: the sections must still follow one another. let prev = 0; let prevId = null; for (const e of next) { if (!isClip(e)) continue; const s = model.sectionOf.get(e.id); if (s < prev) { throw new Error(`${e.id} (${sectionWords(model.sections[s])}) would stand after ${prevId} (${sectionWords(model.sections[prev])}): order keeps every clip in its section — move it across with place or section-move`); } prev = s; prevId = e.id; } tl.splice(0, tl.length, ...next); reanchored = reanchorMarkers(m, model, new Map(model.sectionOf)); } else { tl.splice(0, tl.length, ...next); } if (before === tl.map((e) => e?.id).join("\n") && !reanchored.length) throw new Error("that is the order the cut already has"); // `named`, not `ids`: what moved is what the order changed (syncGroups' common subsequence), not every id named. return { named: want, count: want.length, of: tl.length, reanchored }; } /** * An order as a file or the words of a command: a JSON list of ids, `{order: * […]}`, `{timeline: [{id}…]}`, a claim-groups file (its ids in order), or ids * separated by spaces, commas or lines. * * @param {string} text * @returns {string[]} */ export function parseOrderText(text) { const t = String(text ?? "").trim(); if (!t) return []; if (/^[[{]/.test(t)) { let j; try { j = JSON.parse(t); } catch (e) { throw new Error(`not JSON (${e instanceof Error ? e.message : e})`); } if (Array.isArray(j)) return j.map(String); if (isObj(j) && Array.isArray(j.order)) return j.order.map(String); if (isObj(j) && Array.isArray(j.timeline)) return j.timeline.map((e) => String(isObj(e) ? e.id : e)); if (isObj(j) && Array.isArray(j.sections)) return parseGroupsDoc(j).sections.flatMap((s) => s.groups.flatMap((g) => g.ids)); throw new Error("an order is a list of ids, {order: […]}, {timeline: [{id}…]} or a claim-groups file"); } return t.split(/[\s,]+/).filter(Boolean); }