Files
FabledGrimoire/frontend/src/directives/recordRefs.ts
T
bvandeusenandClaude Opus 5.5 da7c43aa8a
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m48s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 36s
feat(7741): a record reference shows the title of what it cites, before its number
A cited #N, milestone N or rule N in a rendered body now reads as the
record's title followed by its number, muted, so a reader knows what is
cited without hovering. The stored text stays #N and the title is read at
render: every existing record benefits and an edited title shows wherever
it is cited. Titles past 60 characters are shortened at a word, with the
full kind, title and status in the tooltip. A reference whose paragraph
already names the record (a batch writes #9 "Step two") keeps the bare
number, as does one the reader cannot open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:49:30 -05:00

200 lines
8.1 KiB
TypeScript

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:
* <div class="prose" v-html="renderMarkdown(body)" v-record-refs />
*
* 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<string, NoteInfo>; milestones: Record<string, MilestoneInfo>; rules: Record<string, RuleInfo> };
// `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<string, { at: number; info: Info }>();
const TASK_KIND_LABEL: Record<string, string> = { 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<Map<string, Info>> {
const now = Date.now();
const out = new Map<string, Info>();
const ask: Record<RefSpace, number[]> = { 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<Resolved>("/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<HTMLAnchorElement>("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<string, Info>;
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<HTMLElement, (e: MouseEvent) => 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<HTMLElement> = {
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);
},
};