Defend against Chrome rewriting the DOM, and add the language setting
Groundwork for un-shelving translations. Chrome's translator rewrites the rendered DOM directly, wrapping text nodes in <font> elements React has never heard of, and the next update can then call removeChild against a parent whose children have moved (facebook/react#11538). This is the structural defence against that, plus the setting the served language will read from. The language setting is `uiLanguage`, and it is deliberately not the `locale` field that already exists. That one is a formatting choice -- what calendar, clock and numerals to use -- and folding the two together would silently rewrite everybody's date format the first time they picked a language. German dates with an English interface is a real preference, and so is the reverse. It defaults to English when absent, which covers both a new account and every settings file written before this, and Accept-Language is not consulted: a served locale should be something the reader chose rather than something guessed and then written down as though they had. Only languages with strings shipped are offered, which today means English alone -- a picker entry without a catalogue behind it would leave the page claiming a language it is not in, which stops a reader translating a page they cannot read. `<html lang>` is set where applyTheme is set: at store module load, from the localStorage cache, before createRoot() has rendered anything. Not in an effect -- a lang that is briefly wrong is enough to raise the translate prompt on a page that needed none. There is no server-rendered alternative to reach for here: ihasmail serves a static shell and holds no account state, and the settings file lives in the reader's own JMAP Files, so reading it before the page existed would mean authenticating to Stalwart on every page load. The static lang="en" in index.html covers the first bytes; the store only ever corrects a reader who chose otherwise. Both halves are tested. translate="no" and class="notranslate" go on the narrow boundaries only: rendered email bodies, raw message source, attachment text, the generated and hand-edited Sieve, the brand and the login name. Not on <body> -- someone whose language ihasmail does not speak yet should still be able to translate the parts that are ours. Email bodies turn out to live in a shadow root, so React never reconciles them and they were never a crash risk; the marker there is about not rewriting what a sender actually wrote. Twenty-four fragile interpolation points were found with the TypeScript parser rather than grep, and fifteen refactored. Pluralisation and "count + label" pairs are collapsed into a single expression so the text is a lone child React updates with textContent, rather than a text node with conditional siblings to insert around. One of them -- InviteCard's {method === "REPLY" && organizer ? "" : ""} -- rendered an empty string either way and is simply gone. The boundary is scoped to the main content, so the header, folder tree and any open composer sit outside it and survive independently. It recovers by remounting the subtree, which costs nothing because everything inside re-derives from the stores, and it logs at info rather than error: a reader translating a page is expected and recovered from, and filing it as an error would put an entry in every console-reading reporter for behaviour that worked. It re-raises anything that is not a DOM mutation error, so a real bug still surfaces as one, and it gives up after three attempts rather than looping invisibly. Worth recording: the crash could not be reproduced on React 19.2.8. Wrapping 207-249 React-managed text nodes in <font>, exactly as the translator does, then driving in-place conditional toggles and navigations, left the app intact with the boundary never firing. The original issue is from React 16 and the reconciler has changed a great deal since. So this lands as defence whose premise is weaker than assumed rather than as a fix for something observed here, and the boundary is insurance rather than a load-bearing part. The notranslate markers and the collapsed interpolations stand on their own merits either way.
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* A boundary that survives Chrome translating the page.
|
||||
*
|
||||
* Chrome's translator rewrites the rendered DOM directly, wrapping text nodes
|
||||
* in `<font>` elements React has never heard of. React holds references to the
|
||||
* nodes it created, so the next update calls `removeChild` or `insertBefore`
|
||||
* against a parent whose children have moved, the DOM throws, and the whole
|
||||
* component tree unmounts. It is a longstanding React/Chromium problem
|
||||
* (facebook/react#11538), not a fault in anything here, and it cannot be
|
||||
* fixed from inside React.
|
||||
*
|
||||
* `translate="no"` and the structural wrapping elsewhere in this change make
|
||||
* it rarer. Neither makes it impossible: those are hints to the automatic
|
||||
* prompt, and a reader can always force a translation from the extension
|
||||
* regardless of what the page asked for. So the last line is to catch it and
|
||||
* put the subtree back.
|
||||
*
|
||||
* Recovery is a remount rather than a crash screen, because there is nothing
|
||||
* to lose: this wraps the main content area only, so the header, the sidebar
|
||||
* and any open composer are outside it and keep their state. What is inside
|
||||
* re-derives from the stores, which is where it came from a moment ago.
|
||||
*
|
||||
* Deliberately narrow. A boundary is a class component because React offers no
|
||||
* hook for this, and that is the whole of the cost -- no dependency, no
|
||||
* context, no stored state.
|
||||
*/
|
||||
|
||||
/** The DOM errors Chrome's rewriting produces, as opposed to real bugs. */
|
||||
export function isDomMutationError(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
// NotFoundError is what removeChild/insertBefore throw when the node they
|
||||
// were given is not where React last saw it. The name is checked first
|
||||
// because it is the reliable half -- the message is browser-specific and
|
||||
// localised, so matching on it alone would work in English Chrome and
|
||||
// nowhere else, which for a translation bug would be a poor joke.
|
||||
if (err.name === "NotFoundError" || err.name === "HierarchyRequestError") return true;
|
||||
return /removeChild|insertBefore|replaceChild|not a child of this node/i.test(err.message);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
/** Told about each recovery, for whoever is counting. */
|
||||
onRecover?: (info: { attempt: number; error: Error }) => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
/** Bumping this remounts the subtree, which is the whole recovery. */
|
||||
generation: number;
|
||||
failed: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* How many times a subtree is put back before it is left broken.
|
||||
*
|
||||
* Not unlimited: if something genuinely wrong is throwing a DOM error on every
|
||||
* render, remounting for ever is an invisible infinite loop that pins a core.
|
||||
* Three is enough for a reader toggling a translation on and off, and far too
|
||||
* few to hide a real bug.
|
||||
*/
|
||||
const MAX_RECOVERIES = 3;
|
||||
|
||||
export class TranslateBoundary extends Component<Props, State> {
|
||||
state: State = { generation: 0, failed: null };
|
||||
private recoveries = 0;
|
||||
|
||||
static getDerivedStateFromError(error: Error): Partial<State> | null {
|
||||
// Anything that is not the translator's doing is left to propagate, so a
|
||||
// real bug still surfaces as a real bug rather than as a subtree that
|
||||
// silently reappears empty.
|
||||
if (!isDomMutationError(error)) throw error;
|
||||
return { failed: error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
if (!isDomMutationError(error)) throw error;
|
||||
this.recoveries += 1;
|
||||
if (this.recoveries > MAX_RECOVERIES) {
|
||||
console.error("[ihasmail] giving up re-rendering after repeated DOM errors", error, info.componentStack);
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* console.info, not console.error. A reader translating the page is not a
|
||||
* fault, and logging it as one would put an entry in every error reporter
|
||||
* that reads the console, for behaviour that is expected and recovered
|
||||
* from. The marker is here to be counted, not alarmed at.
|
||||
*/
|
||||
console.info(
|
||||
`[ihasmail] recovered from a DOM error, most likely page translation (recovery ${this.recoveries} of ${MAX_RECOVERIES}): ${error.message}`,
|
||||
);
|
||||
this.props.onRecover?.({ attempt: this.recoveries, error });
|
||||
this.setState((s) => ({ generation: s.generation + 1, failed: null }));
|
||||
}
|
||||
|
||||
render(): ReactNode {
|
||||
if (this.state.failed) return null; // one frame, while the remount lands
|
||||
return <div key={this.state.generation} className="translate-boundary">{this.props.children}</div>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TranslateBoundary, isDomMutationError } from "../TranslateBoundary";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
/**
|
||||
* Chrome's translator wraps text nodes in <font> behind React's back, so the
|
||||
* next update calls removeChild against a parent whose children have moved and
|
||||
* the DOM throws. React unmounts the whole tree over it
|
||||
* (facebook/react#11538). The boundary's job is to put the subtree back
|
||||
* instead, and to leave everything that is not that alone.
|
||||
*/
|
||||
describe("recognising the translator's damage", () => {
|
||||
it("knows the DOM errors Chrome's rewriting produces", () => {
|
||||
const notFound = new Error("Failed to execute 'removeChild' on 'Node'");
|
||||
notFound.name = "NotFoundError";
|
||||
expect(isDomMutationError(notFound)).toBe(true);
|
||||
expect(isDomMutationError(new Error("The node before which the new node is to be inserted is not a child of this node"))).toBe(true);
|
||||
});
|
||||
|
||||
it("matches on the error name as well as the message", () => {
|
||||
// The message is browser-specific and localised. Matching only on English
|
||||
// text would be a translation bug that only works in English.
|
||||
const localised = new Error("Знайдений вузол не є дочірнім");
|
||||
localised.name = "NotFoundError";
|
||||
expect(isDomMutationError(localised)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not claim an ordinary bug", () => {
|
||||
expect(isDomMutationError(new TypeError("x is not a function"))).toBe(false);
|
||||
expect(isDomMutationError("a string")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the boundary", () => {
|
||||
let host: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/*
|
||||
* Throws on its first renders, then succeeds — the shape of a pane whose
|
||||
* DOM was rewritten and then remounted clean.
|
||||
*
|
||||
* It has to keep throwing past the first attempt. React answers an error in
|
||||
* a concurrent render by retrying the whole root synchronously, and a
|
||||
* component that throws exactly once succeeds on that retry and never
|
||||
* reaches the boundary at all — which looks like the boundary not working
|
||||
* and is really the test not reproducing anything.
|
||||
*/
|
||||
function Flaky({ fails }: { fails: { left: number } }) {
|
||||
if (fails.left > 0) {
|
||||
fails.left -= 1;
|
||||
const err = new Error("Failed to execute 'removeChild' on 'Node'");
|
||||
err.name = "NotFoundError";
|
||||
throw err;
|
||||
}
|
||||
return <p>content</p>;
|
||||
}
|
||||
|
||||
it("remounts the subtree instead of losing it", () => {
|
||||
const fails = { left: 2 }; // the concurrent attempt and the sync retry
|
||||
const onRecover = vi.fn();
|
||||
vi.spyOn(console, "info").mockImplementation(() => {});
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
act(() => {
|
||||
root.render(<TranslateBoundary onRecover={onRecover}><Flaky fails={fails} /></TranslateBoundary>);
|
||||
});
|
||||
expect(host.textContent).toBe("content");
|
||||
expect(onRecover).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("logs the recovery as information, not as an error", () => {
|
||||
// A reader translating the page is expected and recovered from. Logging it
|
||||
// as an error would file a bug report in every console-reading reporter,
|
||||
// every time, for behaviour that worked.
|
||||
const fails = { left: 2 };
|
||||
const info = vi.spyOn(console, "info").mockImplementation(() => {});
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
act(() => {
|
||||
root.render(<TranslateBoundary><Flaky fails={fails} /></TranslateBoundary>);
|
||||
});
|
||||
expect(info).toHaveBeenCalledOnce();
|
||||
expect(String(info.mock.calls[0]?.[0])).toContain("recovered from a DOM error");
|
||||
/*
|
||||
* React logs every error a boundary catches to console.error itself, in
|
||||
* development, and that is not ours to suppress. What matters is that
|
||||
* ihasmail does not add one of its own on top: the recovery is reported
|
||||
* as information, so a console-reading error reporter sees React's dev
|
||||
* noise and nothing from us claiming a failure.
|
||||
*/
|
||||
const ours = error.mock.calls.filter((c) => String(c[0]).includes("[ihasmail]"));
|
||||
expect(ours).toEqual([]);
|
||||
});
|
||||
|
||||
it("lets a real bug through rather than swallowing it", () => {
|
||||
function Broken(): never {
|
||||
throw new TypeError("genuinely broken");
|
||||
}
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
expect(() => {
|
||||
act(() => {
|
||||
root.render(<TranslateBoundary><Broken /></TranslateBoundary>);
|
||||
});
|
||||
}).toThrow(/genuinely broken/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user