"use client";
import { useCallback, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
import { useHydrated } from "./use-hydrated";
// ---------------------------------------------------------------------------
// THE LIT LINE -- the signature (plans/umtool-redesign.md, "Signature").
//
// Every list is a stack of lines; the focused one is LIT: a Signal edge with
// the play-head notch, ink text, its actions shown. The others sit dim. `j`/`k`
// (and the arrows) glide the head about 120 ms -- the app's only motion -- and
// with reduced motion it jumps (--glide is 0 ms then, app/globals.css).
//
// Lines are found in the DOM, not passed as data: anything marked
// `data-lit-line` inside this list is a line, however deep (LitGroup nests them
// under a head), and the lines themselves can be server-rendered (lit-line.tsx).
// A line inside ANOTHER list nested in this one belongs to that one.
//
// Focus ROVES: the lit line is the one Tab stop into the list, the keys move
// focus with the light, and Tab from the lit line reaches its own buttons. A
// click or a focus anywhere on a line lights it.
//
// Every button in the list is disabled until hydration (the house rule,
// components/VerdictChip.tsx) -- a
does it for the whole
// list at once, server-rendered, and lifts on the first client render.
//
// `lit` is announced as a DOM event, so a client parent can follow it:
// el.addEventListener("lit", (e) => e.detail.index, e.detail.id)
// ---------------------------------------------------------------------------
export type LitDetail = { index: number; id: string | null };
const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
export function LitList({
label,
initial,
columns = false,
global = false,
onLight,
className,
children,
}: {
/** The list's accessible name ("Results", "Decisions"). */
label: string;
/** The line lit on load, by index; a line marked `initial` wins over it. */
initial?: number;
/**
* The lines sit in more than one column (Create's two, P5): the head follows
* the lit line's left edge as well as its top. Off, the head stays at the
* list's left edge, as every one-column list has it.
*/
columns?: boolean;
/**
* `j`/`k` anywhere on the page move this list (when nothing is being typed
* in), not only with focus inside it. For the ONE list a page is about.
*/
global?: boolean;
onLight?: (d: LitDetail) => void;
className?: string;
children: React.ReactNode;
}) {
const hydrated = useHydrated();
const ref = useRef(null);
const head = useRef(null);
const lit = useRef(-1);
const onLightRef = useRef(onLight);
onLightRef.current = onLight;
const lines = useCallback((): HTMLElement[] => {
const root = ref.current;
if (!root) return [];
return [...root.querySelectorAll("[data-lit-line]")].filter(
(el) => el.closest("[data-lit-list]") === root,
);
}, []);
const place = useCallback(() => {
const root = ref.current;
const h = head.current;
if (!root || !h) return;
const el = lines()[lit.current];
if (!el) {
h.setAttribute("data-off", "");
return;
}
const r = el.getBoundingClientRect();
const base = root.getBoundingClientRect();
h.removeAttribute("data-off");
h.style.top = `${r.top - base.top}px`;
h.style.height = `${r.height}px`;
if (columns) h.style.left = `${r.left - base.left}px`;
// The first placement must not glide in from the top of the list.
if (!h.hasAttribute("data-placed")) requestAnimationFrame(() => h.setAttribute("data-placed", ""));
}, [lines, columns]);
const light = useCallback(
(i: number, opts: { focus?: boolean } = {}) => {
const all = lines();
if (!all.length) return;
const n = Math.max(0, Math.min(all.length - 1, i));
all.forEach((el, k) => {
if (k === n) el.setAttribute("data-lit", "");
else el.removeAttribute("data-lit");
el.tabIndex = k === n ? 0 : -1;
});
const el = all[n];
const changed = lit.current !== n;
lit.current = n;
place();
if (opts.focus) {
el.focus({ preventScroll: true });
el.scrollIntoView({ block: "nearest" });
}
if (changed) {
const detail: LitDetail = { index: n, id: el.dataset.litId ?? null };
ref.current?.dispatchEvent(new CustomEvent("lit", { detail }));
onLightRef.current?.(detail);
}
},
[lines, place],
);
// Light the first line once the list is live, and follow its size.
useEffect(() => {
const root = ref.current;
if (!root) return;
const all = lines();
const marked = all.findIndex((el) => el.hasAttribute("data-lit-initial"));
light(marked >= 0 ? marked : (initial ?? 0));
const ro = new ResizeObserver(() => place());
ro.observe(root);
window.addEventListener("resize", place);
void document.fonts?.ready.then(place);
return () => {
ro.disconnect();
window.removeEventListener("resize", place);
};
// `initial` is read once: after that the operator owns the light.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lines, light, place]);
const step = useCallback(
(e: KeyboardEvent | React.KeyboardEvent) => {
if (e.metaKey || e.ctrlKey || e.altKey) return false;
const t = e.target as HTMLElement | null;
if (t?.closest?.(TYPING)) return false;
const k = e.key;
const last = lines().length - 1;
const to =
k === "j" || k === "ArrowDown"
? lit.current + 1
: k === "k" || k === "ArrowUp"
? lit.current - 1
: k === "Home"
? 0
: k === "End"
? last
: null;
if (to === null || last < 0) return false;
e.preventDefault();
light(to, { focus: true });
return true;
},
[light, lines],
);
// A page's ONE list can take j/k from anywhere that is not typing.
useEffect(() => {
if (!global) return;
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
const inOther = (e.target as HTMLElement | null)?.closest?.("[data-lit-list]");
if (inOther && inOther !== ref.current) return;
if (e.key !== "j" && e.key !== "k") return;
step(e);
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [global, step]);
const fromEvent = (target: EventTarget | null) => {
const el = (target as HTMLElement | null)?.closest?.("[data-lit-line]");
if (!el || el.closest("[data-lit-list]") !== ref.current) return -1;
return lines().indexOf(el);
};
return (
{
if (!global || (e.key !== "j" && e.key !== "k")) step(e);
}}
onClick={(e) => {
const i = fromEvent(e.target);
if (i >= 0 && i !== lit.current) light(i);
}}
onFocus={(e) => {
const i = fromEvent(e.target);
if (i >= 0 && i !== lit.current) light(i);
}}
>
{children}
);
}