diff --git a/ui/src/lib/browser-error-context.ts b/ui/src/lib/browser-error-context.ts index 7908070e979..0aea37b1693 100644 --- a/ui/src/lib/browser-error-context.ts +++ b/ui/src/lib/browser-error-context.ts @@ -44,13 +44,25 @@ export function readBrowserErrorState() { if (state === "visible" || state === "hidden") browserState.visibility_state = state; } catch { /* diagnostic unavailable */ } try { - const classes = document.documentElement.classList; - browserState.translation_marker = classes.contains("translated-ltr") || classes.contains("translated-rtl"); + browserState.translation_marker = readPageTranslationMarker(); } catch { /* diagnostic unavailable */ } } return browserState; } +function readPageTranslationMarker(): boolean { + const classes = document.documentElement.classList; + return classes.contains("translated-ltr") || classes.contains("translated-rtl"); +} + +export function hasPageTranslationMarker(): boolean { + try { + return typeof document !== "undefined" && readPageTranslationMarker(); + } catch { + return false; + } +} + type PageTransition = "visible" | "hidden" | "pagehide" | "pageshow" | "freeze" | "resume"; type ElapsedBucket = "<1s" | "1-10s" | "10-60s" | "1-10m" | ">10m"; type RejectionPromiseKind = "native" | "subclass" | "other" | "missing"; diff --git a/ui/src/lib/translation-dom-guard.test.tsx b/ui/src/lib/translation-dom-guard.test.tsx new file mode 100644 index 00000000000..8250d5b41a4 --- /dev/null +++ b/ui/src/lib/translation-dom-guard.test.tsx @@ -0,0 +1,203 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { startTranslationDomGuard } from "./translation-dom-guard"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +function translateTextNode(textNode: Text, translated: string) { + document.documentElement.classList.add("translated-ltr"); + const font = document.createElement("font"); + font.appendChild(document.createTextNode(translated)); + textNode.parentNode!.replaceChild(font, textNode); + return font; +} + +function translateTextNodeInTwoSteps(textNode: Text, translated: string) { + document.documentElement.classList.add("translated-ltr"); + const font = document.createElement("font"); + font.appendChild(document.createTextNode(translated)); + textNode.parentNode!.insertBefore(font, textNode); + textNode.parentNode!.removeChild(textNode); + return font; +} + +function wrapTextNode(textNode: Text) { + document.documentElement.classList.add("translated-ltr"); + const font = document.createElement("font"); + textNode.parentNode!.replaceChild(font, textNode); + font.appendChild(textNode); + return font; +} + +function expectNotFound(action: () => unknown) { + expect(action).toThrow(expect.objectContaining({ name: "NotFoundError" })); +} + +function firstTextNode(element: Element): Text { + for (const node of Array.from(element.childNodes)) { + if (node.nodeType === Node.TEXT_NODE) return node as Text; + } + throw new Error("no text node"); +} + +function Status({ done }: { done: boolean }) { + return

{done ? null : "Running"}end

; +} + +function Pair({ showLeft }: { showLeft: boolean }) { + return

{showLeft ? "Left" : null}{"Right"}

; +} + +function textNodes(element: Element): Text[] { + return Array.from(element.childNodes).filter((node): node is Text => node.nodeType === Node.TEXT_NODE); +} + +function Toggle({ show }: { show: boolean }) { + return

{show ? new : null}{"Running"}

; +} + +describe("startTranslationDomGuard", () => { + let container: HTMLDivElement; + let root: Root; + let stop: (() => void) | undefined; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + stop?.(); + stop = undefined; + document.documentElement.classList.remove("translated-ltr", "translated-rtl"); + }); + + it("reproduces the translated-page removeChild crash without the guard", () => { + act(() => root.render()); + translateTextNode(firstTextNode(container.querySelector("p")!), "En curso"); + expect(() => act(() => root.render())).toThrow(/not a child of this node/); + }); + + it("removes the translated replacement when React removes a detached text node", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const font = translateTextNode(firstTextNode(container.querySelector("p")!), "En curso"); + expect(() => act(() => root.render())).not.toThrow(); + expect(font.isConnected).toBe(false); + expect(container.textContent).toBe("end"); + act(() => root.render()); + expect(container.textContent).toBe("Runningend"); + }); + + it("removes a replacement that translation inserted and detached in separate steps", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const font = translateTextNodeInTwoSteps(firstTextNode(container.querySelector("p")!), "En curso"); + act(() => root.render()); + expect(font.isConnected).toBe(false); + expect(container.textContent).toBe("end"); + }); + + it("keeps a neighbor's translation when adjacent text nodes are translated right to left", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const [left, right] = textNodes(container.querySelector("p")!); + const rightFont = translateTextNodeInTwoSteps(right, "Derecha"); + const leftFont = translateTextNodeInTwoSteps(left, "Izquierda"); + act(() => root.render()); + expect(leftFont.isConnected).toBe(false); + expect(rightFont.isConnected).toBe(true); + expect(container.textContent).toBe("Derecha"); + }); + + it("keeps a neighbor's translation when adjacent text nodes are translated left to right", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const [left, right] = textNodes(container.querySelector("p")!); + const leftFont = translateTextNodeInTwoSteps(left, "Izquierda"); + const rightFont = translateTextNodeInTwoSteps(right, "Derecha"); + act(() => root.render()); + expect(leftFont.isConnected).toBe(false); + expect(rightFont.isConnected).toBe(true); + expect(container.textContent).toBe("Derecha"); + }); + + it("removes a text node that translation moved into its wrapper", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const font = wrapTextNode(firstTextNode(container.querySelector("p")!)); + act(() => root.render()); + expect(font.textContent).toBe(""); + expect(container.textContent).toBe("end"); + }); + + it("inserts before a reference node that translation moved into its wrapper", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const paragraph = container.querySelector("p")!; + const font = wrapTextNode(firstTextNode(paragraph)); + act(() => root.render()); + expect(paragraph.firstChild).toBe(container.querySelector("i")); + expect(paragraph.lastChild).toBe(font); + }); + + it("inserts before the translated replacement of a detached reference node", () => { + stop = startTranslationDomGuard(); + act(() => root.render()); + const paragraph = container.querySelector("p")!; + const font = translateTextNode(firstTextNode(paragraph), "En curso"); + expect(() => act(() => root.render())).not.toThrow(); + expect(paragraph.firstChild).toBe(container.querySelector("i")); + expect(paragraph.lastChild).toBe(font); + }); + + it("appends when a detached reference node has no translated replacement", () => { + stop = startTranslationDomGuard(); + document.documentElement.classList.add("translated-ltr"); + const parent = document.createElement("div"); + parent.appendChild(document.createElement("span")); + const detached = document.createTextNode("gone"); + const added = document.createElement("i"); + expect(parent.insertBefore(added, detached)).toBe(added); + expect(parent.lastChild).toBe(added); + }); + + it("keeps the native errors when the page is not translated", () => { + stop = startTranslationDomGuard(); + const parent = document.createElement("div"); + const stray = document.createElement("span"); + expectNotFound(() => parent.removeChild(stray)); + expectNotFound(() => parent.insertBefore(document.createElement("i"), stray)); + }); + + it("keeps the native errors for nodes outside the parent on a translated page", () => { + stop = startTranslationDomGuard(); + document.documentElement.classList.add("translated-rtl"); + const parent = document.createElement("div"); + const elsewhere = document.createElement("section"); + const stray = elsewhere.appendChild(document.createElement("span")); + expectNotFound(() => parent.removeChild(stray)); + expectNotFound(() => parent.insertBefore(document.createElement("i"), stray)); + expect(stray.parentNode).toBe(elsewhere); + }); + + it("installs once and restores the native methods when stopped", () => { + const nativeRemove = Node.prototype.removeChild; + const nativeInsert = Node.prototype.insertBefore; + const first = startTranslationDomGuard(); + const second = startTranslationDomGuard(); + const guardedRemove = Node.prototype.removeChild; + expect(guardedRemove).not.toBe(nativeRemove); + second(); + expect(Node.prototype.removeChild).toBe(guardedRemove); + first(); + expect(Node.prototype.removeChild).toBe(nativeRemove); + expect(Node.prototype.insertBefore).toBe(nativeInsert); + }); +}); diff --git a/ui/src/lib/translation-dom-guard.ts b/ui/src/lib/translation-dom-guard.ts new file mode 100644 index 00000000000..bd58b85e0a0 --- /dev/null +++ b/ui/src/lib/translation-dom-guard.ts @@ -0,0 +1,104 @@ +import { hasPageTranslationMarker } from "./browser-error-context"; + +interface GuardedMethods { + removeChild: Node["removeChild"]; + insertBefore: Node["insertBefore"]; +} + +let installed: GuardedMethods | undefined; + +function childOfParentContaining(parent: Node, node: Node): Node | null { + let current: Node | null = node; + while (current && current.parentNode !== parent) current = current.parentNode; + return current; +} + +function isTranslationWrapper(node: Node | null | undefined): node is Element { + return !!node && node.nodeType === Node.ELEMENT_NODE && (node as Element).localName === "font"; +} + +interface ReplacementTracker { + inserted: WeakMap; + replacements: WeakMap; +} + +function isTextNode(node: Node | null | undefined): node is Text { + return !!node && node.nodeType === Node.TEXT_NODE; +} + +function recordReplacements(records: MutationRecord[], tracker: ReplacementTracker) { + for (const record of records) { + if (record.type !== "childList") continue; + const added = record.addedNodes.length === 1 ? record.addedNodes[0] : null; + const wrapper = isTranslationWrapper(added) ? added : null; + if (record.removedNodes.length === 0) { + if (!wrapper) continue; + if (isTextNode(record.previousSibling)) tracker.inserted.set(record.previousSibling, wrapper); + if (isTextNode(record.nextSibling)) tracker.inserted.set(record.nextSibling, wrapper); + continue; + } + if (record.removedNodes.length !== 1) continue; + const removed = record.removedNodes[0]; + if (!isTextNode(removed)) continue; + if (wrapper) { + tracker.replacements.set(removed, wrapper); + continue; + } + if (record.addedNodes.length > 0) continue; + const insertedWrapper = tracker.inserted.get(removed); + if (insertedWrapper && (record.previousSibling === insertedWrapper || record.nextSibling === insertedWrapper)) { + tracker.replacements.set(removed, insertedWrapper); + } + } +} + +export function startTranslationDomGuard(): () => void { + if (installed || typeof Node !== "function" || !Node.prototype) return () => {}; + const proto = Node.prototype; + const native: GuardedMethods = { removeChild: proto.removeChild, insertBefore: proto.insertBefore }; + installed = native; + + const tracker: ReplacementTracker = { inserted: new WeakMap(), replacements: new WeakMap() }; + let observer: MutationObserver | undefined; + if (typeof MutationObserver === "function" && typeof document !== "undefined" && document.documentElement) { + observer = new MutationObserver((records) => recordReplacements(records, tracker)); + observer.observe(document.documentElement, { childList: true, subtree: true }); + } + + const replacementInside = (parent: Node, node: Node): Element | null => { + if (observer) recordReplacements(observer.takeRecords(), tracker); + const replacement = tracker.replacements.get(node); + return replacement && replacement.parentNode === parent ? replacement : null; + }; + + proto.removeChild = function removeChild(this: Node, child: T): T { + if (child && child.parentNode !== this && hasPageTranslationMarker()) { + if (child.parentNode === null) { + const replacement = replacementInside(this, child); + if (replacement) native.removeChild.call(this, replacement); + return child; + } + if (this.contains(child)) return native.removeChild.call(child.parentNode, child) as T; + } + return native.removeChild.call(this, child) as T; + }; + + proto.insertBefore = function insertBefore(this: Node, node: T, child: Node | null): T { + if (child && child.parentNode !== this && hasPageTranslationMarker()) { + if (child.parentNode === null) { + return native.insertBefore.call(this, node, replacementInside(this, child)) as T; + } + const wrapper = this.contains(child) ? childOfParentContaining(this, child) : null; + if (wrapper) return native.insertBefore.call(this, node, wrapper) as T; + } + return native.insertBefore.call(this, node, child) as T; + }; + + return () => { + if (installed !== native) return; + observer?.disconnect(); + proto.removeChild = native.removeChild; + proto.insertBefore = native.insertBefore; + installed = undefined; + }; +} diff --git a/ui/src/main.tsx b/ui/src/main.tsx index 84ec06f738a..4923aafbb30 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -28,6 +28,7 @@ import { initPluginBridge } from "./plugins/bridge-init"; import { PluginLauncherProvider } from "./plugins/launchers"; import { startChunkLoadRecovery } from "./lib/chunk-load-recovery"; import { startPerfMeasureReaper } from "./lib/perf-measure-reaper"; +import { startTranslationDomGuard } from "./lib/translation-dom-guard"; import { getOrCreatePaperclipReactRoot } from "./lib/react-root"; import { startServiceWorkerUpdates } from "./lib/service-worker-updates"; import { connectivity } from "./lib/connectivity"; @@ -48,6 +49,8 @@ startPerfMeasureReaper(); startChunkLoadRecovery(); +startTranslationDomGuard(); + // The global mutation error toast is raised from the MutationCache, outside // React; the bridge below hands it the ToastProvider's pushToast. let pushMutationErrorToast: ((input: ToastInput) => void) | null = null;