// Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one (or // "Create note") replaces "[[query" with the title as a link mark whose href is /notes/. // The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same. import type { MarkType, Schema } from "prosemirror-model"; import { Plugin, TextSelection, type EditorState } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; import { t } from "./i18n"; import { h, keycaps, placeFloating, rangeBox } from "./dom"; interface NoteHit { id: string; title: string; } type Item = { kind: "note"; hit: NoteHit } | { kind: "create"; title: string }; /** "[[" trigger: `from` is the position of the first bracket, `query` the text after it. */ interface Trigger { from: number; query: string; } const SEARCH_DEBOUNCE_MS = 120; export interface NoteLinks { plugins: Plugin[]; } export function isNoteHref(href: string | null | undefined): boolean { return !!href && href.startsWith("/notes/"); } /** The "[[query" right before the cursor, when the cursor is in a textblock outside code. */ function triggerAt(state: EditorState, code: MarkType): Trigger | null { const { selection } = state; if (!(selection instanceof TextSelection) || !selection.empty) return null; const $from = selection.$from; if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null; if (code.isInSet(state.storedMarks || $from.marks())) return null; const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); // A closing "]]" or a stray bracket ends the match, so the menu closes on its own. const match = /\[\[([^\[\]\n]*)$/.exec(before); if (!match) return null; return { from: $from.pos - match[0].length, query: match[1] }; } function parseHits(data: unknown): NoteHit[] { if (!Array.isArray(data)) return []; return data.filter( (x): x is NoteHit => typeof x === "object" && x !== null && typeof x.id === "string" && typeof x.title === "string", ); } async function createNote(title: string): Promise { const res = await fetch("/notes/quick", { method: "POST", body: new URLSearchParams({ title }) }); if (!res.ok) throw new Error(`quick ${res.status}`); const id = (await res.text()).trim(); if (!id) throw new Error("empty note id"); return id; } export function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks { const linkMark = schema.marks.link; const codeMark = schema.marks.code; const currentId = opts.currentNoteId; let view: EditorView | null = null; let active: Trigger | null = null; let dismissedFrom: number | null = null; let results: NoteHit[] = []; let loaded = false; let items: Item[] = []; let index = 0; let busy = false; let fetchTimer: ReturnType | undefined; let controller: AbortController | null = null; const menu = h("div", { class: "popover slash-menu note-menu", role: "presentation" }); menu.hidden = true; const list = h("div", { class: "slash-list", role: "listbox", "aria-label": t("noteMenu") }); const footer = h( "div", { class: "slash-footer", "aria-hidden": "true" }, keycaps("↑", "↓"), ` ${t("navigate")} `, keycaps("↵"), ` ${t("insert")} `, keycaps("Esc"), ` ${t("close")}`, ); menu.append(list, footer); // Keep focus in the editor while clicking menu items. menu.addEventListener("mousedown", (e) => e.preventDefault()); function itemText(item: Item): string { if (item.kind === "create") return item.title; return item.hit.title.trim() || t("untitled"); } function itemLabel(item: Item): string { return item.kind === "create" ? t("createNote", { q: item.title }) : itemText(item); } function buildItems(query: string): Item[] { const list: Item[] = results.map((hit): Item => ({ kind: "note", hit })); const q = query.trim(); const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase()); if (q && !exact) list.push({ kind: "create", title: q }); return list; } function abortFetch() { clearTimeout(fetchTimer); controller?.abort(); controller = null; } function close() { abortFetch(); active = null; items = []; results = []; loaded = false; index = 0; menu.hidden = true; view?.dom.removeAttribute("aria-activedescendant"); } async function search(query: string) { const ctrl = new AbortController(); controller = ctrl; try { const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, { signal: ctrl.signal, headers: { accept: "application/json" }, }); if (!res.ok) throw new Error(`titles ${res.status}`); const data: unknown = await res.json(); if (ctrl.signal.aborted) return; results = parseHits(data).filter((hit) => hit.id !== currentId); } catch (err) { if (ctrl.signal.aborted) return; console.error("note search failed", err); results = []; } if (controller === ctrl) controller = null; loaded = true; renderList(); } function scheduleSearch(query: string) { abortFetch(); loaded = false; fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS); } function markActive() { if (!view) return; const rows = list.querySelectorAll(".slash-item"); rows.forEach((row, i) => row.setAttribute("aria-selected", String(i === index))); const row = rows[index]; if (row) { view.dom.setAttribute("aria-activedescendant", row.id); row.scrollIntoView({ block: "nearest" }); } } function setIndex(i: number) { index = i; markActive(); } function renderList() { if (!view || !active) return; items = buildItems(active.query); if (index >= items.length) index = 0; if (items.length === 0) { // Only shown once the search for this query has answered; an empty query with no notes lands here. list.replaceChildren( ...(loaded ? [h("div", { class: "slash-empty", role: "presentation" }, t("noNotesFound"))] : []), ); view.dom.removeAttribute("aria-activedescendant"); return; } list.replaceChildren( ...items.map((item, i) => { const el = h( "div", { class: "slash-item", role: "option", id: `note-opt-${i}`, "aria-selected": String(i === index) }, h("span", { class: "slash-label" }, itemLabel(item)), ); el.addEventListener("mouseenter", () => setIndex(i)); el.addEventListener("click", () => pick(item)); return el; }), ); markActive(); } function place(v: EditorView) { if (!active) return; placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), "below"); } /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */ function insertLink(v: EditorView, from: number, to: number, text: string, id: string) { const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })])); const end = from + text.length; tr.insert(end, schema.text(" ")); tr.setSelection(TextSelection.create(tr.doc, end + 1)); tr.setStoredMarks([]); v.dispatch(tr.scrollIntoView()); v.focus(); } async function createAndInsert(v: EditorView, from: number, to: number, title: string) { // The range as it reads now; if the user edits it while the request runs, nothing is inserted. const before = v.state.doc.textBetween(from, to); busy = true; let id: string; try { id = await createNote(title); } catch (err) { console.error("note create failed", err); return; } finally { busy = false; } const cur = view; if (!cur) return; const sel = cur.state.selection; if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return; insertLink(cur, from, to, title, id); } function pick(item: Item) { const v = view; if (!v || !active || busy) return; const { from } = active; const to = v.state.selection.from; if (item.kind === "note") { insertLink(v, from, to, itemText(item), item.hit.id); return; } void createAndInsert(v, from, to, item.title); } /** Opens, refetches or closes the menu from the current selection. */ function sync(v: EditorView) { view = v; const trig = triggerAt(v.state, codeMark); if (!trig) { dismissedFrom = null; close(); return; } if (trig.from === dismissedFrom) { close(); return; } const changed = !active || trig.from !== active.from || trig.query !== active.query; active = trig; if (changed) { index = 0; scheduleSearch(trig.query); } menu.hidden = false; if (changed) renderList(); place(v); } const plugin = new Plugin({ props: { handleKeyDown(v, e) { if (!active) return false; const n = items.length; if (e.key === "Escape") { dismissedFrom = active.from; close(); return true; } if (e.key === "ArrowDown" && n) { setIndex((index + 1) % n); return true; } if (e.key === "ArrowUp" && n) { setIndex((index - 1 + n) % n); return true; } if ((e.key === "Enter" || e.key === "Tab") && n) { if (!busy) pick(items[index]); return true; } return false; }, // Ctrl/Cmd+click on a note link opens the note in this tab. handleDOMEvents: { click(_view, event) { if (!(event.ctrlKey || event.metaKey)) return false; const anchor = (event.target as Element | null)?.closest?.("a"); const href = anchor?.getAttribute("href"); if (!href || !isNoteHref(href)) return false; event.preventDefault(); location.assign(href); return true; }, }, }, view(v) { view = v; document.body.append(menu); const onViewport = () => { if (view) place(view); }; window.addEventListener("scroll", onViewport, { capture: true, passive: true }); window.addEventListener("resize", onViewport); return { update(u) { sync(u); }, destroy() { window.removeEventListener("scroll", onViewport, { capture: true }); window.removeEventListener("resize", onViewport); abortFetch(); menu.remove(); view = null; }, }; }, }); return { plugins: [plugin] }; }