import { tr } from "../i18n/index.ts"; import { invoke, isTauri } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; import type { ActionIcon } from "../ui/actionIcons"; import { spellingWord } from "./spellingWord"; /** WebView2 owns spelling suggestions and applies corrections to the original word. */ export function isSpellingTarget(target: EventTarget | null): boolean { if (!(target instanceof HTMLElement)) return false; if (target instanceof HTMLTextAreaElement || (target instanceof HTMLInputElement && ["text", "search"].includes(target.type))) { return target.spellcheck && !target.disabled && !target.readOnly; } const editable = target.closest('[contenteditable="true"][spellcheck="true"]'); return !!editable && target.isContentEditable && !target.closest('a, code, pre, button, [data-href], [spellcheck="false"], .writer-inline-code, .writer-code-source, .writer-code-line'); } export function useSpellingMenu(event: MouseEvent, selectionEmpty: boolean): boolean { return selectionEmpty && isSpellingTarget(event.target); } export type NativeSpellingItem = { id: number; name: string; label: string; shortcut: string; kind: number; enabled: boolean; checked: boolean; children: NativeSpellingItem[]; }; type NativeMenu = { request: string; items: NativeSpellingItem[]; fallback_spelling?: boolean }; const icons: Record = { undo: "undo", redo: "redo", cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text", selectAll: "select", addToDictionary: "book", spellCheck: "book", spellingAndGrammar: "book", }; function nativeLabel(label: string): string { // Windows uses ampersands for access keys and doubles literal ampersands. return label.replace(/&&|&/g, value => value === "&&" ? "&" : ""); } export function spellingItems(items: NativeSpellingItem[], select: (id: number) => void): ActionMenuItem[] { return items.map(item => item.kind === 3 ? { separator: true } : { label: nativeLabel(item.label), icon: icons[item.name], shortcut: item.shortcut || undefined, disabled: !item.enabled, checked: item.kind === 1 || item.kind === 2 ? item.checked : undefined, radio: item.kind === 2, children: item.kind === 4 ? spellingItems(item.children, select) : undefined, run: () => select(item.id), }); } /** Mount once per app window. Other platforms keep their native spelling menu. */ export function mountSpellingMenu(): () => void { if (!isTauri()) return () => {}; let disposed = false, unlisten: (() => void) | undefined; let context: { target: HTMLElement; x: number; y: number; word: ReturnType } | undefined; let revision = 0; let active: { request: string; root: HTMLElement; target: HTMLElement } | undefined; const finish = (command: number | null = null, restoreFocus = false) => { if (!active) return; const { request, root, target } = active; active = undefined; root.remove(); if (restoreFocus && target.isConnected) target.focus({ preventScroll: true }); void invoke("spelling_menu_select", { request, command }).catch(error => console.error("Cannot close the spelling menu", error)); }; const remember = (event: MouseEvent) => { revision++; finish(); if (event.defaultPrevented || !isSpellingTarget(event.target)) { context = undefined; return; } const target = (event.target as HTMLElement).closest('[contenteditable="true"], textarea, input')!; const bounds = document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).getBoundingClientRect() : target.getBoundingClientRect(); context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom, word: spellingWord(target, event.clientX, event.clientY) }; }; const outside = (event: PointerEvent) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } }; const scroll = (event: Event) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } }; const cancel = () => { revision++; finish(); }; window.addEventListener("contextmenu", remember); window.addEventListener("pointerdown", outside); window.addEventListener("resize", cancel); window.addEventListener("blur", cancel); window.addEventListener("pagehide", cancel); document.addEventListener("scroll", scroll, true); document.addEventListener("input", cancel, true); void listen("spelling-menu", async ({ payload }) => { finish(); if (disposed || !context?.target.isConnected) { void invoke("spelling_menu_select", { request: payload.request, command: null, fallback: true }); return; } const { target, x, y, word } = context; const requestRevision = ++revision; let items = spellingItems(payload.items, id => finish(id, true)); const parent = target.closest("dialog[open]") ?? document.body; const show = () => { const previous = active?.request === payload.request ? active.root : undefined; const focusedLabel = previous?.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined; previous?.remove(); const root = actionMenu(x, y, items, () => finish(null, true), tr("Spelling actions"), parent); active = { request: payload.request, root, target }; if (focusedLabel) [...root.querySelectorAll(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus(); }; if (payload.fallback_spelling) { const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) })); items = spellingItems(readable(payload.items), id => finish(id, true)); show(); if (word) { const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))]; try { const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }); const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } })); if (result.misspelled && !suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true }); if (result.misspelled) suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => { finish(null, true); void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error)); } }, { separator: true }); items = [...suggestions, ...items]; } catch { items = [{ label: tr("Spelling suggestions unavailable"), disabled: true }, { separator: true }, ...items]; } } } if (disposed || requestRevision !== revision || (payload.fallback_spelling && active?.request !== payload.request) || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) { void invoke("spelling_menu_select", { request: payload.request, command: null }); return; } show(); }).then(async stop => { if (disposed) { stop(); return; } unlisten = stop; await invoke("spelling_menu_install"); if (disposed) await invoke("spelling_menu_uninstall"); }).catch(error => console.warn("Native spelling menu remains active", error)); return () => { disposed = true; finish(); unlisten?.(); void invoke("spelling_menu_uninstall").catch(() => {}); window.removeEventListener("contextmenu", remember); window.removeEventListener("pointerdown", outside); window.removeEventListener("resize", cancel); window.removeEventListener("blur", cancel); window.removeEventListener("pagehide", cancel); document.removeEventListener("scroll", scroll, true); document.removeEventListener("input", cancel, true); }; }