diff --git a/frontend/src/assets/prose.css b/frontend/src/assets/prose.css index ede3b289..5a280128 100644 --- a/frontend/src/assets/prose.css +++ b/frontend/src/assets/prose.css @@ -147,6 +147,37 @@ text-decoration: none; } +/* A record reference — `#4286`, `milestone 639`, `rule 34`. Reads as a link in + running text rather than a chip: a work log cites a dozen of them, and a row + of pills would drown the sentence they sit in. */ +.record-ref { + color: var(--fs-wikilink); + text-decoration: underline; + text-decoration-color: color-mix(in srgb, var(--fs-wikilink) 40%, transparent); + text-underline-offset: 0.15em; + font-variant-numeric: tabular-nums; + border-radius: var(--fs-radius-sm); + cursor: pointer; +} + +.record-ref:hover { + text-decoration-color: currentColor; +} + +.record-ref:focus-visible { + outline: none; + box-shadow: var(--fs-focus-ring); +} + +/* One the reader cannot open: missing, trashed or not shared. Still legible — + the number is part of the sentence — but plainly not a way through. */ +.record-ref--missing { + color: var(--fs-text-tertiary-fg); + text-decoration-style: dashed; + text-decoration-color: var(--fs-text-tertiary); + cursor: default; +} + /* Task list */ .prose ul[data-type="taskList"] { list-style: none; diff --git a/frontend/src/components/TaskLogSection.vue b/frontend/src/components/TaskLogSection.vue index dc8ed2ef..bdf02dd1 100644 --- a/frontend/src/components/TaskLogSection.vue +++ b/frontend/src/components/TaskLogSection.vue @@ -2,6 +2,7 @@ import { ref, onMounted } from "vue"; import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client"; import { renderMarkdown } from "@/utils/markdown"; +import { vRecordRefs } from "@/directives/recordRefs"; import type { TaskLog } from "@/types/task"; import { fmtStamp } from "@/utils/dateFormat"; @@ -131,7 +132,7 @@ onMounted(loadLogs); -
+
diff --git a/frontend/src/composables/useAutocomplete.ts b/frontend/src/composables/useAutocomplete.ts index 97245609..d29d806b 100644 --- a/frontend/src/composables/useAutocomplete.ts +++ b/frontend/src/composables/useAutocomplete.ts @@ -51,7 +51,8 @@ export function useAutocomplete( // Must be start of line or preceded by whitespace if (i === 0 || /\s/.test(text[i - 1])) { const query = text.slice(i + 1, cursor); - if (/^[\w/]*$/.test(query)) { + // Digits alone are a record reference being typed (`#4286`), not a tag. + if (/^[\w/]*$/.test(query) && !/^\d+$/.test(query)) { acTriggerStart = i; acType = "tag"; debouncedSearch(query); diff --git a/frontend/src/directives/recordRefs.ts b/frontend/src/directives/recordRefs.ts new file mode 100644 index 00000000..546d7b95 --- /dev/null +++ b/frontend/src/directives/recordRefs.ts @@ -0,0 +1,149 @@ +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 kind and title as a tooltip + * and accessible name, and a "leads nowhere" style when the reader cannot open + * it: missing, trashed and not-shared-with-you look the same, on purpose. + * 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 }; +type Info = { href: 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, " ")})` : ""; + return { href: recordHref(n), label: `${kind} · ${n.title || "Untitled"}${state}` }; +} + +function milestoneInfo(m: MilestoneInfo): Info { + if (m.project_id == null) return null; + return { + href: `/projects/${m.project_id}?milestone=${m.id}`, + label: `Milestone · ${m.title || "Untitled"}${m.status === "done" ? " (done)" : ""}`, + }; +} + +function ruleInfo(r: RuleInfo): Info { + const kind = r.kind === "preference" ? "Preference" : "Rule"; + return { href: `/rules?rule=${r.id}`, label: `${kind} · ${r.title || "Untitled"}` }; +} + +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; + a.setAttribute("aria-label", `${a.textContent}: ${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); + }, +}; diff --git a/frontend/src/extensions/TagDecoration.ts b/frontend/src/extensions/TagDecoration.ts index c35d0991..fe522172 100644 --- a/frontend/src/extensions/TagDecoration.ts +++ b/frontend/src/extensions/TagDecoration.ts @@ -2,7 +2,9 @@ import { Extension } from "@tiptap/core"; import { Plugin, PluginKey } from "@tiptap/pm/state"; import { Decoration, DecorationSet } from "@tiptap/pm/view"; -const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g; +// Digits alone (`#4286`) are a record reference, not a tag, and are left plain +// here; the rendered view links them (utils/recordRefs.ts). +const TAG_RE = /(?<=\s|^)#(?!\d+(?![\w/-]))([\w]+(?:\/[\w]+)*)/g; export const TagDecoration = Extension.create({ name: "tagDecoration", diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 056c64fb..ca444829 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -123,6 +123,26 @@ const router = createRouter({ name: "project-view", component: () => import("@/views/ProjectView.vue"), }, + { + // Where a `milestone N` reference leads. A milestone is shown on its + // project's board, so this only looks up which project and goes there. + path: "/milestones/:id", + name: "milestone", + component: () => import("@/views/ProjectListView.vue"), + beforeEnter: async (to) => { + const id = Number(to.params.id); + const { resolveRecordRefs } = await import("@/directives/recordRefs"); + try { + const found = (await resolveRecordRefs([{ space: "milestones", id }])).get(`milestones:${id}`); + if (found) return found.href; + } catch { + // Fall through to the projects list with the notice below. + } + const { useToastStore } = await import("@/stores/toast"); + useToastStore().show(`No milestone ${id} you can open`, "warning"); + return { name: "projects" }; + }, + }, { path: "/rules", name: "rules", diff --git a/frontend/src/utils/markdown.ts b/frontend/src/utils/markdown.ts index 4b3dc0ca..3f1d6302 100644 --- a/frontend/src/utils/markdown.ts +++ b/frontend/src/utils/markdown.ts @@ -1,6 +1,7 @@ import { marked, type RendererThis, type Tokens } from "marked"; import DOMPurify from "dompurify"; import { linkifyTags, linkifyWikilinks } from "@/utils/tags"; +import { linkifyRecordRefs } from "@/utils/recordRefs"; function decodeEntities(text: string): string { const textarea = document.createElement("textarea"); @@ -20,9 +21,11 @@ export function slugify(text: string): string { export function stripFirstLineTags(text: string): string { const match = text.match(/^[ \t]*((?:(? /^#[\w]+(?:\/[\w]+)*$/.test(t)); + const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t)); if (!allTags) return text; return text.slice(match[0].length); } @@ -38,7 +41,7 @@ const headingRenderer = { marked.use({ renderer: headingRenderer }); const PURIFY_OPTS_FULL = { - ADD_ATTR: ["data-tag", "data-title", "data-task-index"], + ADD_ATTR: ["data-tag", "data-title", "data-task-index", "data-ref-space", "data-ref-id"], FORCE_BODY: true, }; @@ -64,7 +67,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } = } const withTags = linkifyTags(html); - const withLinks = linkifyWikilinks(withTags); + const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags)); const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL); // marked escapes ' to ' — replace after sanitization to ensure clean rendering return sanitized.replace(/'/g, "'"); diff --git a/frontend/src/utils/recordRefs.ts b/frontend/src/utils/recordRefs.ts new file mode 100644 index 00000000..1f1a8fc0 --- /dev/null +++ b/frontend/src/utils/recordRefs.ts @@ -0,0 +1,104 @@ +/** Record references in rendered prose: `#N`, `milestone N`, `rule N`. + * + * Three id spaces, three forms: + * `#N` a note, task, lesson or snippet (one sequence, the notes table) + * `milestone N` a milestone — the form a batch create writes for `{{ref:milestone}}` + * `rule N` a rule; `preference N` too, since a preference is a rule + * A `#N` after a word that names another numbering ("PR #198", "rule #34", + * "step #3") is not a note, and stays plain text. + * + * The backend reads references with the same patterns and the same word list + * (src/grimoire/services/record_refs.py: REF_RE, PROSE_REF_RE, _OTHER_SPACE), + * so a backlink, a graph edge and a rendered link agree about what a body + * cites. tests/test_record_ref_links.py fails when the two differ. + * + * linkifyRecordRefs only marks the references up. What each one IS — its + * route, its title, whether the reader can open it — is filled in after render + * by the v-record-refs directive (directives/recordRefs.ts), which asks the + * server once per rendered body. + */ + +export const NOTE_REF_RE = /(? start < f.end && end > f.start)) continue; + if (OTHER_SPACE_SET.has(prevWord(context + text.slice(0, start)))) continue; + found.push({ start, end, space: "notes", id: Number(m[1]) }); + } + return found.sort((a, b) => a.start - b.start); +} + +/** Where a reference opens before the server has said what it is. A note id + * may turn out to be a task, lesson or snippet; the directive corrects it. */ +export function provisionalHref(space: RefSpace, id: number): string { + if (space === "milestones") return `/milestones/${id}`; + if (space === "rules") return `/rules?rule=${id}`; + return `/notes/${id}`; +} + +// Markup a reference is never drawn inside: an existing link (a wikilink, a +// markdown link, a tag chip), code, and the tags themselves. +const SKIP_RE = /(|||<[^>]+>)/gi; + +/** Wrap each record reference in rendered HTML in an `a.record-ref`. */ +export function linkifyRecordRefs(html: string): string { + const parts = html.split(SKIP_RE); + let context = ""; + return parts + .map((part, i) => { + // Odd indices are markup the split kept; text between them is even. + if (i % 2 === 1) return part; + const refs = findRecordRefs(part, context); + context = (context + part).slice(-80); + if (!refs.length) return part; + let out = ""; + let at = 0; + for (const r of refs) { + out += part.slice(at, r.start); + const label = part.slice(r.start, r.end); + out += `${label}`; + at = r.end; + } + return out + part.slice(at); + }) + .join(""); +} diff --git a/frontend/src/utils/tags.ts b/frontend/src/utils/tags.ts index 05949b50..14141b30 100644 --- a/frontend/src/utils/tags.ts +++ b/frontend/src/utils/tags.ts @@ -1,5 +1,9 @@ const CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/g; -const TAG_RE = /(?/g, ">"); diff --git a/frontend/src/views/GraphView.vue b/frontend/src/views/GraphView.vue index e6eec38b..bc7a260d 100644 --- a/frontend/src/views/GraphView.vue +++ b/frontend/src/views/GraphView.vue @@ -8,6 +8,7 @@ import { drag } from "d3-drag"; import { select } from "d3-selection"; import { apiGet } from "@/api/client"; import { renderMarkdown } from "@/utils/markdown"; +import { vRecordRefs } from "@/directives/recordRefs"; const router = useRouter(); @@ -26,7 +27,8 @@ interface GraphNode extends SimulationNodeDatum { interface GraphEdge { source: number | string | GraphNode; target: number | string | GraphNode; - type: "wikilink" | "tag"; + /** wikilink: `[[title]]`; reference: a `#N` citation; tag: a shared tag. */ + type: "wikilink" | "reference" | "tag"; } interface Project { @@ -237,12 +239,14 @@ function initGraph() { .append("line") .attr("class", "graph-edge") .attr("stroke", (d: any) => - d.type === "wikilink" ? "var(--fs-accent)" : "var(--fs-text-tertiary)" + d.type === "tag" ? "var(--fs-text-tertiary)" : "var(--fs-accent)" ) - .attr("stroke-opacity", (d: any) => (d.type === "wikilink" ? 0.5 : 0.4)) - .attr("stroke-dasharray", null) - .attr("stroke-width", (d: any) => (d.type === "wikilink" ? 1.5 : 1)) - .attr("marker-end", (d: any) => (d.type === "wikilink" ? "url(#arrow)" : null)); + .attr("stroke-opacity", (d: any) => (d.type === "tag" ? 0.4 : 0.5)) + // A citation is a looser link than a wikilink: same colour and direction, + // drawn dashed so the two read apart. + .attr("stroke-dasharray", (d: any) => (d.type === "reference" ? "4 3" : null)) + .attr("stroke-width", (d: any) => (d.type === "tag" ? 1 : 1.5)) + .attr("marker-end", (d: any) => (d.type === "tag" ? null : "url(#arrow)")); // Node groups const nodeSel = zoomG @@ -559,7 +563,7 @@ onUnmounted(() => {
No content.
diff --git a/frontend/src/views/LessonDetailView.vue b/frontend/src/views/LessonDetailView.vue index a44f2ef3..a231f81e 100644 --- a/frontend/src/views/LessonDetailView.vue +++ b/frontend/src/views/LessonDetailView.vue @@ -40,6 +40,7 @@ import UsageBadge from "@/components/UsageBadge.vue"; import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight"; import { useToastStore } from "@/stores/toast"; import { renderMarkdown } from "@/utils/markdown"; +import { vRecordRefs } from "@/directives/recordRefs"; import { canWriteRecord } from "@/utils/permission"; import { recordHref } from "@/utils/recordHref"; @@ -171,7 +172,7 @@ onMounted(load);

No detail was recorded — the claim above is the whole lesson. diff --git a/frontend/src/views/NoteEditorView.vue b/frontend/src/views/NoteEditorView.vue index 9a792d4b..879f1550 100644 --- a/frontend/src/views/NoteEditorView.vue +++ b/frontend/src/views/NoteEditorView.vue @@ -5,6 +5,7 @@ import type { NoteType } from "@/types/note"; import { useNotesStore } from "@/stores/notes"; import { useToastStore } from "@/stores/toast"; import { renderMarkdown } from "@/utils/markdown"; +import { vRecordRefs } from "@/directives/recordRefs"; import { useAssist, type NoteDraft } from "@/composables/useAssist"; import { useAutoSave } from "@/composables/useAutoSave"; import { useEditorGuards } from "@/composables/useEditorGuards"; @@ -439,7 +440,7 @@ onUnmounted(() => assist.clearSelection());

diff --git a/frontend/src/views/NoteViewerView.vue b/frontend/src/views/NoteViewerView.vue index 9f65ae47..8bb5b58b 100644 --- a/frontend/src/views/NoteViewerView.vue +++ b/frontend/src/views/NoteViewerView.vue @@ -3,6 +3,8 @@ import { onMounted, computed, ref, watch } from "vue"; import { useRoute, useRouter } from "vue-router"; import { useNotesStore } from "@/stores/notes"; import { renderMarkdown } from "@/utils/markdown"; +import { vRecordRefs } from "@/directives/recordRefs"; +import { recordHref } from "@/utils/recordHref"; import { relativeTime } from "@/composables/useRelativeTime"; import { apiPost, apiGet, apiPatch } from "@/api/client"; import type { Note } from "@/types/note"; @@ -14,7 +16,12 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next"; const route = useRoute(); const router = useRouter(); const store = useNotesStore(); -const backlinks = ref<{ type: string; id: number; title: string }[]>([]); +/** What links here, and how: a `[[title]]` wikilink or a `#N` reference in a + * body or work log. */ +const backlinks = ref<{ + type: string; id: number; title: string; + is_task?: boolean; note_type?: string; via?: "wikilink" | "reference"; +}[]>([]); const converting = ref(false); const showShare = ref(false); @@ -259,7 +266,7 @@ async function convertToTask() {
@@ -274,7 +281,8 @@ async function convertToTask() { {{ link.type }} diff --git a/frontend/src/views/ProjectView.vue b/frontend/src/views/ProjectView.vue index 7e445283..e55db8f8 100644 --- a/frontend/src/views/ProjectView.vue +++ b/frontend/src/views/ProjectView.vue @@ -1,5 +1,5 @@