forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

noteLinks.ts334 lines, 10.5 KiBHistoryRawDownload
1// Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one (or
2// "Create note") replaces "[[query" with the title as a link mark whose href is /notes/<id>.
3// The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same.
4import type { MarkType, Schema } from "prosemirror-model";
5import { Plugin, TextSelection, type EditorState } from "prosemirror-state";
6import type { EditorView } from "prosemirror-view";
7import { t } from "./i18n";
8import { h, keycaps, placeFloating, rangeBox } from "./dom";
9
10interface NoteHit {
11 id: string;
12 title: string;
13}
14
15type Item = { kind: "note"; hit: NoteHit } | { kind: "create"; title: string };
16
17/** "[[" trigger: `from` is the position of the first bracket, `query` the text after it. */
18interface Trigger {
19 from: number;
20 query: string;
21}
22
23const SEARCH_DEBOUNCE_MS = 120;
24
25export interface NoteLinks {
26 plugins: Plugin[];
27}
28
29export function isNoteHref(href: string | null | undefined): boolean {
30 return !!href && href.startsWith("/notes/");
31}
32
33/** The "[[query" right before the cursor, when the cursor is in a textblock outside code. */
34function triggerAt(state: EditorState, code: MarkType): Trigger | null {
35 const { selection } = state;
36 if (!(selection instanceof TextSelection) || !selection.empty) return null;
37 const $from = selection.$from;
38 if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;
39 if (code.isInSet(state.storedMarks || $from.marks())) return null;
40 const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n");
41 // A closing "]]" or a stray bracket ends the match, so the menu closes on its own.
42 const match = /\[\[([^\[\]\n]*)$/.exec(before);
43 if (!match) return null;
44 return { from: $from.pos - match[0].length, query: match[1] };
45}
46
47function parseHits(data: unknown): NoteHit[] {
48 if (!Array.isArray(data)) return [];
49 return data.filter(
50 (x): x is NoteHit =>
51 typeof x === "object" && x !== null && typeof x.id === "string" && typeof x.title === "string",
52 );
53}
54
55async function createNote(title: string): Promise<string> {
56 const res = await fetch("/notes/quick", { method: "POST", body: new URLSearchParams({ title }) });
57 if (!res.ok) throw new Error(`quick ${res.status}`);
58 const id = (await res.text()).trim();
59 if (!id) throw new Error("empty note id");
60 return id;
61}
62
63export function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks {
64 const linkMark = schema.marks.link;
65 const codeMark = schema.marks.code;
66 const currentId = opts.currentNoteId;
67
68 let view: EditorView | null = null;
69 let active: Trigger | null = null;
70 let dismissedFrom: number | null = null;
71 let results: NoteHit[] = [];
72 let loaded = false;
73 let items: Item[] = [];
74 let index = 0;
75 let busy = false;
76 let fetchTimer: ReturnType<typeof setTimeout> | undefined;
77 let controller: AbortController | null = null;
78
79 const menu = h("div", { class: "popover slash-menu note-menu", role: "presentation" });
80 menu.hidden = true;
81 const list = h("div", { class: "slash-list", role: "listbox", "aria-label": t("noteMenu") });
82 const footer = h(
83 "div",
84 { class: "slash-footer", "aria-hidden": "true" },
85 keycaps("↑", "↓"),
86 ` ${t("navigate")} `,
87 keycaps("↵"),
88 ` ${t("insert")} `,
89 keycaps("Esc"),
90 ` ${t("close")}`,
91 );
92 menu.append(list, footer);
93 // Keep focus in the editor while clicking menu items.
94 menu.addEventListener("mousedown", (e) => e.preventDefault());
95
96 function itemText(item: Item): string {
97 if (item.kind === "create") return item.title;
98 return item.hit.title.trim() || t("untitled");
99 }
100
101 function itemLabel(item: Item): string {
102 return item.kind === "create" ? t("createNote", { q: item.title }) : itemText(item);
103 }
104
105 function buildItems(query: string): Item[] {
106 const list: Item[] = results.map((hit): Item => ({ kind: "note", hit }));
107 const q = query.trim();
108 const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase());
109 if (q && !exact) list.push({ kind: "create", title: q });
110 return list;
111 }
112
113 function abortFetch() {
114 clearTimeout(fetchTimer);
115 controller?.abort();
116 controller = null;
117 }
118
119 function close() {
120 abortFetch();
121 active = null;
122 items = [];
123 results = [];
124 loaded = false;
125 index = 0;
126 menu.hidden = true;
127 view?.dom.removeAttribute("aria-activedescendant");
128 }
129
130 async function search(query: string) {
131 const ctrl = new AbortController();
132 controller = ctrl;
133 try {
134 const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, {
135 signal: ctrl.signal,
136 headers: { accept: "application/json" },
137 });
138 if (!res.ok) throw new Error(`titles ${res.status}`);
139 const data: unknown = await res.json();
140 if (ctrl.signal.aborted) return;
141 results = parseHits(data).filter((hit) => hit.id !== currentId);
142 } catch (err) {
143 if (ctrl.signal.aborted) return;
144 console.error("note search failed", err);
145 results = [];
146 }
147 if (controller === ctrl) controller = null;
148 loaded = true;
149 renderList();
150 }
151
152 function scheduleSearch(query: string) {
153 abortFetch();
154 loaded = false;
155 fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS);
156 }
157
158 function markActive() {
159 if (!view) return;
160 const rows = list.querySelectorAll<HTMLElement>(".slash-item");
161 rows.forEach((row, i) => row.setAttribute("aria-selected", String(i === index)));
162 const row = rows[index];
163 if (row) {
164 view.dom.setAttribute("aria-activedescendant", row.id);
165 row.scrollIntoView({ block: "nearest" });
166 }
167 }
168
169 function setIndex(i: number) {
170 index = i;
171 markActive();
172 }
173
174 function renderList() {
175 if (!view || !active) return;
176 items = buildItems(active.query);
177 if (index >= items.length) index = 0;
178 if (items.length === 0) {
179 // Only shown once the search for this query has answered; an empty query with no notes lands here.
180 list.replaceChildren(
181 ...(loaded ? [h("div", { class: "slash-empty", role: "presentation" }, t("noNotesFound"))] : []),
182 );
183 view.dom.removeAttribute("aria-activedescendant");
184 return;
185 }
186 list.replaceChildren(
187 ...items.map((item, i) => {
188 const el = h(
189 "div",
190 { class: "slash-item", role: "option", id: `note-opt-${i}`, "aria-selected": String(i === index) },
191 h("span", { class: "slash-label" }, itemLabel(item)),
192 );
193 el.addEventListener("mouseenter", () => setIndex(i));
194 el.addEventListener("click", () => pick(item));
195 return el;
196 }),
197 );
198 markActive();
199 }
200
201 function place(v: EditorView) {
202 if (!active) return;
203 placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), "below");
204 }
205
206 /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */
207 function insertLink(v: EditorView, from: number, to: number, text: string, id: string) {
208 const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })]));
209 const end = from + text.length;
210 tr.insert(end, schema.text(" "));
211 tr.setSelection(TextSelection.create(tr.doc, end + 1));
212 tr.setStoredMarks([]);
213 v.dispatch(tr.scrollIntoView());
214 v.focus();
215 }
216
217 async function createAndInsert(v: EditorView, from: number, to: number, title: string) {
218 // The range as it reads now; if the user edits it while the request runs, nothing is inserted.
219 const before = v.state.doc.textBetween(from, to);
220 busy = true;
221 let id: string;
222 try {
223 id = await createNote(title);
224 } catch (err) {
225 console.error("note create failed", err);
226 return;
227 } finally {
228 busy = false;
229 }
230 const cur = view;
231 if (!cur) return;
232 const sel = cur.state.selection;
233 if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return;
234 insertLink(cur, from, to, title, id);
235 }
236
237 function pick(item: Item) {
238 const v = view;
239 if (!v || !active || busy) return;
240 const { from } = active;
241 const to = v.state.selection.from;
242 if (item.kind === "note") {
243 insertLink(v, from, to, itemText(item), item.hit.id);
244 return;
245 }
246 void createAndInsert(v, from, to, item.title);
247 }
248
249 /** Opens, refetches or closes the menu from the current selection. */
250 function sync(v: EditorView) {
251 view = v;
252 const trig = triggerAt(v.state, codeMark);
253 if (!trig) {
254 dismissedFrom = null;
255 close();
256 return;
257 }
258 if (trig.from === dismissedFrom) {
259 close();
260 return;
261 }
262 const changed = !active || trig.from !== active.from || trig.query !== active.query;
263 active = trig;
264 if (changed) {
265 index = 0;
266 scheduleSearch(trig.query);
267 }
268 menu.hidden = false;
269 if (changed) renderList();
270 place(v);
271 }
272
273 const plugin = new Plugin({
274 props: {
275 handleKeyDown(v, e) {
276 if (!active) return false;
277 const n = items.length;
278 if (e.key === "Escape") {
279 dismissedFrom = active.from;
280 close();
281 return true;
282 }
283 if (e.key === "ArrowDown" && n) {
284 setIndex((index + 1) % n);
285 return true;
286 }
287 if (e.key === "ArrowUp" && n) {
288 setIndex((index - 1 + n) % n);
289 return true;
290 }
291 if ((e.key === "Enter" || e.key === "Tab") && n) {
292 if (!busy) pick(items[index]);
293 return true;
294 }
295 return false;
296 },
297 // Ctrl/Cmd+click on a note link opens the note in this tab.
298 handleDOMEvents: {
299 click(_view, event) {
300 if (!(event.ctrlKey || event.metaKey)) return false;
301 const anchor = (event.target as Element | null)?.closest?.("a");
302 const href = anchor?.getAttribute("href");
303 if (!href || !isNoteHref(href)) return false;
304 event.preventDefault();
305 location.assign(href);
306 return true;
307 },
308 },
309 },
310 view(v) {
311 view = v;
312 document.body.append(menu);
313 const onViewport = () => {
314 if (view) place(view);
315 };
316 window.addEventListener("scroll", onViewport, { capture: true, passive: true });
317 window.addEventListener("resize", onViewport);
318 return {
319 update(u) {
320 sync(u);
321 },
322 destroy() {
323 window.removeEventListener("scroll", onViewport, { capture: true });
324 window.removeEventListener("resize", onViewport);
325 abortFetch();
326 menu.remove();
327 view = null;
328 },
329 };
330 },
331 });
332
333 return { plugins: [plugin] };
334}