import { memo, useEffect, useMemo, useState } from "react"; import type { CSSProperties } from "react"; import { NAV_MINIMIZE_EVENT, signal } from "../apiContract"; import { formatDisplay } from "./display"; import { ModeIcon } from "./icons"; import type { Field, Row } from "./types"; import "./GalleryTimelineViews.css"; /** * ⭐⭐ W50-T01 / owner ruling R1 (2026-09-03) — THE CLIENT RENDER CAP IS RETIRED. * * There is no "Showing first N" bar and no "See more" anywhere any more. Every loaded row is * reachable: the Grid canvas paints them all (glide virtualises), and the DOM card views below * paint a WINDOW of the same complete list inside their own scroll container, with a spacer * above and below standing in for the rows that are not mounted. Scrolling to the bottom reaches * the last record, and the node count stays small at any table size. * * ⛔ THE SERVER WINDOW IS UNTOUCHED. R1 retires the CLIENT cap only; `serverWindowed`, * `requestWindow`, `WINDOW_ROWS` and `windowedFoldNote` are the other half of the same ruling and * they stay exactly as they were. A 1M-row table still arrives as a window. * * ⛔ EVERY GEOMETRY NUMBER BELOW IS DECLARED HERE AND NOWHERE ELSE. The stylesheet reads them as * custom properties set inline on the section, so the layout maths and the painted layout cannot * disagree. A spacer model over heights the CSS owns independently drifts, and a drifting model * makes the LAST card unreachable, which is the same user-visible failure as the cap that was * just deleted. One source of truth is what stops that. */ const GALLERY_CARD_MIN = 224; const GALLERY_GAP = 10; const GALLERY_CARD_H = 116; const GALLERY_PAD = 16; /** Timeline geometry. A card's height follows the number of detail lines it lists, which is * fixed for a render (`visibleDetailFields` slices to 3), so it is exact rather than estimated. */ const TIMELINE_PAD = 16; const TIMELINE_CARD_BASE = 46; const TIMELINE_DETAIL_H = 22; const TIMELINE_EVENT_GAP = 10; const TIMELINE_MONTH_H = 34; /** * Rows of extra work above and below the viewport, so a fast flick does not paint blank. * * ⚠ IT COSTS `2 × OVERSCAN_ROWS × columns` MOUNTED CARDS, WHICH IS THE HALF OF THE NODE COUNT * NOBODY LOOKS AT. The viewport's own rows are irreducible - a window cannot mount fewer cards * than the screen shows - so overscan is the only term here anybody chooses. At ten columns, 3 * rows of it is sixty cards of pure headroom. Two is the smallest value that still covers a * flick between paints on this hardware. */ const OVERSCAN_ROWS = 2; type ScrollBox = { setBox: (el: HTMLDivElement | null) => void; top: number; height: number; width: number; }; /** * The scroll container's live geometry. * * ⚠ A CALLBACK REF, not a `useRef`. These views return an empty-state before their container * exists, so a `useRef` + `useEffect([ref])` pair would subscribe once, to nothing, and never * re-run when rows arrived: the window would sit frozen at its first guess and the view would * never scroll. State-as-a-ref re-runs the effect on the actual mount and unmount. * * ⭐ EXPORTED for `viewModes.tsx`, which windows Kanban and Calendar against the SAME hook. * R1 names four DOM views and "windowed the same way" has to mean one implementation: a second * copy of this would be a second place for the scroll/resize subscription to be got wrong, and * the two would drift the moment either is tuned. */ export function useScrollBox(): ScrollBox { const [box, setBox] = useState(null); const [geom, setGeom] = useState({ top: 0, height: 0, width: 0 }); useEffect(() => { if (!box) return; const read = () => { const top = box.scrollTop; const height = box.clientHeight; const width = box.clientWidth; setGeom((prev) => prev.top === top && prev.height === height && prev.width === width ? prev : { top, height, width } ); }; read(); box.addEventListener("scroll", read, { passive: true }); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(read); if (observer) observer.observe(box); return () => { box.removeEventListener("scroll", read); if (observer) observer.disconnect(); }; }, [box]); return { setBox, top: geom.top, height: geom.height, width: geom.width }; } /** The half-open item range to mount, given a uniform pitch. `height` is 0 on the very first * paint (before the effect measures), so a floor of one viewport keeps that frame non-empty. * * ⭐ EXPORTED alongside `useScrollBox`, and for the same reason: the overscan and the * first-paint floor are a policy, and a policy stated twice is a policy that diverges. */ export function windowRange(total: number, pitch: number, top: number, height: number) { const view = Math.max(height, pitch * 8); const first = Math.max(0, Math.floor(top / pitch) - OVERSCAN_ROWS); const span = Math.ceil(view / pitch) + OVERSCAN_ROWS * 2; return { first, last: Math.min(total, first + span) }; } function visibleDetailFields(fields: Field[], visibleKeys: string[], excluded: string[]) { const byKey = new Map(fields.map((field) => [field.key, field])); return visibleKeys .filter((key) => !excluded.includes(key)) .map((key) => byKey.get(key)) .filter((field): field is Field => !!field) .slice(0, 3); } function titleFor(row: Row, titleKey: string) { const value = String(row[titleKey] ?? "").trim(); return value || "Untitled record"; } function openRecord(pid: number, detail: number, onOpen: (pid: number) => void) { if (detail <= 1) signal(NAV_MINIMIZE_EVENT); onOpen(pid); } /** A quiet card arrangement over the exact filtered rows the Grid would paint. */ export const GalleryView = memo(function GalleryView({ rows, fields, visibleKeys, titleKey, onOpen, }: { rows: Row[]; fields: Field[]; visibleKeys: string[]; titleKey: string; onOpen: (pid: number) => void; }) { const details = useMemo( () => visibleDetailFields(fields, visibleKeys, [titleKey]), [fields, visibleKeys, titleKey] ); const scroll = useScrollBox(); /* auto-fill's OWN arithmetic, over the same two numbers the stylesheet is handed below, so the column count the window assumes is the column count the browser lays out. */ const inner = Math.max(0, scroll.width - GALLERY_PAD * 2); const cols = Math.max( 1, Math.floor((inner + GALLERY_GAP) / (GALLERY_CARD_MIN + GALLERY_GAP)) ); const pitch = GALLERY_CARD_H + GALLERY_GAP; const cardRows = Math.ceil(rows.length / cols); const { first, last } = windowRange(cardRows, pitch, scroll.top, scroll.height); const mounted = rows.slice(first * cols, last * cols); const padTop = first * pitch; const padBottom = Math.max(0, (cardRows - last) * pitch); const vars = { "--cg-gallery-card-min": `${GALLERY_CARD_MIN}px`, "--cg-gallery-gap": `${GALLERY_GAP}px`, "--cg-gallery-card-h": `${GALLERY_CARD_H}px`, "--cg-mode-pad": `${GALLERY_PAD}px`, } as CSSProperties; if (!rows.length) return
No records match this view.
; return (
Gallery {rows.length.toLocaleString()} records
{padTop > 0 && (
)} {mounted.map((row) => { const title = titleFor(row, titleKey); return ( ); })} {padBottom > 0 && (
)}
); }); type TimelineEvent = { row: Row; day: string; title: string }; type TimelineItem = | { kind: "month"; key: string; label: string } | { kind: "event"; key: string; event: TimelineEvent }; function monthLabel(day: string) { return new Intl.DateTimeFormat(undefined, { month: "long", year: "numeric", timeZone: "UTC" }) .format(new Date(`${day.slice(0, 7)}-01T00:00:00Z`)); } function dayLabel(day: string) { return new Intl.DateTimeFormat(undefined, { weekday: "short", day: "numeric", timeZone: "UTC" }) .format(new Date(`${day}T00:00:00Z`)); } /** A chronological projection. It never writes dates: editing remains in the normal record drawer. */ export const TimelineView = memo(function TimelineView({ rows, fields, visibleKeys, field, titleKey, onOpen, }: { rows: Row[]; fields: Field[]; visibleKeys: string[]; field: Field; titleKey: string; onOpen: (pid: number) => void; }) { const events = useMemo( () => rows .map((row) => ({ row, day: String(row[field.key] ?? "").slice(0, 10), title: titleFor(row, titleKey) })) .filter((event) => /^\d{4}-\d{2}-\d{2}$/.test(event.day)) .sort((a, b) => a.day.localeCompare(b.day) || a.title.localeCompare(b.title)), [rows, field.key, titleKey] ); const details = useMemo( () => visibleDetailFields(fields, visibleKeys, [titleKey, field.key]), [fields, visibleKeys, titleKey, field.key] ); const missing = rows.length - events.length; /** * ⚠ FLATTENED, and that is what makes the window exact. The old markup nested every month's * events inside a `
` with its own heading, so an item's offset depended on how many * months sat above it AND on two different gaps. One flat list of month-heading items and * event items, each with a height this file declares, turns "where does item i start" into a * prefix sum, which a spacer model can be right about at row 3,000 as well as at row 3. */ const items = useMemo(() => { const out: TimelineItem[] = []; let month = ""; for (const event of events) { const key = event.day.slice(0, 7); if (key !== month) { month = key; out.push({ kind: "month", key: `m:${key}`, label: monthLabel(`${key}-01`) }); } out.push({ kind: "event", key: `e:${event.row.pid}:${event.day}`, event }); } return out; }, [events]); const cardH = TIMELINE_CARD_BASE + details.length * TIMELINE_DETAIL_H; const eventH = cardH + TIMELINE_EVENT_GAP; /** Prefix offsets, one entry longer than `items`, so the tail is the full scroll height. */ const offsets = useMemo(() => { const out = new Array(items.length + 1); out[0] = 0; for (let i = 0; i < items.length; i += 1) out[i + 1] = out[i] + (items[i].kind === "month" ? TIMELINE_MONTH_H : eventH); return out; }, [items, eventH]); const scroll = useScrollBox(); const total = offsets[items.length] ?? 0; const view = Math.max(scroll.height, eventH * 8); let firstIdx = 0; let lastIdx = items.length; if (items.length) { let lo = 0; let hi = items.length - 1; const target = Math.max(0, scroll.top - OVERSCAN_ROWS * eventH); while (lo < hi) { const mid = (lo + hi) >> 1; if (offsets[mid + 1] <= target) lo = mid + 1; else hi = mid; } firstIdx = lo; const bottom = scroll.top + view + OVERSCAN_ROWS * eventH; let end = firstIdx; while (end < items.length && offsets[end] < bottom) end += 1; lastIdx = end; } const mounted = items.slice(firstIdx, lastIdx); const padTop = offsets[firstIdx] ?? 0; const padBottom = Math.max(0, total - (offsets[lastIdx] ?? total)); const vars = { "--cg-tl-card-h": `${cardH}px`, "--cg-tl-event-h": `${eventH}px`, "--cg-tl-month-h": `${TIMELINE_MONTH_H}px`, "--cg-mode-pad": `${TIMELINE_PAD}px`, } as CSSProperties; if (!events.length) { return (
No records have a valid {field.label} date for this timeline.
); } return (
Timeline {events.length.toLocaleString()} dated records · by {field.label} {missing > 0 && {missing.toLocaleString()} without a date}
{padTop > 0 && (
)} {mounted.map((item) => item.kind === "month" ? (

{item.label}

) : (
{dayLabel(item.event.day)}
) )} {padBottom > 0 && (
)}
); });