Archilyzer · Source

archilyzer

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

commit 9443a9bf1810037fa644d30567d2b467065b0471
parent 7a0b9431f899fa9a18221c8b39584d141ce17377
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 10:44:10 -0400

deck markers: a label's align, and crowded labels staggered into two rows

render.chrome.deck.markers[].align: "auto" (as ever) | "left" (the label
starts at its flag) | "right" (ends at it) | "center"; a label reading away
from a neighbour lets that neighbour's reach up to its flag.
render.chrome.deck.markerLayout: "stagger" (default) | "truncate". When a
label would not fit its box (markerLabelWidth, a little over Fira Sans
Bold's measured advances at 18 px), the flags are split between two rows --
every split tried, the most labels fitting wins -- the band grows by
MARKER_ROW and the track and body move down by it; row 1's flags carry a
stick up to their labels and row 0's labels keep 8 px clear of those sticks.
A label that still does not fit is ellipsized, as in one row. A row that
fits is laid byte for byte as before. deckLayout takes the schedule to know
(compose-chrome and the deck page pass it, so the QR is made at its size).

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

Diffstat:
Mumtool/report-to-video/chrome-deck.mjs | 23+++++++++++++++--------
Mumtool/report-to-video/compose-chrome.mjs | 3++-
Aumtool/report-to-video/deck-markers-layout.test.mjs | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
4 files changed, 342 insertions(+), 33 deletions(-)

diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -37,7 +37,7 @@ // second clock or a label. import { fileURLToPath } from "node:url"; -import { deckChoreography, deckLayout, deckMarkers, pageDuration, pipSegments, pipXs, resolveDeck } from "./deck.mjs"; +import { deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck } from "./deck.mjs"; import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyOf, VERDICT_SHAPES } from "./factcheck.mjs"; /** @@ -146,7 +146,7 @@ const keyOf = (i, part) => (part === "seg" ? `s${i}` : `s${i}.${part}`); export function deckCues(schedule, render) { const deck = resolveDeck(render); const tally = tallyOf(schedule, render); - const lay = deckLayout(render, { tally }); + const lay = deckLayout(render, { tally, schedule }); const segs = schedule.segments; const ch = deckChoreography(schedule, render); const pipped = pipSegments(schedule); @@ -362,7 +362,7 @@ export function subtitleMarkup(text) { export function deckHtml(schedule, render, opts = {}) { const deck = resolveDeck(render); const tally = tallyOf(schedule, render); - const lay = deckLayout(render, { tally }); + const lay = deckLayout(render, { tally, schedule }); const pal = render.palette; const W = lay.width, H = lay.height; const fonts = opts.fonts ?? {}; @@ -437,16 +437,20 @@ export function deckHtml(schedule, render, opts = {}) { .join(""); // The markers: a flag on the track and its label in the band above it. const band = lay.markerBand ?? null; + // Staggered (deckMarkers `row`): row 1's flags carry a taller stick up to + // their labels, a row above row 0's. A label's `align` sets its text's side. const markerHtml = markers .map((mk, j) => { const left = r4(mk.box[0] - mk.x); + const side = mk.align === "left" || mk.align === "right" ? `; text-align:${mk.align}` : ""; return ( - `<div class="mflag" data-k="mk${j}" data-after="${esc(mk.after)}" style="left:${r4(mk.x)}px; --mc:${esc(mk.color)}">` + + `<div class="mflag${mk.row === 1 ? " up" : ""}" data-k="mk${j}" data-after="${esc(mk.after)}" style="left:${r4(mk.x)}px; --mc:${esc(mk.color)}">` + `<div class="mstick"></div><div class="mhead"></div>` + - `<div class="mlabel" style="left:${left}px; width:${mk.box[1] - mk.box[0]}px">${esc(mk.label)}</div></div>` + `<div class="mlabel" style="left:${left}px; width:${mk.box[1] - mk.box[0]}px${side}">${esc(mk.label)}</div></div>` ); }) .join(""); + const staggered = (band?.rows ?? 1) > 1; // The tally: one cell per verdict the cut stamps, each with every count it // will show stacked in one box (`n0` … `n<final>`), its label under it. const tb = lay.tally ?? null; @@ -615,10 +619,13 @@ export function deckHtml(schedule, render, opts = {}) { .mstick { position: absolute; left: -1.5px; top: -14px; width: 3px; height: 20px; border-radius: 1.5px; background: var(--mc); } .mhead { position: absolute; left: 1.5px; top: -14px; width: 12px; height: 10px; background: var(--mc); clip-path: polygon(0% 0%, 100% 50%, 0% 100%); } - .mlabel { position: absolute; top: ${(band?.y ?? 3) - tr.y}px; height: 20px; text-align: center; white-space: nowrap; - overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: 18px; + .mlabel { position: absolute; top: ${(band?.y ?? 3) + (staggered ? MARKER_ROW : 0) - tr.y}px; height: 20px; text-align: center; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: ${MARKER_LABEL_SIZE}px; line-height: 20px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--mc); - text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); }` : ""} + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); }` : ""}${staggered ? ` + /* Staggered labels: row 1 a row above, its flag's stick up to it. */ + .mflag.up .mlabel { top: ${band.y - tr.y}px; } + .mflag.up .mstick { top: ${band.y + 20 - tr.y}px; height: ${tr.y + 6 - (band.y + 20)}px; }` : ""} .deck-qr img { display: block; width: ${qr?.size ?? 0}px; height: ${qr?.size ?? 0}px; border-radius: 6px; image-rendering: pixelated; backface-visibility: hidden; box-shadow: 0 0 0 1px ${rgba(pal.fg, 0.25)}, 0 6px 18px rgba(0, 0, 0, 0.35); } diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -748,7 +748,8 @@ async function regionHtml(region, { manifest, manifestDir, base, projDir, assets if (region === "deck") { const render = manifest.render; const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - const lay = deckLayout(render); + // With the schedule: a staggered marker band moves the QR down and may shrink it. + const lay = deckLayout(render, { schedule }); const qrSrcs = {}; if (lay.qr) { const byUrl = await qrPngsFor(schedule.segments.map((s) => s.qrUrl), render, lay.qr.size, assetsDir); diff --git a/umtool/report-to-video/deck-markers-layout.test.mjs b/umtool/report-to-video/deck-markers-layout.test.mjs @@ -0,0 +1,155 @@ +// The deck's marker labels laid against crowding: a marker's `align`, and +// `deck.markerLayout` -- "stagger" (the default: two rows when one would not +// fit) or "truncate" (one row, ellipsized). A row that fits is laid as ever. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + DECK_DEFAULTS, deckLayout, deckMarkers, deckSchedule, MARKER_BAND, MARKER_ROW, markerLabelWidth, markerRowsOf, + pipSegments, pipXs, validateChrome, +} from "./deck.mjs"; +import { deckHtml } from "./chrome-deck.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const CHROME = { engine: "hyperframes", layout: "deck" }; +const BASE = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE }; +const renderWith = (deck = {}) => ({ ...BASE, chrome: { ...CHROME, deck } }); +const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" }; + +// 26 clips, evenly pipped, as the Huck story cut. +const N = 26; +const ENTRIES = Array.from({ length: N }, (_, i) => ({ id: `c${i}`, type: "clip", video: `v${i}`, start: 0, end: 30 })); +const DURS = ENTRIES.map(() => 30); + +// The crowded case: nine grey chapter flags along the cut and two red promise +// flags, the last three flags within ~200 px of the track's right end. +const CROWD = [ + ...[1, 4, 7, 10, 13, 16, 19, 22].map((i, n) => ({ after: `c${i}`, label: `Chapter ${n + 1}: the dog`, color: "muted" })), + { after: "c23", label: "“3–5 weeks”: 3 wks on", color: "#e5534b" }, + { after: "c24", label: "Chapter 9: the posts", color: "muted" }, + { after: "c25", label: "“I'll post”: 8 wks on", color: "#e5534b" }, +]; + +function lay(render) { + const s = deckSchedule({ entries: ENTRIES, durs: DURS, D: 0.5, render, provenance: PROV }); + const l = deckLayout(render, { schedule: s }); + const pipped = pipSegments(s); + const xs = pipXs(pipped.length, l.pipTrack.x0, l.pipTrack.x1, "even"); + return { s, l, ms: deckMarkers(s, render, xs, pipped, l) }; +} + +test("align and markerLayout: refused in sentences; the layout defaults to stagger", () => { + assert.equal(DECK_DEFAULTS.markerLayout, "stagger"); + const errs = validateChrome({ ...CHROME, deck: { markerLayout: "wrap", markers: [{ after: "c1", label: "x", align: "middle" }] } }); + assert.ok(errs.includes('render.chrome.deck.markers[0].align must be "auto", "left", "right", "center"'), errs.join("\n")); + assert.ok(errs.includes('render.chrome.deck.markerLayout must be "stagger" or "truncate"'), errs.join("\n")); + assert.deepEqual(validateChrome({ ...CHROME, deck: { markerLayout: "truncate", markers: [{ after: "c1", label: "x", align: "left" }] } }), []); +}); + +test("markerLabelWidth: at least Fira Sans Bold's measured widths at 18 px, upper-cased", () => { + // Measured with fontTools (advances + 0.04 em spacing): 207.5 and 195.7 px. + assert.ok(markerLabelWidth("“3–5 weeks”: 3 wks on") >= 208); + assert.ok(markerLabelWidth("“I'll post”: 8 wks on") >= 196); + assert.ok(markerLabelWidth("“3–5 weeks”: 3 wks on") < 260, "and not wildly over"); + assert.equal(markerLabelWidth("ab"), markerLabelWidth("AB")); +}); + +test("a row that fits is laid as it always was: one row, no row keys, the band unchanged", () => { + const r = renderWith({ markers: [{ after: "c5", label: "Short" }, { after: "c20", label: "Also short" }] }); + const { l, ms } = lay(r); + assert.equal(l.markerBand.height, MARKER_BAND + 6); + assert.equal(l.markerBand.rows, undefined); + for (const m of ms) assert.equal("row" in m, false); + assert.equal(markerRowsOf(lay(r).s, r), 1); +}); + +test("crowded: the labels stagger into two rows; none meets another in its row, a stick or the deck's edge", () => { + const r = renderWith({ markers: CROWD }); + const { s, l, ms } = lay(r); + const W = l.width; + // The last three flags sit within ~200 px of the track's end. + const last3 = [...ms].sort((a, b) => a.x - b.x).slice(-3); + assert.ok(last3.every((m) => l.pipTrack.x1 - m.x <= 200), last3.map((m) => m.x).join(", ")); + // In one row they would not all fit. + const trunc = lay(renderWith({ markers: CROWD, markerLayout: "truncate" })).ms; + const fitting = (list) => list.filter((m) => markerLabelWidth(m.label) <= m.box[1] - m.box[0]).length; + assert.ok(fitting(trunc) < trunc.length, "one row truncates some"); + for (const m of trunc) assert.equal("row" in m, false); + // Staggered: two rows. + assert.equal(markerRowsOf(s, r), 2); + const sorted = [...ms].sort((a, b) => a.x - b.x); + assert.ok(sorted.every((m) => m.row === 0 || m.row === 1)); + assert.ok(sorted.some((m) => m.row === 1)); + for (const row of [0, 1]) { + const inRow = sorted.filter((m) => m.row === row); + for (let j = 1; j < inRow.length; j += 1) { + assert.ok(inRow[j - 1].box[1] < inRow[j].box[0], `row ${row}: ${inRow[j - 1].after} and ${inRow[j].after} meet`); + } + } + // Row 0 keeps clear of the sticks reaching up to row 1. + const sticks = sorted.filter((m) => m.row === 1).map((m) => m.x); + for (const m of sorted.filter((x) => x.row === 0)) { + for (const x of sticks) assert.ok(x < m.box[0] || x > m.box[1], `${m.after}'s label crosses a stick at ${x}`); + } + for (const m of ms) assert.ok(m.box[0] >= 16 && m.box[1] <= W - 16, `${m.after} ${m.box}`); + // More of them fit than in one row -- the last three among them. (Three + // ~200 px labels on 140 px of track cannot all fit two rows: the rest are + // ellipsized, as in one row.) + assert.ok(fitting(ms) > fitting(trunc), `${fitting(ms)} vs ${fitting(trunc)}`); + const lastTrunc = [...trunc].sort((a, b) => a.x - b.x).slice(-3); + assert.ok(fitting(last3) > fitting(lastTrunc), `last three: ${fitting(last3)} vs ${fitting(lastTrunc)}`); + // The band grows by a row; the track and everything under it move down by it. + assert.equal(l.markerBand.height, MARKER_BAND + MARKER_ROW + 6); + assert.equal(l.markerBand.rows, 2); + assert.equal(l.pipTrack.y, 16 + MARKER_BAND + MARKER_ROW); + assert.ok(l.qr.y + l.qr.size <= l.height, `qr ${l.qr.y}+${l.qr.size}`); + assert.ok(l.qr.y >= l.pipTrack.y + 12); + assert.ok(l.text.titleY >= l.pipTrack.y + 14); + // The page: row 1's flags are `up`; their labels a row above; neither row reaches the flags' heads. + const html = deckHtml(s, r, {}); + assert.equal((html.match(/class="mflag up"/g) ?? []).length, ms.filter((m) => m.row === 1).length); + const tr = l.pipTrack.y; + const lowTop = Number(html.match(/\.mlabel \{ position: absolute; top: (-?\d+)px;/)[1]); + const upTop = Number(html.match(/\.mflag\.up \.mlabel \{ top: (-?\d+)px; \}/)[1]); + assert.equal(upTop, l.markerBand.y - tr); + assert.equal(lowTop, l.markerBand.y + MARKER_ROW - tr); + assert.ok(upTop + 20 <= lowTop, "the rows do not overlap"); + assert.ok(lowTop + 20 <= -14, "row 0 ends above the flags' heads (14 px over the track)"); + assert.ok(upTop >= -tr, "row 1 starts inside the deck"); + const stick = html.match(/\.mflag\.up \.mstick \{ top: (-?\d+)px; height: (\d+)px; \}/); + assert.equal(Number(stick[1]), upTop + 20, "the tall stick starts under its label"); + assert.equal(Number(stick[1]) + Number(stick[2]), 6, "and ends where a flag's stick does"); +}); + +test("truncate keeps one row in the crowd: the band as ever", () => { + const r = renderWith({ markers: CROWD, markerLayout: "truncate" }); + const { s, l } = lay(r); + assert.equal(markerRowsOf(s, r), 1); + assert.equal(l.markerBand.height, MARKER_BAND + 6); + assert.doesNotMatch(deckHtml(s, r, {}), /mflag up|\.mflag\.up/); +}); + +test("align: left starts the label at its flag, right ends it there, center centres it; text set to that side", () => { + const markers = [ + { after: "c5", label: "left one", align: "left" }, + { after: "c12", label: "right one", align: "right" }, + { after: "c18", label: "centred", align: "center" }, + ]; + const r = renderWith({ markers }); + const { s, ms } = lay(r); + const [a, b, c] = ms; + assert.equal(a.align, "left"); + assert.equal(a.box[0], Math.round(a.x)); + assert.ok(a.box[1] > a.x + 100); + assert.equal(b.box[1], Math.round(b.x)); + assert.ok(b.box[0] < b.x - 100); + assert.ok(Math.abs((c.box[0] + c.box[1]) / 2 - c.x) <= 1); + const html = deckHtml(s, r, {}); + assert.match(html, /data-after="c5"[^>]*>.*?<div class="mlabel" style="left:[^"]*; text-align:left">LEFT ONE|data-after="c5".*?text-align:left/); + assert.match(html, /data-after="c12".*?text-align:right/); + // A left flag followed by another left one may reach right up to it. + const two = lay(renderWith({ markers: [{ after: "c5", label: "a", align: "left" }, { after: "c7", label: "b", align: "left" }] })).ms; + assert.equal(two[0].box[1], Math.round(two[1].x - 3)); +}); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -78,11 +78,16 @@ export const DECK_DEFAULTS = Object.freeze({ // take the code's width. The clip's own deck QR (`qr`) is untouched. qr: true, }), - // Flags on the pip track: `[{ after, label, color? }]`, each between the pip - // of the clip `after` names and the next, hidden until the fuse reaches it - // (deckMarkers). An empty list is no flags, and the deck lays out as it - // always did. + // Flags on the pip track: `[{ after, label, color?, align? }]`, each between + // the pip of the clip `after` names and the next, hidden until the fuse + // reaches it (deckMarkers). An empty list is no flags, and the deck lays out + // as it always did. markers: Object.freeze([]), + // Crowded labels: "stagger" lays them in two rows when one would not fit in + // a single row (the band grows by MARKER_ROW, the track moves down by it); + // "truncate" keeps one row and ellipsizes. A single row that fits is laid + // the same either way. + markerLayout: "stagger", }); /** The pip's colour when lit (`pip.color`): the deck's accent, or a claimed clip's verdict. */ @@ -91,6 +96,17 @@ export const PIP_COLORS = Object.freeze(["accent", "verdict"]); /** A marker's limits: how many, and a label's characters. */ export const MARKER_LIMITS = Object.freeze({ count: 12, label: 24 }); +/** + * Where a marker's label sits against its flag: "auto" (centred when it has + * the room, else the stretch it may take -- as it always was), "left" (it + * starts at the flag and reads on to the right), "right" (it ends at the + * flag), "center" (centred on it, always). + */ +export const MARKER_ALIGNS = Object.freeze(["auto", "left", "right", "center"]); + +/** `deck.markerLayout`: crowded labels in two rows, or one row ellipsized. */ +export const MARKER_LAYOUTS = Object.freeze(["stagger", "truncate"]); + /** The palette keys a marker's `color` may name (else a `#rgb` / `#rrggbb`). */ export const MARKER_PALETTE_KEYS = Object.freeze(["fg", "muted", "accent", "amber", "dim"]); @@ -303,6 +319,9 @@ export function validateChrome(chrome, render = {}) { if (p.inset !== undefined && !numIn(p.inset, 0, 80)) errors.push(`${w}.posts.inset must be from 0 to 80`); }); errors.push(...markerShapeErrors(d.markers, `${w}.markers`)); + if (d.markerLayout !== undefined && !MARKER_LAYOUTS.includes(d.markerLayout)) { + errors.push(`${w}.markerLayout must be ${MARKER_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`); + } sub("motion", ["out", "in", "pip"], (m) => { for (const k of ["out", "in"]) { if (m[k] !== undefined && !numIn(m[k], 0, 2)) errors.push(`${w}.motion.${k} must be from 0 to 2 seconds`); @@ -356,7 +375,10 @@ function markerShapeErrors(markers, where) { const at = `${where}[${i}]`; if (!isObj(m)) { errors.push(`${at} must be { after, label, color? }`); return; } for (const k of Object.keys(m)) { - if (!["after", "label", "color"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color)`); + if (!["after", "label", "color", "align"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color, align)`); + } + if (m.align !== undefined && !MARKER_ALIGNS.includes(m.align)) { + errors.push(`${at}.align must be ${MARKER_ALIGNS.map((a) => `"${a}"`).join(", ")}`); } if (typeof m.after !== "string" || !m.after.trim()) errors.push(`${at}.after must name a clip's id`); const label = typeof m.label === "string" ? m.label.trim() : ""; @@ -492,16 +514,22 @@ export function threadsGeometry(render) { * text column (`factcheck.tally.position`) and the text keeps the rest. * * @param {any} render - * @param {{ tally?: string[] | null }} [opts] + * `schedule`, when given, lets the markers' labels stagger: when they need + * two rows (deckMarkers) the band is MARKER_ROW taller and everything under + * it moves down by that. Without it -- or when one row fits -- one row. + * + * @param {{ tally?: string[] | null, schedule?: any }} [opts] */ -export function deckLayout(render, { tally = null } = {}) { +export function deckLayout(render, { tally = null, schedule = null } = {}) { const { W, deck: rect } = deckGeometry(render); const d = resolveDeck(render); const padX = 48; // The markers' labels (`deck.markers`) stand in a band above the track: the // track moves down by it, and only when there is a marker to label, so a // deck without them lays out as it always did. - const markerBand = Array.isArray(d.markers) && d.markers.length ? MARKER_BAND : 0; + const marked = Array.isArray(d.markers) && d.markers.length > 0; + const rows = marked && schedule ? markerRowsOf(schedule, render) : 1; + const markerBand = marked ? MARKER_BAND + (rows > 1 ? MARKER_ROW : 0) : 0; const trackY = 16 + markerBand; // The body is everything under the pip track: the text block and the QR are // both centred in it, so the title's optical centre and the code's agree @@ -563,13 +591,90 @@ export function deckLayout(render, { tally = null } = {}) { // Only with a tally, so a deck without claims lays out as it always did. ...(tallyBox ? { tally: tallyBox } : {}), // Only with markers, likewise: where their labels stand (deckMarkers). - ...(markerBand ? { markerBand: { y: 3, height: markerBand + 6 } } : {}), + ...(markerBand ? { markerBand: { y: 3, height: markerBand + 6, ...(rows > 1 ? { rows } : {}) } } : {}), }; } /** How far the track moves down to make room for the markers' labels. */ export const MARKER_BAND = 22; +/** How much taller the band is when the labels stagger into a second row. */ +export const MARKER_ROW = 22; + +/** A marker label's font size, px (chrome-deck.mjs draws it at this). */ +export const MARKER_LABEL_SIZE = 18; + +/** + * About how wide a marker's label draws, px: its characters upper-cased (the + * page sets it so), each at a bold sans's advance for its kind plus the + * 0.04 em the page spaces letters by -- a little over Fira Sans Bold's + * measured widths, so a label called fitting does fit. What decides that a + * row of labels is crowded; the page still ellipsizes one that is not. + */ +export function markerLabelWidth(label, size = MARKER_LABEL_SIZE) { + let em = 0; + for (const ch of String(label ?? "").toUpperCase()) { + if (ch === " ") em += 0.25; + else if (/[.,:;'!|’‘]/.test(ch)) em += 0.26; + else if (/[0-9]/.test(ch)) em += 0.56; + else if (/[MW@&]/.test(ch)) em += 0.86; + else if (/[A-Z]/.test(ch)) em += 0.62; + else em += 0.52; + em += 0.04; + } + return Math.ceil(em * size); +} + +/** A flag's stick is kept this clear of a label in the row under its own. */ +const STICK_CLEAR = 8; + +/** + * The label boxes of one row of flags (sorted by x): each up to halfway to + * its neighbours in the row -- or right up to one whose label reads away + * from it ("left"/"right") -- 360 px at most, inside the deck, and clear of + * `walls` (the sticks of the flags labelled in the row above). "auto" is the + * rule it always was: centred when that leaves the label room, else the + * whole stretch it may take. + */ +function labelBoxes(row, W, walls = []) { + return row.map((p, o) => { + const prev = row[o - 1] ?? null; + const next = row[o + 1] ?? null; + const a = p.align ?? "auto"; + const reach = a === "left" ? [p.x, p.x + 360] : a === "right" ? [p.x - 360, p.x] : [p.x - 180, p.x + 180]; + let lo = Math.max(16, reach[0], prev === null ? -Infinity : prev.align === "right" ? prev.x + 3 : (prev.x + p.x) / 2 + 3); + let hi = Math.min(W - 16, reach[1], next === null ? Infinity : next.align === "left" ? next.x - 3 : (p.x + next.x) / 2 - 3); + for (const w of walls) { + if (w < p.x) lo = Math.max(lo, w + STICK_CLEAR); + else if (w > p.x) hi = Math.min(hi, w - STICK_CLEAR); + } + hi = Math.max(lo, hi); + let box; + if (a === "left" || a === "right") box = [lo, hi]; + else { + const half = Math.min(p.x - lo, hi - p.x); + box = a === "center" || half * 2 >= Math.min(140, hi - lo) ? [p.x - half, p.x + half] : [lo, hi]; + } + return box.map((v) => Math.round(v)); + }); +} + +/** + * How many rows the deck's marker labels take for this schedule: 2 when they + * stagger (deckMarkers), else 1. + */ +export function markerRowsOf(schedule, render) { + const d = resolveDeck(render); + if (!Array.isArray(d.markers) || !d.markers.length) return 1; + const lay = deckLayout(render); + const pipped = pipSegments(schedule); + const xs = pipXs( + pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, d.pip.spacing, + d.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null, + ); + return deckMarkers(schedule, render, xs, pipped, lay).some((m) => m.row === 1) ? 2 : 1; +} + /** * Where each of the deck's markers (`deck.markers`) stands on the pip track, * region-local px: `x` between the pip of the clip it follows and the next @@ -578,11 +683,21 @@ export const MARKER_BAND = 22; * box `[left, right]`: at most 360 px centred on the flag, never past halfway * to the next flag either side nor off the track's ends, so two labels never * meet -- a long one is ellipsized in it. `k` is the pip it follows. A marker - * whose clip has no pip (not in the cut) is left out. + * whose clip has no pip (not in the cut) is left out. A marker's `align` + * places its label against its flag (MARKER_ALIGNS; "auto" as ever). + * + * Crowded: when a label would not fit its box and `deck.markerLayout` is + * "stagger" (the default), the flags alternate between two rows (`row` 0, the + * one over the track, and 1 above it) and each label takes the room to its + * neighbours in its own row; one in row 0 stays clear of the sticks that + * reach up past it to row 1. A label that still does not fit is ellipsized, + * as in one row. `row` and `align` are on a marker only when they say + * something (staggered; not "auto"). * * `xs` are the pips' x (pipXs), `pipped` their segments (pipSegments). * - * @returns {Array<{ after: string, label: string, color: string, k: number, x: number, box: [number, number] }>} + * @returns {Array<{ after: string, label: string, color: string, k: number, x: number, box: [number, number], + * align?: string, row?: number }>} */ export function deckMarkers(schedule, render, xs, pipped, lay = deckLayout(render)) { const d = resolveDeck(render); @@ -609,23 +724,54 @@ export function deckMarkers(schedule, render, xs, pipped, lay = deckLayout(rende x = Math.min(x1, Math.max(x0, x)); const key = m.color ?? MARKER_DEFAULT_COLOR; const color = HEX_RE.test(key) ? key : pal[key] ?? pal.fg ?? "#ffffff"; - placed.push({ after, label: String(m.label ?? "").trim(), color, k, x: Math.round(x * 100) / 100 }); + const align = MARKER_ALIGNS.includes(m.align) && m.align !== "auto" ? m.align : null; + placed.push({ after, label: String(m.label ?? "").trim(), color, k, x: Math.round(x * 100) / 100, ...(align ? { align } : {}) }); } // The label boxes: each up to halfway to its neighbours, 360 px at most. const order = placed.map((p, j) => j).sort((a, b) => placed[a].x - placed[b].x); const W = lay.width; - return placed.map((p, j) => { - const o = order.indexOf(j); - const prev = o > 0 ? placed[order[o - 1]].x : null; - const next = o < order.length - 1 ? placed[order[o + 1]].x : null; - const lo = Math.max(16, p.x - 180, prev === null ? -Infinity : (prev + p.x) / 2 + 3); - const hi = Math.max(lo, Math.min(W - 16, p.x + 180, next === null ? Infinity : (p.x + next) / 2 - 3)); - // Centred on the flag when that leaves the label room; else the whole - // stretch it may take, off-centre (a flag near the track's end). - const half = Math.min(p.x - lo, hi - p.x); - const box = half * 2 >= Math.min(140, hi - lo) ? [p.x - half, p.x + half] : [lo, hi]; - return { ...p, box: box.map((v) => Math.round(v)) }; - }); + const one = labelBoxes(order.map((j) => placed[j]), W); + const boxOf = new Map(order.map((j, o) => [j, one[o]])); + const need = placed.map((p) => markerLabelWidth(p.label)); + const fits = (j, box) => need[j] <= box[1] - box[0]; + if (d.markerLayout === "truncate" || order.every((j) => fits(j, boxOf.get(j)))) { + return placed.map((p, j) => ({ ...p, box: boxOf.get(j) })); + } + // Two rows: row 1's sticks reach up through row 0. Every split of the flags + // between the rows is tried (there are at most MARKER_LIMITS.count) and the + // one where the most labels fit wins -- then the least cut off the rest, + // then the fewest in row 1, then the first in order: alternating flags, + // when nothing tells two splits apart. Past 12 flags, they alternate. + const n = order.length; + const lay2 = (mask) => { + const rows = [order.filter((_, o) => !((mask >> o) & 1)), order.filter((_, o) => (mask >> o) & 1)]; + const up = labelBoxes(rows[1].map((j) => placed[j]), W); + const low = labelBoxes(rows[0].map((j) => placed[j]), W, rows[1].map((j) => placed[j].x)); + const at = new Map([ + ...rows[0].map((j, o) => [j, { box: low[o], row: 0 }]), + ...rows[1].map((j, o) => [j, { box: up[o], row: 1 }]), + ]); + let fit = 0, short = 0; + for (const [j, { box }] of at) { + const over = need[j] - (box[1] - box[0]); + if (over <= 0) fit += 1; + else short += over; + } + return { at, fit, short, ups: rows[1].length }; + }; + let alt = 0; + for (let o = 1; o < n; o += 2) alt |= 1 << o; + let best = lay2(alt); + if (n <= MARKER_LIMITS.count) { + for (let mask = 0; mask < 1 << n; mask += 1) { + if (mask === alt) continue; + const c = lay2(mask); + if (c.fit > best.fit || (c.fit === best.fit && (c.short < best.short || (c.short === best.short && c.ups < best.ups)))) best = c; + } + } + // All in one row is no stagger: the one row as above. + if (best.ups === 0) return placed.map((p, j) => ({ ...p, box: boxOf.get(j) })); + return placed.map((p, j) => ({ ...p, ...best.at.get(j) })); } /**