// Floating editor UI, all plain DOM on
and positioned from view.coordsAtPos: // - selection bubble menu (formatting, shown for a non-empty text selection), // - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked), // - slash menu (typing "/" at the start of a block or after a space). // One ProseMirror plugin keeps them in sync with the editor state. import type { MarkType, Schema } from "prosemirror-model"; import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; import { t } from "./i18n"; import { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from "./editing"; import { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from "./dom"; import { isNoteHref } from "./noteLinks"; interface BubbleItem { id: string; label: string; glyph: string; keys: string[]; run: Command; active: (state: EditorState) => boolean; } interface SlashItem { id: string; label: string; /** English words the filter also matches, so "h2" or "list" work in either language. */ keywords: string; keys: string[]; run: Command; } export interface Floating { plugins: Plugin[]; /** Opens the link popover for the selection, or for the link the cursor is in. */ openLink(view: EditorView): void; } interface LinkState { from: number; to: number; mode: "edit" | "view"; /** Existing href at the range, if any. */ href: string | null; } /** Position of an open "/query" trigger and what has been typed after the slash. */ function slashContext(state: EditorState): { from: number; query: string } | 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; const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); const match = /(?:^|\s)\/([^\s/]*)$/.exec(before); if (!match) return null; return { from: $from.pos - match[1].length - 1, query: match[1] }; } function hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null { let href: string | null = null; state.doc.nodesBetween(from, to, (node) => { if (href !== null) return false; const mark = type.isInSet(node.marks); if (mark) href = String(mark.attrs.href); return href === null; }); return href; } export function createFloating(schema: Schema, editing: Editing): Floating { const { strong, em, code, link: linkMark } = schema.marks; const { heading } = schema.nodes; let view: EditorView | null = null; let bubbleDismissed = false; let link: LinkState | null = null; let slashFrom: number | null = null; let slashQuery = ""; let slashIndex = 0; let slashFiltered: SlashItem[] = []; let slashDismissed: number | null = null; // ---- Bubble menu ---- const bubbleItems: BubbleItem[] = [ { id: "bold", label: t("bold"), glyph: "B", keys: [MOD, "B"], run: editing.bold, active: (s) => isMarkActive(s, strong) }, { id: "italic", label: t("italic"), glyph: "I", keys: [MOD, "I"], run: editing.italic, active: (s) => isMarkActive(s, em) }, { id: "code", label: t("inlineCode"), glyph: ">", keys: [MOD, "E"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) }, { id: "link", label: t("link"), glyph: "Link", keys: [MOD, "K"], run: editing.link, active: (s) => isMarkActive(s, linkMark) }, { id: "h1", label: t("heading1"), glyph: "H1", keys: [MOD, ALT, "1"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) }, { id: "h2", label: t("heading2"), glyph: "H2", keys: [MOD, ALT, "2"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) }, { id: "h3", label: t("heading3"), glyph: "H3", keys: [MOD, ALT, "3"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) }, ]; const bubble = h("div", { class: "bubble", role: "toolbar", "aria-label": t("bubbleLabel") }); bubble.hidden = true; const bubbleButtons = bubbleItems.map((item) => { const btn = h( "button", { type: "button", class: "bubble-btn", "aria-label": item.label, "data-command": item.id }, h("span", { class: "bubble-glyph", "aria-hidden": "true" }, item.glyph), tooltip(item.label, item.keys), ); btn.addEventListener("click", () => { if (!view) return; item.run(view.state, view.dispatch, view); if (item.id !== "link") view.focus(); }); bubble.append(btn); return { btn, item }; }); // Keep the text selection while pressing bubble buttons. bubble.addEventListener("mousedown", (e) => e.preventDefault()); // ---- Link popover (edit and view panels share one element) ---- const linkPop = h("div", { class: "popover link-popover", role: "dialog", "aria-label": t("linkDialog") }); linkPop.hidden = true; const editPanel = h("form", { class: "link-edit", novalidate: "" }); const linkInput = h("input", { type: "text", class: "link-input", inputmode: "url", autocomplete: "off", autocapitalize: "off", spellcheck: "false", placeholder: "https://", "aria-label": t("linkUrl"), "aria-describedby": "link-error", }); const linkError = h("p", { class: "link-error", id: "link-error", role: "alert" }); linkError.hidden = true; const applyBtn = h("button", { type: "submit", class: "btn btn-primary" }, t("apply"), keycaps("↵")); const editRemove = h("button", { type: "button", class: "btn" }, t("remove")); const editOpen = h("button", { type: "button", class: "btn" }, t("open")); editPanel.append( h("div", { class: "link-row" }, linkInput, applyBtn), linkError, h("div", { class: "link-actions" }, editRemove, editOpen), ); // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items. const viewPanel = h("div", { class: "link-view", role: "menu", "aria-label": t("linkMenu") }); const linkHref = h("span", { class: "link-href" }); const viewEdit = h("button", { type: "button", class: "btn", role: "menuitem" }, t("edit")); const viewRemove = h("button", { type: "button", class: "btn", role: "menuitem" }, t("remove")); const viewOpen = h("button", { type: "button", class: "btn", role: "menuitem" }, t("open")); viewPanel.append(linkHref, h("div", { class: "link-actions", role: "none" }, viewEdit, viewRemove, viewOpen)); linkPop.append(editPanel, viewPanel); function closeLink(restoreFocus: boolean) { if (!link) return; link = null; linkPop.hidden = true; if (restoreFocus) view?.focus(); } function showLink(v: EditorView, from: number, to: number, mode: "edit" | "view") { closeSlash(); const href = hrefInRange(v.state, from, to, linkMark); link = { from, to, mode, href }; linkPop.hidden = false; editPanel.hidden = mode !== "edit"; viewPanel.hidden = mode !== "view"; linkError.hidden = true; linkInput.removeAttribute("aria-invalid"); linkInput.value = href ?? ""; linkHref.textContent = href ?? ""; for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) { btn.disabled = href === null; btn.title = href === null ? t("linkNeedsLink") : ""; } renderFloating(v); if (mode === "edit") { linkInput.focus(); linkInput.select(); } else { viewEdit.focus(); } } function openLink(v: EditorView) { const sel = v.state.selection; const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to }; if (!range) return; showLink(v, range.from, range.to, "edit"); } editPanel.addEventListener("submit", (e) => { e.preventDefault(); if (!link || !view) return; const href = normalizeHref(linkInput.value); if (!href) { linkError.textContent = t("linkInvalid"); linkError.hidden = false; linkInput.setAttribute("aria-invalid", "true"); linkInput.focus(); return; } const { from, to } = link; closeLink(false); view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href }))); view.focus(); }); function removeLink() { if (!link || !view) return; const { from, to } = link; closeLink(false); view.dispatch(view.state.tr.removeMark(from, to, linkMark)); view.focus(); } function openHref() { if (!link?.href) return; // Note links open in this tab; external links keep opening in a new one. if (isNoteHref(link.href)) { location.assign(link.href); return; } window.open(link.href, "_blank", "noopener,noreferrer"); } editRemove.addEventListener("click", removeLink); viewRemove.addEventListener("click", removeLink); editOpen.addEventListener("click", openHref); viewOpen.addEventListener("click", openHref); viewEdit.addEventListener("click", () => { if (view && link) showLink(view, link.from, link.to, "edit"); }); linkPop.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeLink(true); return; } // Arrow keys move between the menu items in view mode. if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !viewPanel.hidden) { const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled); const index = items.indexOf(document.activeElement as HTMLButtonElement); const step = e.key === "ArrowDown" ? 1 : -1; const next = items[(index + step + items.length) % items.length]; if (next) { e.preventDefault(); next.focus(); } } }); // ---- Slash menu ---- const slashItems: SlashItem[] = [ { id: "text", label: t("paragraph"), keywords: "text paragraph p", keys: [MOD, ALT, "0"], run: editing.paragraph }, { id: "h1", label: t("heading1"), keywords: "heading title h1", keys: [MOD, ALT, "1"], run: editing.heading(1) }, { id: "h2", label: t("heading2"), keywords: "heading subtitle h2", keys: [MOD, ALT, "2"], run: editing.heading(2) }, { id: "h3", label: t("heading3"), keywords: "heading h3", keys: [MOD, ALT, "3"], run: editing.heading(3) }, { id: "bullets", label: t("bulletList"), keywords: "list ul bullet unordered", keys: [MOD, SHIFT, "8"], run: editing.bulletList }, { id: "ordered", label: t("numberedList"), keywords: "list ol number ordered", keys: [MOD, SHIFT, "9"], run: editing.orderedList }, { id: "quote", label: t("quote"), keywords: "blockquote quote", keys: [">"], run: editing.blockquote }, { id: "codeblock", label: t("codeBlock"), keywords: "code pre fence", keys: ["```"], run: editing.codeBlock }, { id: "divider", label: t("divider"), keywords: "hr rule line divider", keys: ["---"], run: editing.horizontalRule }, ]; const slashMenu = h("div", { class: "popover slash-menu", role: "presentation" }); slashMenu.hidden = true; const slashList = h("div", { class: "slash-list", role: "listbox", "aria-label": t("blockMenu") }); const slashFooter = h( "div", { class: "slash-footer", "aria-hidden": "true" }, keycaps("↑", "↓"), ` ${t("navigate")} `, keycaps("↵"), ` ${t("insert")} `, keycaps("Esc"), ` ${t("close")}`, ); slashMenu.append(slashList, slashFooter); // Keep focus in the editor while clicking menu items. slashMenu.addEventListener("mousedown", (e) => e.preventDefault()); function closeSlash() { slashFrom = null; slashMenu.hidden = true; view?.dom.removeAttribute("aria-activedescendant"); } function renderSlash() { if (!view || slashFrom === null) return; const q = slashQuery.toLowerCase(); slashFiltered = slashItems.filter( (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(" ").some((w) => w.startsWith(q)), ); if (slashIndex >= slashFiltered.length) slashIndex = 0; if (slashFiltered.length === 0) { slashList.replaceChildren(h("div", { class: "slash-empty", role: "presentation" }, t("noMatches"))); view.dom.removeAttribute("aria-activedescendant"); return; } slashList.replaceChildren( ...slashFiltered.map((item, i) => { const el = h( "div", { class: "slash-item", role: "option", id: `slash-opt-${item.id}`, "aria-selected": String(i === slashIndex) }, h("span", { class: "slash-label" }, item.label), keycaps(...item.keys), ); el.addEventListener("click", () => applySlash(item)); return el; }), ); const active = slashFiltered[slashIndex]; view.dom.setAttribute("aria-activedescendant", `slash-opt-${active.id}`); slashList.querySelector