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,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