forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

floating.ts453 lines, 17.1 KiBHistoryRawDownload
1// Floating editor UI, all plain DOM on <body> and positioned from view.coordsAtPos:
2// - selection bubble menu (formatting, shown for a non-empty text selection),
3// - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked),
4// - slash menu (typing "/" at the start of a block or after a space).
5// One ProseMirror plugin keeps them in sync with the editor state.
6import type { MarkType, Schema } from "prosemirror-model";
7import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state";
8import type { EditorView } from "prosemirror-view";
9import { t } from "./i18n";
10import { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from "./editing";
11import { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from "./dom";
12import { isNoteHref } from "./noteLinks";
13
14interface BubbleItem {
15 id: string;
16 label: string;
17 glyph: string;
18 keys: string[];
19 run: Command;
20 active: (state: EditorState) => boolean;
21}
22
23interface SlashItem {
24 id: string;
25 label: string;
26 /** English words the filter also matches, so "h2" or "list" work in either language. */
27 keywords: string;
28 keys: string[];
29 run: Command;
30}
31
32export interface Floating {
33 plugins: Plugin[];
34 /** Opens the link popover for the selection, or for the link the cursor is in. */
35 openLink(view: EditorView): void;
36}
37
38interface LinkState {
39 from: number;
40 to: number;
41 mode: "edit" | "view";
42 /** Existing href at the range, if any. */
43 href: string | null;
44}
45
46/** Position of an open "/query" trigger and what has been typed after the slash. */
47function slashContext(state: EditorState): { from: number; query: string } | null {
48 const { selection } = state;
49 if (!(selection instanceof TextSelection) || !selection.empty) return null;
50 const $from = selection.$from;
51 if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;
52 const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n");
53 const match = /(?:^|\s)\/([^\s/]*)$/.exec(before);
54 if (!match) return null;
55 return { from: $from.pos - match[1].length - 1, query: match[1] };
56}
57
58function hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null {
59 let href: string | null = null;
60 state.doc.nodesBetween(from, to, (node) => {
61 if (href !== null) return false;
62 const mark = type.isInSet(node.marks);
63 if (mark) href = String(mark.attrs.href);
64 return href === null;
65 });
66 return href;
67}
68
69export function createFloating(schema: Schema, editing: Editing): Floating {
70 const { strong, em, code, link: linkMark } = schema.marks;
71 const { heading } = schema.nodes;
72
73 let view: EditorView | null = null;
74 let bubbleDismissed = false;
75 let link: LinkState | null = null;
76 let slashFrom: number | null = null;
77 let slashQuery = "";
78 let slashIndex = 0;
79 let slashFiltered: SlashItem[] = [];
80 let slashDismissed: number | null = null;
81
82 // ---- Bubble menu ----
83 const bubbleItems: BubbleItem[] = [
84 { id: "bold", label: t("bold"), glyph: "B", keys: [MOD, "B"], run: editing.bold, active: (s) => isMarkActive(s, strong) },
85 { id: "italic", label: t("italic"), glyph: "I", keys: [MOD, "I"], run: editing.italic, active: (s) => isMarkActive(s, em) },
86 { id: "code", label: t("inlineCode"), glyph: "</>", keys: [MOD, "E"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) },
87 { id: "link", label: t("link"), glyph: "Link", keys: [MOD, "K"], run: editing.link, active: (s) => isMarkActive(s, linkMark) },
88 { id: "h1", label: t("heading1"), glyph: "H1", keys: [MOD, ALT, "1"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) },
89 { id: "h2", label: t("heading2"), glyph: "H2", keys: [MOD, ALT, "2"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) },
90 { id: "h3", label: t("heading3"), glyph: "H3", keys: [MOD, ALT, "3"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) },
91 ];
92
93 const bubble = h("div", { class: "bubble", role: "toolbar", "aria-label": t("bubbleLabel") });
94 bubble.hidden = true;
95 const bubbleButtons = bubbleItems.map((item) => {
96 const btn = h(
97 "button",
98 { type: "button", class: "bubble-btn", "aria-label": item.label, "data-command": item.id },
99 h("span", { class: "bubble-glyph", "aria-hidden": "true" }, item.glyph),
100 tooltip(item.label, item.keys),
101 );
102 btn.addEventListener("click", () => {
103 if (!view) return;
104 item.run(view.state, view.dispatch, view);
105 if (item.id !== "link") view.focus();
106 });
107 bubble.append(btn);
108 return { btn, item };
109 });
110 // Keep the text selection while pressing bubble buttons.
111 bubble.addEventListener("mousedown", (e) => e.preventDefault());
112
113 // ---- Link popover (edit and view panels share one element) ----
114 const linkPop = h("div", { class: "popover link-popover", role: "dialog", "aria-label": t("linkDialog") });
115 linkPop.hidden = true;
116
117 const editPanel = h("form", { class: "link-edit", novalidate: "" });
118 const linkInput = h("input", {
119 type: "text",
120 class: "link-input",
121 inputmode: "url",
122 autocomplete: "off",
123 autocapitalize: "off",
124 spellcheck: "false",
125 placeholder: "https://",
126 "aria-label": t("linkUrl"),
127 "aria-describedby": "link-error",
128 });
129 const linkError = h("p", { class: "link-error", id: "link-error", role: "alert" });
130 linkError.hidden = true;
131 const applyBtn = h("button", { type: "submit", class: "btn btn-primary" }, t("apply"), keycaps("↵"));
132 const editRemove = h("button", { type: "button", class: "btn" }, t("remove"));
133 const editOpen = h("button", { type: "button", class: "btn" }, t("open"));
134 editPanel.append(
135 h("div", { class: "link-row" }, linkInput, applyBtn),
136 linkError,
137 h("div", { class: "link-actions" }, editRemove, editOpen),
138 );
139
140 // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items.
141 const viewPanel = h("div", { class: "link-view", role: "menu", "aria-label": t("linkMenu") });
142 const linkHref = h("span", { class: "link-href" });
143 const viewEdit = h("button", { type: "button", class: "btn", role: "menuitem" }, t("edit"));
144 const viewRemove = h("button", { type: "button", class: "btn", role: "menuitem" }, t("remove"));
145 const viewOpen = h("button", { type: "button", class: "btn", role: "menuitem" }, t("open"));
146 viewPanel.append(linkHref, h("div", { class: "link-actions", role: "none" }, viewEdit, viewRemove, viewOpen));
147
148 linkPop.append(editPanel, viewPanel);
149
150 function closeLink(restoreFocus: boolean) {
151 if (!link) return;
152 link = null;
153 linkPop.hidden = true;
154 if (restoreFocus) view?.focus();
155 }
156
157 function showLink(v: EditorView, from: number, to: number, mode: "edit" | "view") {
158 closeSlash();
159 const href = hrefInRange(v.state, from, to, linkMark);
160 link = { from, to, mode, href };
161 linkPop.hidden = false;
162 editPanel.hidden = mode !== "edit";
163 viewPanel.hidden = mode !== "view";
164 linkError.hidden = true;
165 linkInput.removeAttribute("aria-invalid");
166 linkInput.value = href ?? "";
167 linkHref.textContent = href ?? "";
168 for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) {
169 btn.disabled = href === null;
170 btn.title = href === null ? t("linkNeedsLink") : "";
171 }
172 renderFloating(v);
173 if (mode === "edit") {
174 linkInput.focus();
175 linkInput.select();
176 } else {
177 viewEdit.focus();
178 }
179 }
180
181 function openLink(v: EditorView) {
182 const sel = v.state.selection;
183 const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to };
184 if (!range) return;
185 showLink(v, range.from, range.to, "edit");
186 }
187
188 editPanel.addEventListener("submit", (e) => {
189 e.preventDefault();
190 if (!link || !view) return;
191 const href = normalizeHref(linkInput.value);
192 if (!href) {
193 linkError.textContent = t("linkInvalid");
194 linkError.hidden = false;
195 linkInput.setAttribute("aria-invalid", "true");
196 linkInput.focus();
197 return;
198 }
199 const { from, to } = link;
200 closeLink(false);
201 view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href })));
202 view.focus();
203 });
204
205 function removeLink() {
206 if (!link || !view) return;
207 const { from, to } = link;
208 closeLink(false);
209 view.dispatch(view.state.tr.removeMark(from, to, linkMark));
210 view.focus();
211 }
212
213 function openHref() {
214 if (!link?.href) return;
215 // Note links open in this tab; external links keep opening in a new one.
216 if (isNoteHref(link.href)) {
217 location.assign(link.href);
218 return;
219 }
220 window.open(link.href, "_blank", "noopener,noreferrer");
221 }
222
223 editRemove.addEventListener("click", removeLink);
224 viewRemove.addEventListener("click", removeLink);
225 editOpen.addEventListener("click", openHref);
226 viewOpen.addEventListener("click", openHref);
227 viewEdit.addEventListener("click", () => {
228 if (view && link) showLink(view, link.from, link.to, "edit");
229 });
230
231 linkPop.addEventListener("keydown", (e) => {
232 if (e.key === "Escape") {
233 e.preventDefault();
234 e.stopPropagation();
235 closeLink(true);
236 return;
237 }
238 // Arrow keys move between the menu items in view mode.
239 if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !viewPanel.hidden) {
240 const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled);
241 const index = items.indexOf(document.activeElement as HTMLButtonElement);
242 const step = e.key === "ArrowDown" ? 1 : -1;
243 const next = items[(index + step + items.length) % items.length];
244 if (next) {
245 e.preventDefault();
246 next.focus();
247 }
248 }
249 });
250
251 // ---- Slash menu ----
252 const slashItems: SlashItem[] = [
253 { id: "text", label: t("paragraph"), keywords: "text paragraph p", keys: [MOD, ALT, "0"], run: editing.paragraph },
254 { id: "h1", label: t("heading1"), keywords: "heading title h1", keys: [MOD, ALT, "1"], run: editing.heading(1) },
255 { id: "h2", label: t("heading2"), keywords: "heading subtitle h2", keys: [MOD, ALT, "2"], run: editing.heading(2) },
256 { id: "h3", label: t("heading3"), keywords: "heading h3", keys: [MOD, ALT, "3"], run: editing.heading(3) },
257 { id: "bullets", label: t("bulletList"), keywords: "list ul bullet unordered", keys: [MOD, SHIFT, "8"], run: editing.bulletList },
258 { id: "ordered", label: t("numberedList"), keywords: "list ol number ordered", keys: [MOD, SHIFT, "9"], run: editing.orderedList },
259 { id: "quote", label: t("quote"), keywords: "blockquote quote", keys: [">"], run: editing.blockquote },
260 { id: "codeblock", label: t("codeBlock"), keywords: "code pre fence", keys: ["```"], run: editing.codeBlock },
261 { id: "divider", label: t("divider"), keywords: "hr rule line divider", keys: ["---"], run: editing.horizontalRule },
262 ];
263
264 const slashMenu = h("div", { class: "popover slash-menu", role: "presentation" });
265 slashMenu.hidden = true;
266 const slashList = h("div", { class: "slash-list", role: "listbox", "aria-label": t("blockMenu") });
267 const slashFooter = h(
268 "div",
269 { class: "slash-footer", "aria-hidden": "true" },
270 keycaps("↑", "↓"),
271 ` ${t("navigate")} `,
272 keycaps("↵"),
273 ` ${t("insert")} `,
274 keycaps("Esc"),
275 ` ${t("close")}`,
276 );
277 slashMenu.append(slashList, slashFooter);
278 // Keep focus in the editor while clicking menu items.
279 slashMenu.addEventListener("mousedown", (e) => e.preventDefault());
280
281 function closeSlash() {
282 slashFrom = null;
283 slashMenu.hidden = true;
284 view?.dom.removeAttribute("aria-activedescendant");
285 }
286
287 function renderSlash() {
288 if (!view || slashFrom === null) return;
289 const q = slashQuery.toLowerCase();
290 slashFiltered = slashItems.filter(
291 (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(" ").some((w) => w.startsWith(q)),
292 );
293 if (slashIndex >= slashFiltered.length) slashIndex = 0;
294 if (slashFiltered.length === 0) {
295 slashList.replaceChildren(h("div", { class: "slash-empty", role: "presentation" }, t("noMatches")));
296 view.dom.removeAttribute("aria-activedescendant");
297 return;
298 }
299 slashList.replaceChildren(
300 ...slashFiltered.map((item, i) => {
301 const el = h(
302 "div",
303 { class: "slash-item", role: "option", id: `slash-opt-${item.id}`, "aria-selected": String(i === slashIndex) },
304 h("span", { class: "slash-label" }, item.label),
305 keycaps(...item.keys),
306 );
307 el.addEventListener("click", () => applySlash(item));
308 return el;
309 }),
310 );
311 const active = slashFiltered[slashIndex];
312 view.dom.setAttribute("aria-activedescendant", `slash-opt-${active.id}`);
313 slashList.querySelector<HTMLElement>(`#slash-opt-${active.id}`)?.scrollIntoView({ block: "nearest" });
314 }
315
316 function applySlash(item: SlashItem) {
317 const v = view;
318 if (!v || slashFrom === null) return;
319 const from = slashFrom;
320 const to = v.state.selection.from;
321 closeSlash();
322 v.dispatch(v.state.tr.delete(from, to));
323 item.run(v.state, v.dispatch, v);
324 v.focus();
325 }
326
327 /** Opens, filters or closes the slash menu from the current selection. */
328 function syncSlash(v: EditorView) {
329 const ctx = slashContext(v.state);
330 if (!ctx) {
331 slashDismissed = null;
332 closeSlash();
333 return;
334 }
335 if (ctx.from === slashDismissed || link) {
336 closeSlash();
337 return;
338 }
339 if (ctx.from !== slashFrom || ctx.query !== slashQuery) slashIndex = 0;
340 slashFrom = ctx.from;
341 slashQuery = ctx.query;
342 slashMenu.hidden = false;
343 renderSlash();
344 }
345
346 // ---- Positioning and visibility ----
347 function bubbleVisible(v: EditorView): boolean {
348 const sel = v.state.selection;
349 return sel instanceof TextSelection && !sel.empty && !v.composing && !bubbleDismissed && link === null;
350 }
351
352 function renderFloating(v: EditorView) {
353 view = v;
354 const state = v.state;
355 const show = bubbleVisible(v);
356 bubble.hidden = !show;
357 if (show) {
358 for (const { btn, item } of bubbleButtons) {
359 const on = item.active(state);
360 btn.dataset.active = String(on);
361 btn.setAttribute("aria-pressed", String(on));
362 btn.disabled = !item.run(state);
363 }
364 placeFloating(bubble, rangeBox(v, state.selection.from, state.selection.to), "above");
365 }
366 if (link) {
367 placeFloating(linkPop, rangeBox(v, link.from, link.to), "above");
368 }
369 if (slashFrom !== null && !slashMenu.hidden) {
370 placeFloating(slashMenu, rangeBox(v, slashFrom, state.selection.from), "below");
371 }
372 }
373
374 // ---- Keyboard and mouse ----
375 const plugin = new Plugin({
376 props: {
377 handleKeyDown(v, e) {
378 if (slashFrom !== null) {
379 const n = slashFiltered.length;
380 if (e.key === "ArrowDown" && n) {
381 slashIndex = (slashIndex + 1) % n;
382 renderSlash();
383 return true;
384 }
385 if (e.key === "ArrowUp" && n) {
386 slashIndex = (slashIndex - 1 + n) % n;
387 renderSlash();
388 return true;
389 }
390 if (e.key === "Enter" && n) {
391 applySlash(slashFiltered[slashIndex]);
392 return true;
393 }
394 if (e.key === "Escape") {
395 slashDismissed = slashFrom;
396 closeSlash();
397 return true;
398 }
399 }
400 if (e.key === "Escape" && bubbleVisible(v)) {
401 bubbleDismissed = true;
402 renderFloating(v);
403 return true;
404 }
405 return false;
406 },
407 handleClick(v, pos, event) {
408 const target = event.target as Element | null;
409 const anchor = target?.closest?.("a");
410 if (!anchor) return false;
411 // Ctrl/Cmd+click navigates to a note (noteLinks.ts), so no popover opens for it.
412 if ((event.ctrlKey || event.metaKey) && isNoteHref(anchor.getAttribute("href"))) return false;
413 const range = markRangeAt(v.state.doc, pos, linkMark);
414 if (range) showLink(v, range.from, range.to, "view");
415 return false;
416 },
417 },
418 view(v) {
419 view = v;
420 document.body.append(bubble, linkPop, slashMenu);
421 const onViewport = () => {
422 if (view) renderFloating(view);
423 };
424 const onOutsideDown = (e: MouseEvent) => {
425 if (link && !linkPop.contains(e.target as Node)) closeLink(false);
426 };
427 window.addEventListener("scroll", onViewport, { capture: true, passive: true });
428 window.addEventListener("resize", onViewport);
429 document.addEventListener("mousedown", onOutsideDown, true);
430 renderFloating(v);
431 return {
432 update(u, prev) {
433 if (!prev.selection.eq(u.state.selection)) bubbleDismissed = false;
434 // A popover refers to a fixed range; remote or local edits invalidate it.
435 if (link && u.state.doc !== prev.doc) closeLink(false);
436 syncSlash(u);
437 renderFloating(u);
438 },
439 destroy() {
440 window.removeEventListener("scroll", onViewport, { capture: true });
441 window.removeEventListener("resize", onViewport);
442 document.removeEventListener("mousedown", onOutsideDown, true);
443 bubble.remove();
444 linkPop.remove();
445 slashMenu.remove();
446 view = null;
447 },
448 };
449 },
450 });
451
452 return { plugins: [plugin], openLink };
453}