Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🐛 Stop page translation from crashing React DOM updates (#3612)

Luke Vella5278fbd8576b
diff --git a/apps/web/instrumentation-client.ts b/apps/web/instrumentation-client.ts
index d2bd99e2f..95a99b3c8 100644
--- a/apps/web/instrumentation-client.ts
+++ b/apps/web/instrumentation-client.ts
@@ -11,6 +11,10 @@ import {
reloadOnceForChunkError,
} from "@/lib/chunk-recovery";
import { getChunkRegistrationContext } from "@/lib/chunk-registration-log";
+import { installTranslationDomGuard } from "@/lib/translation-dom-guard";
+
+// Runs before React hydrates, so every DOM update React makes is covered.
+installTranslationDomGuard();
const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;
diff --git a/apps/web/src/lib/translation-dom-guard.test.ts b/apps/web/src/lib/translation-dom-guard.test.ts
new file mode 100644
index 000000000..ec8340b7d
--- /dev/null
+++ b/apps/web/src/lib/translation-dom-guard.test.ts
@@ -0,0 +1,129 @@
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { installTranslationDomGuard } from "./translation-dom-guard";
+
+// What Google Translate does: swap each text node for <font><font>…</font></font>.
+function translate(container: HTMLElement) {
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
+ const textNodes: Text[] = [];
+ while (walker.nextNode()) {
+ textNodes.push(walker.currentNode as Text);
+ }
+ for (const text of textNodes) {
+ const outer = document.createElement("font");
+ const inner = document.createElement("font");
+ inner.textContent = `translated ${text.data}`;
+ outer.appendChild(inner);
+ text.replaceWith(outer);
+ }
+}
+
+function Vote({ yes }: { yes: boolean }) {
+ return createElement(
+ "button",
+ { type: "button" },
+ yes ? "Yes" : null,
+ "Vote",
+ " ",
+ "now",
+ );
+}
+
+function mountTranslated() {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(createElement(Vote, { yes: true })));
+ translate(container);
+ return { container, root };
+}
+
+const INSTALLED = Symbol.for("rallly.translationDomGuard");
+const nativeRemoveChild = Node.prototype.removeChild;
+const nativeInsertBefore = Node.prototype.insertBefore;
+
+function restoreNativeDom() {
+ Node.prototype.removeChild = nativeRemoveChild;
+ Node.prototype.insertBefore = nativeInsertBefore;
+ delete (Node.prototype as { [INSTALLED]?: true })[INSTALLED];
+}
+
+describe("installTranslationDomGuard", () => {
+ beforeEach(restoreNativeDom);
+ afterEach(restoreNativeDom);
+
+ it("React throws on a translated page without the guard", () => {
+ const { root } = mountTranslated();
+ expect(() =>
+ act(() => root.render(createElement(Vote, { yes: false }))),
+ ).toThrow(/not a child/);
+ });
+
+ it("lets React update and unmount a translated page", () => {
+ installTranslationDomGuard();
+ const { container, root } = mountTranslated();
+ act(() => root.render(createElement(Vote, { yes: false })));
+ act(() => root.render(createElement(Vote, { yes: true })));
+ expect(container.querySelector("button")?.textContent).toContain("Yes");
+ act(() => root.unmount());
+ expect(container.innerHTML).toBe("");
+ });
+
+ it("inserts before the wrapper of a wrapped reference node", () => {
+ installTranslationDomGuard();
+ const parent = document.createElement("div");
+ const reference = document.createTextNode("b");
+ const wrapper = document.createElement("font");
+ parent.appendChild(wrapper);
+ wrapper.appendChild(reference);
+ const inserted = document.createTextNode("a");
+ parent.insertBefore(inserted, reference);
+ expect(parent.firstChild).toBe(inserted);
+ expect(parent.lastChild).toBe(wrapper);
+ });
+
+ it("appends when the reference text node was detached", () => {
+ installTranslationDomGuard();
+ const parent = document.createElement("div");
+ parent.appendChild(document.createElement("span"));
+ const inserted = document.createTextNode("a");
+ parent.insertBefore(inserted, document.createTextNode("gone"));
+ expect(parent.lastChild).toBe(inserted);
+ });
+
+ it("removes a wrapped child from its wrapper", () => {
+ installTranslationDomGuard();
+ const parent = document.createElement("div");
+ const wrapper = document.createElement("font");
+ const child = document.createTextNode("a");
+ parent.appendChild(wrapper);
+ wrapper.appendChild(child);
+ parent.removeChild(child);
+ expect(child.parentNode).toBeNull();
+ });
+
+ it("ignores removing a detached text node", () => {
+ installTranslationDomGuard();
+ const parent = document.createElement("div");
+ const text = document.createTextNode("gone");
+ expect(parent.removeChild(text)).toBe(text);
+ });
+
+ it("keeps the native error for nodes translation did not touch", () => {
+ installTranslationDomGuard();
+ const parent = document.createElement("div");
+ const elsewhere = document.createElement("div");
+ const element = document.createElement("span");
+ const text = document.createTextNode("a");
+ elsewhere.append(element, text);
+ expect(() => parent.removeChild(document.createElement("span"))).toThrow();
+ expect(() => parent.removeChild(text)).toThrow();
+ expect(() =>
+ parent.insertBefore(document.createTextNode("b"), element),
+ ).toThrow();
+ expect(() =>
+ parent.insertBefore(document.createTextNode("b"), text),
+ ).toThrow();
+ });
+});
diff --git a/apps/web/src/lib/translation-dom-guard.ts b/apps/web/src/lib/translation-dom-guard.ts
new file mode 100644
index 000000000..19b59e056
--- /dev/null
+++ b/apps/web/src/lib/translation-dom-guard.ts
@@ -0,0 +1,71 @@
+// Browser page translation (Chrome, Google Translate, Safari) and some
+// extensions replace the text nodes React rendered with <font> wrappers. React
+// still holds the original nodes, so its next removeChild or insertBefore on
+// them throws NotFoundError and the error boundary replaces the page. These
+// patches make both calls tolerate a node that has moved, so the page keeps
+// working and stays translatable. See facebook/react#11538.
+
+const INSTALLED = Symbol.for("rallly.translationDomGuard");
+
+type GuardedPrototype = typeof Node.prototype & { [INSTALLED]?: true };
+
+// A text node a translator detached, or wrapped while leaving it under
+// `parent`. Anything else keeps the native NotFoundError.
+function isTranslatedText(parent: Node, node: Node) {
+ return (
+ node.nodeType === Node.TEXT_NODE &&
+ (node.parentNode === null || parent.contains(node))
+ );
+}
+
+// The direct child of `parent` that contains `node`, when a wrapper was
+// inserted between them.
+function childContaining(parent: Node, node: Node) {
+ let current: Node | null = node;
+ while (current && current.parentNode !== parent) {
+ current = current.parentNode;
+ }
+ return current;
+}
+
+export function installTranslationDomGuard() {
+ if (typeof Node !== "function") {
+ return;
+ }
+ const proto: GuardedPrototype = Node.prototype;
+ if (proto[INSTALLED]) {
+ return;
+ }
+ proto[INSTALLED] = true;
+
+ const originalRemoveChild = proto.removeChild;
+ proto.removeChild = function removeChild<T extends Node>(
+ this: Node,
+ child: T,
+ ): T {
+ if (child.parentNode === this || !isTranslatedText(this, child)) {
+ return originalRemoveChild.call(this, child) as T;
+ }
+ // Wrapped in a <font> that is still under this parent: remove it from
+ // where it is. Already detached by the translator: nothing to remove.
+ if (child.parentNode) {
+ return originalRemoveChild.call(child.parentNode, child) as T;
+ }
+ return child;
+ };
+
+ const originalInsertBefore = proto.insertBefore;
+ proto.insertBefore = function insertBefore<T extends Node>(
+ this: Node,
+ node: T,
+ child: Node | null,
+ ): T {
+ if (!child || child.parentNode === this || !isTranslatedText(this, child)) {
+ return originalInsertBefore.call(this, node, child) as T;
+ }
+ // The reference node is wrapped: insert before its wrapper. It was
+ // detached: its position is lost, so append rather than drop the node.
+ const anchor = childContaining(this, child);
+ return originalInsertBefore.call(this, node, anchor) as T;
+ };
+}