/** Rendering shared by both page layouts: a node's body with its notes, the outline rows, and the top of the page. */ import { Component, type ComponentChildren } from "preact"; import { useLayoutEffect, useRef, useState } from "preact/hooks"; import { anchorLost, ancestors, descendants, docOf, isLibraryRoot, label, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model"; import type { Ref } from "../core/ref"; import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text"; import { streamView } from "../core/marks"; import { ownerSection } from "../core/links"; import { ChoiceRows, LinkMark, useForkMark, LinkPreview, NodeBacklinks, NodeRelated, SuggestionCard, TargetRow, articleChoice, sectionChoice, useWikiSuggest, type Choice } from "./Links"; import { store, type Pending } from "./store"; // ---- inline text ---- /** A note as the renderer sees it: one in the document, or one still being written. */ export interface VNote { key: string; id?: NodeId; form: Form; ranges: Range[]; open: boolean; pending?: Pending; lens?: string; /** Its target, if it links somewhere. */ ref?: Ref; /** A link: a target and no text of its own. */ link?: boolean; } function notesFor(snap: Snap, id: NodeId): { placed: VNote[]; orphans: NodeId[] } { const placed: VNote[] = []; const orphans: NodeId[] = []; for (const c of notesOf(snap, id)) { const n = snap.nodes[c]; const ranges = n.anchors.filter((a) => a.end > a.start).map((a): Range => [a.start, a.end]); if (!ranges.length || n.anchors.every(anchorLost)) orphans.push(c); else placed.push({ key: c, id: c, form: n.form ?? "note", ranges, open: store.open.has(c), lens: n.lens, ref: n.ref, link: !!n.ref && !n.body.trim() }); } for (const p of store.pending.values()) { if (p.node === id && p.kind === "note" && p.range) placed.push({ key: p.key, form: p.form ?? "note", ranges: [p.range], open: true, pending: p, lens: p.lens }); } return { placed, orphans }; } const MARK = /\*([^*\n]+)\*|`([^`\n]+)`/g; /** One paragraph (or a whole short body) as spans that know their offsets into the body. */ function Para(props: { id: NodeId; range: Range; notes: VNote[]; inline: boolean; inNote: boolean; first: boolean }) { const { id, range, notes, inline } = props; const snap = store.snap; const forkMark = useForkMark(); const body = snap.nodes[id].body; const [ps, pe] = range; const cuts = new Set([ps, pe]); const clipTo = (r: Range): Range | null => (r[0] < pe && r[1] > ps ? [Math.max(r[0], ps), Math.min(r[1], pe)] : null); const cut = (r: Range | null) => r && (cuts.add(r[0]), cuts.add(r[1])); // *emphasis* and `code`: the markers are hidden but still count as characters. const hidden = new Set(); const em: Range[] = []; const code: Range[] = []; const text = body.slice(ps, pe); MARK.lastIndex = 0; for (let m; (m = MARK.exec(text)); ) { const a = ps + m.index; const b = a + m[0].length; hidden.add(a).add(b - 1); (m[1] !== undefined ? em : code).push([a + 1, b - 1]); [a, a + 1, b - 1, b].forEach((x) => cuts.add(x)); } for (const n of notes) n.ranges.forEach((r) => cut(clipTo(r))); // Suggested links: a faint dashed underline where no note or link already is. const suggs = store.preview ? [] : store.links.forNode(id, snap).filter((sg) => !notes.some((n) => n.ranges.some((r) => overlaps(r, sg.range)))); for (const sg of suggs) cut(clipTo(sg.range)); const focusedSugg = store.focusedSuggestion(); // Each linked span gets one mark, after its last character: the first link on it, in library order. const marked = new Set(); const f = store.focus; const sel = f.node === id && f.grain !== "node" && f.range ? clipTo(f.range) : null; cut(sel); // On the root, show which sentences of the prompt the focused section grew from. const focusNode = snap.nodes[f.node]; const chain = focusNode ? [f.node, ...ancestors(snap, f.node)] : []; const source = chain.map((x) => snap.nodes[x]).find((x) => x.parent === id && x.kind === "section" && x.anchors.length); const srcRanges = source ? source.anchors.map((a): Range => [a.start, a.end]) : []; srcRanges.forEach((r) => cut(clipTo(r))); const within = (rs: Range[], a: number, b: number) => rs.some((r) => r[0] <= a && r[1] >= b); const points = [...cuts].sort((x, y) => x - y); const out: ComponentChildren[] = []; const after: ComponentChildren[] = []; for (let i = 0; i + 1 < points.length; i++) { const a = points[i]; const b = points[i + 1]; if (!(b === a + 1 && hidden.has(a))) { // A note (with text) gets the dotted underline; a link the solid one. A note that also links // keeps its dotted underline and gets the mark, so the two facts stay separately legible. const note = notes.find((n) => !n.link && within(n.ranges, a, b)); const link = notes.find((n) => n.ref && within(n.ranges, a, b)); const sugg = !note && !link ? suggs.find((sg) => sg.range[0] <= a && sg.range[1] >= b) : undefined; const cls = [ within(em, a, b) && "em", within(code, a, b) && "code", note && `anchor a-${note.form}`, note?.open && "on", note?.pending && "writing", link?.link && !note && `lnk l-${link.ref!.kind}${link.open ? " on" : ""}`, forkMark && (note ?? link)?.id && forkMark(`n:${(note ?? link)!.id}`, link?.ref && store.targetKey(link.ref)), sel && sel[0] <= a && sel[1] >= b && `sel ${f.grain}`, within(srcRanges, a, b) && "src", sugg && `sugg${sugg.tier === "auto" ? " sure" : ""}`, ].filter(Boolean).join(" "); out.push( {body.slice(a, b)} , ); } for (const n of notes) { const r = n.ranges[0]; if (!n.ref || r[1] !== b || b <= ps || b > pe || marked.has(`${r[0]}:${r[1]}`)) continue; marked.add(`${r[0]}:${r[1]}`); out.push(); } if (focusedSugg && focusedSugg.node === id && focusedSugg.range[1] === b && b > ps && b <= pe) after.push(); for (const n of notes) { if (!n.open || n.ranges[0][1] !== b || (b === ps && i === 0)) continue; if (n.link) { // A link opens its target in panes; in the column it shows a preview under the paragraph. if (!store.panes && n.id) after.push(); continue; } const view = ; // A pane has no margin, so there a margin note follows its paragraph instead of splitting it. if (n.form === "passage" || (n.form === "note" && (props.inNote || store.panes))) after.push(view); else out.push(view); } } const Tag = (inline ? "span" : "p") as "p"; return ( <> {out} {after} ); } function Writing({ text }: { text: string }) { // Link marks ([[…]]) a model writes are never shown, even half-written. return ( <> {plain(streamView(text))} ); } const LENS_LABEL: Record = { elaborate: "", define: "definition", why: "why", example: "example", challenge: "objection" }; export function NoteView({ v, inNote }: { v: VNote; inNote: boolean }) { const snap = store.snap; const focused = !!v.id && store.focus.node === v.id; const st = v.id ? staleness(snap, v.id) : null; const stale = !!st && (st.down || st.up); const cls = `${focused && store.focus.grain === "node" ? " focused" : ""}${v.pending ? " pending" : ""}${stale ? " stale" : ""}`; const lens = v.lens ? (LENS_LABEL[v.lens] ?? v.lens) : ""; const content = v.pending ? : ; const meta = (lens || stale || (v.id && snap.nodes[v.id].pinned)) && ( {lens} {v.id && snap.nodes[v.id].pinned ? " · locked" : ""} {stale ? " · stale" : ""} ); if (v.form === "gloss") { return ( {content} ); } const kids = v.id ? sections(snap, v.id) : []; return ( {v.id && } {meta} {content} {kids.length > 0 && } {v.id && } ); } /** The phrase a choice puts in the text: what was typed, finished from the title where the title continues it. */ function phraseFor(typed: string, title: string): string { const base = title.replace(/\s*\([^)]*\)\s*$/, ""); if (!typed.trim()) return base; return base.toLowerCase().startsWith(typed.toLowerCase()) ? typed + base.slice(typed.length) : typed.trim(); } function BodyEditor({ id }: { id: NodeId }) { const ref = useRef(null); // The [[ completer: where the [[ is, what follows it, Wikipedia's answer for it, and the selection. const [comp, setComp] = useState<{ start: number; q: string } | null>(null); const [sel, setSel] = useState(0); const fit = () => { const el = ref.current; if (!el) return; el.style.height = "auto"; el.style.height = `${el.scrollHeight + 2}px`; }; useLayoutEffect(() => { ref.current?.focus(); fit(); }, []); const typed = comp?.q.trim() ?? ""; const wiki = useWikiSuggest(typed.length >= 2 ? typed : ""); const detect = () => { const el = ref.current!; const m = /\[\[([^\[\]\n|]{0,60})$/.exec(el.value.slice(0, el.selectionStart)); setComp(m ? { start: el.selectionStart - m[0].length, q: m[1] } : null); setSel(0); }; // Library titles are instant and come first. const choices: Choice[] = typed ? [...store.search(comp!.q).filter((x) => x !== id).slice(0, 5).map(sectionChoice), ...(wiki?.list.slice(0, 6) ?? []).map(articleChoice)] : []; const accept = (c: Choice) => { const el = ref.current!; const phrase = phraseFor(comp!.q, c.label); el.setRangeText(phrase, comp!.start, el.selectionStart, "end"); (store.edit!.chosen ??= []).push({ phrase, at: comp!.start, target: c.ref }); setComp(null); fit(); }; return ( <>