import type { ObjectDirective } from "vue"; import { apiPost } from "@/api/client"; import router from "@/router"; import { recordHref } from "@/utils/recordHref"; import type { RefSpace } from "@/utils/recordRefs"; /** v-record-refs — makes the `a.record-ref` links in a v-html body real. * * Put it on the element that holds rendered markdown: *
* * After each render it asks the server, once for the whole body, what every * referenced id is. Each link then gets the route its kind opens at (a `#N` * may be a task, lesson or snippet), the record's title drawn before its * number — "Fix the cache key #3127" — so a reader knows what is cited * without hovering, its kind, full title and status as a tooltip, and a * "leads nowhere" style when the reader cannot open it: missing, trashed and * not-shared-with-you look the same, on purpose, and keep the bare number. * The stored text stays `#N`; the title is read at render, so an edited * title shows everywhere it is cited. * A plain click navigates in the app; a modified click (new tab) keeps the * browser's own behaviour. */ interface NoteInfo { id: number; title: string; is_task: boolean; note_type: string; status: string | null; task_kind: string | null } interface MilestoneInfo { id: number; title: string; project_id: number | null; status: string } interface RuleInfo { id: number; title: string; kind: string } type Resolved = { notes: Record; milestones: Record; rules: Record }; // `title` is drawn in the link; `label` (kind · title (status)) is its tooltip. type Info = { href: string; title: string; label: string } | null; // A short-lived cache: the same body re-renders on every keystroke in a // preview, and a page of work logs cites the same few records again and again. const CACHE_MS = 60_000; const cache = new Map(); const TASK_KIND_LABEL: Record = { issue: "Issue", spike: "Spike" }; function noteInfo(n: NoteInfo): Info { let kind = "Note"; if (n.is_task) kind = TASK_KIND_LABEL[n.task_kind ?? ""] ?? "Task"; else if (n.note_type === "lesson") kind = "Lesson"; else if (n.note_type === "snippet") kind = "Snippet"; const state = n.is_task && n.status ? ` (${n.status.replace(/_/g, " ")})` : ""; const title = n.title || "Untitled"; return { href: recordHref(n), title, label: `${kind} · ${title}${state}` }; } function milestoneInfo(m: MilestoneInfo): Info { if (m.project_id == null) return null; const title = m.title || "Untitled"; return { href: `/projects/${m.project_id}?milestone=${m.id}`, title, label: `Milestone · ${title}${m.status === "done" ? " (done)" : ""}`, }; } function ruleInfo(r: RuleInfo): Info { const kind = r.kind === "preference" ? "Preference" : "Rule"; const title = r.title || "Untitled"; return { href: `/rules?rule=${r.id}`, title, label: `${kind} · ${title}` }; } // Titles here are often whole sentences; in running text a reference names its // record in a few words and the tooltip carries the rest. const MAX_TITLE = 60; function shorten(title: string): string { if (title.length <= MAX_TITLE) return title; const cut = title.slice(0, MAX_TITLE); const space = cut.lastIndexOf(" "); return (space > MAX_TITLE / 2 ? cut.slice(0, space) : cut).replace(/[\s,.;:—–-]+$/, "") + "…"; } const BLOCK = "p, li, td, th, blockquote, h1, h2, h3, h4, h5, h6"; /** Whether the sentence around this link already names the record — a batch * writes `#9 "Step two"`, and a paragraph citing one record twice names it * the first time. A short title is drawn regardless: three letters turn up * in prose by chance. */ function alreadyNamed(a: HTMLAnchorElement, shown: string, title: string): boolean { if (title.length < 8) return false; const text = (a.closest(BLOCK) ?? a.parentElement)?.textContent?.toLowerCase() ?? ""; return text.includes(title.toLowerCase()) || text.includes(shown.toLowerCase()); } /** Draw the record's title in the link, its number after it, muted. Set as * text, never as markup: a title is whatever its author typed. */ function showTitle(a: HTMLAnchorElement, title: string): boolean { const shown = shorten(title); if (alreadyNamed(a, shown, title)) return false; const name = document.createElement("span"); name.className = "record-ref__title"; name.textContent = shown; const ref = document.createElement("span"); ref.className = "record-ref__id"; ref.textContent = a.textContent ?? ""; a.replaceChildren(name, " ", ref); return true; } function refKey(space: RefSpace, id: number): string { return `${space}:${id}`; } /** What each of these references is, from the cache or one server call. */ export async function resolveRecordRefs(wanted: { space: RefSpace; id: number }[]): Promise> { const now = Date.now(); const out = new Map(); const ask: Record = { notes: [], milestones: [], rules: [] }; for (const w of wanted) { const k = refKey(w.space, w.id); if (out.has(k)) continue; const hit = cache.get(k); if (hit && now - hit.at < CACHE_MS) out.set(k, hit.info); else if (!ask[w.space].includes(w.id)) ask[w.space].push(w.id); } if (ask.notes.length + ask.milestones.length + ask.rules.length === 0) return out; const res = await apiPost("/api/notes/resolve-refs", ask); const store = (space: RefSpace, id: number, info: Info) => { cache.set(refKey(space, id), { at: now, info }); out.set(refKey(space, id), info); }; for (const id of ask.notes) store("notes", id, res.notes[id] ? noteInfo(res.notes[id]) : null); for (const id of ask.milestones) store("milestones", id, res.milestones[id] ? milestoneInfo(res.milestones[id]) : null); for (const id of ask.rules) store("rules", id, res.rules[id] ? ruleInfo(res.rules[id]) : null); return out; } function unresolvedLinks(el: HTMLElement): HTMLAnchorElement[] { return Array.from(el.querySelectorAll("a.record-ref:not([data-ref-state])")); } async function decorate(el: HTMLElement) { const links = unresolvedLinks(el); if (!links.length) return; const wanted = links.map((a) => ({ space: a.dataset.refSpace as RefSpace, id: Number(a.dataset.refId) })); let resolved: Map; try { resolved = await resolveRecordRefs(wanted); } catch { // The links keep their provisional routes, which open the right view for // notes, rules and milestones alike; only the titles are missing. return; } for (const a of links) { if (!a.isConnected) continue; const info = resolved.get(refKey(a.dataset.refSpace as RefSpace, Number(a.dataset.refId))); if (info === undefined) continue; if (info === null) { a.dataset.refState = "missing"; a.classList.add("record-ref--missing"); a.removeAttribute("href"); a.setAttribute("aria-disabled", "true"); a.title = `${a.textContent} — no record you can open`; continue; } a.dataset.refState = "ok"; a.href = info.href; a.title = info.label; const bare = a.textContent; // Drawn with its title, the link's own text is its accessible name; a bare // number needs the label spoken for it. if (!showTitle(a, info.title)) a.setAttribute("aria-label", `${bare}: ${info.label}`); } } const clickHandlers = new WeakMap void>(); function onClick(e: MouseEvent) { const a = (e.target as HTMLElement).closest("a.record-ref") as HTMLAnchorElement | null; if (!a) return; if (a.dataset.refState === "missing") { e.preventDefault(); return; } if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; const href = a.getAttribute("href"); if (!href) return; e.preventDefault(); router.push(href); } export const vRecordRefs: ObjectDirective = { mounted(el) { clickHandlers.set(el, onClick); el.addEventListener("click", onClick); void decorate(el); }, updated(el) { void decorate(el); }, beforeUnmount(el) { const h = clickHandlers.get(el); if (h) el.removeEventListener("click", h); clickHandlers.delete(el); }, };