Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,14 @@ upgrading Fern, also verify navigation, language switching, themes and history i
Safari and Chrome. This guards a hosted-renderer failure; it does not patch
WebKit's module loader or Fern's generated bundles.

The interface localization bridge preserves incoming server-rendered labels and
Fern's hydration strategies during language changes. It updates labels only after
island readiness and a post-render task. Within React-owned islands, read-only
React DOM binding markers also keep deferred Suspense content untouched until
React adopts each target. Only waiting targets are retried; disconnected nodes
are discarded. Verify these markers against the hosted renderer after Fern/React
upgrades. Do not normalize incoming labels to English.

The browser regression suite runs the checkout's configured custom scripts and
CSS in Chromium and WebKit. Scripts follow their configured loading phases,
preserving declaration order within each phase; Fern's parser, hydration and
Expand Down
90 changes: 57 additions & 33 deletions fern/docs-interface.js

Large diffs are not rendered by default.

25 changes: 0 additions & 25 deletions fern/language-modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -610,30 +610,6 @@
if (root.classList.contains("light")) return "light";
return root.dataset.theme === "dark" ? "dark" : "light";
}
function prepareLocaleSwap(event) {
if (!event.from || !event.to || !event.newDocument) return;
var routeLocale = function (url) {
var first = url.pathname.split("/").find(Boolean) || "";
return locales.some(function (item) { return item.code && item.code === first; }) ? first : "";
};
if (typeof window.__sixmmPrepareInterfaceSwap === 'function') {
window.__sixmmPrepareInterfaceSwap(event.newDocument, routeLocale(event.to) || 'en');
return;
}
if (routeLocale(event.from) === routeLocale(event.to)) return;
// A fast navigation before the interface bridge loads only remounts the
// small UI roots. Article/sidebar content keeps its original lazy strategy.
event.newDocument.querySelectorAll('astro-island[client]:not([client="only"])').forEach(function (island) {
var options;
try { options = JSON.parse(island.getAttribute("opts") || "{}"); }
catch (error) { return; }
if (!/^(HeaderContentIsland|PageHeaderIsland|TableOfContentsIsland|FooterIsland)$/.test(options.name)) return;
options.value = "react";
island.setAttribute("opts", JSON.stringify(options));
island.setAttribute("client", "only");
});
}

async function navigateDocsTheme(theme) {
if (theme !== "light" && theme !== "dark") return false;
if (currentTheme() === theme) return true;
Expand Down Expand Up @@ -695,7 +671,6 @@
// locale immediately so standalone navigation tabs never flash on first paint.
syncLocaleTabs(currentRoute());
document.addEventListener("DOMContentLoaded", scheduleSync);
document.addEventListener("astro:before-swap", prepareLocaleSwap);
document.addEventListener("fern:island-hydrated", scheduleSync);
document.addEventListener("astro:page-load", scheduleSync);
window.addEventListener("pageshow", function () {
Expand Down
29 changes: 20 additions & 9 deletions scripts/check-docs-interface.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { runInNewContext } from "node:vm";

const script = await readFile(new URL("../fern/docs-interface.js", import.meta.url), "utf8");
const callbacks = [];
const tasks = [];
const listeners = {};
let observerCount = 0;
const observerCallbacks = [];
Expand Down Expand Up @@ -39,6 +40,7 @@ const window = {
location: { pathname: "/ar/prediction/overview" },
__sixmmDocsLocales: [{ code: "" }, { code: "ar" }, { code: "zh-CN" }, { code: "ja" }],
requestAnimationFrame: (callback) => callbacks.push(callback),
setTimeout: (callback) => tasks.push(callback),
addEventListener: (name, callback) => { listeners[name] = callback; },
};
const document = {
Expand All @@ -61,7 +63,13 @@ const sandbox = {
observe() {} disconnect() {}
},
};
function flush() { while (callbacks.length) callbacks.shift()(); }
function flushFrames() { while (callbacks.length) callbacks.shift()(); }
function flush() {
while (callbacks.length || tasks.length) {
flushFrames();
while (tasks.length) tasks.shift()();
}
}
runInNewContext(script, sandbox);
flush();
assert.equal(nodes[0].nodeValue, "Search", "Do not mutate text while React hydration is pending");
Expand All @@ -77,6 +85,9 @@ flush();
assert.equal(nodes[0].nodeValue, "Search", "A child island cannot alter markup while its parent layout is still hydrating");
layoutReady = true;
listeners["fern:island-hydrated"]();
flushFrames();
assert.equal(nodes[0].nodeValue, "Search", "An outer island effect must not rewrite labels in React's current render/paint turn");
assert.equal(attributes.get("aria-label"), "Search", "Accessibility labels also wait for the post-render task");
flush();
assert.equal(nodes[0].nodeValue, "بحث");
assert.equal(nodes[1].nodeValue, "نسخ الصفحة");
Expand All @@ -101,18 +112,18 @@ assert.equal(nodes[2].nodeValue, 'Search', 'Article text is never translated by
window.location.pathname = '/sdk/overview';
listeners['astro:page-load'](); flush();
assert.equal(nodes[0].nodeValue, 'Search', 'Returning to English must restore labels');
window.__sixmmPrepareInterfaceSwap(document,'zh-CN');
assert.equal(nodes[0].nodeValue,'Search','Unsupported initial UI languages normalize to Fern native English before hydration');
assert.equal(nodes[4].nodeValue,'Edit this page','Normalize the GitHub edit label before lazy footer hydration');
nodes[4].nodeValue='在仪表板中编辑';
window.__sixmmPrepareInterfaceSwap(document,'zh-CN');
assert.equal(nodes[4].nodeValue,'Edit this page','Both native edit label variants share the English key');
for (const label of ['编辑此页面', '在仪表板中编辑']) {
nodes[4].nodeValue = label;
window.location.pathname = '/sdk/overview';
listeners['astro:page-load'](); flush();
assert.equal(nodes[4].nodeValue, 'Edit this page', 'Both edit label variants remain localized after hydration');
}
nodes.push({ nodeValue: 'Light', parentElement: { closest: hydratedAncestor } });
window.__sixmmDocsLocales.push({ code: 'de' }, { code: 'id' }, { code: 'uk' }, { code: 'vi' });
window.location.pathname = '/de/sdk/overview'; listeners['astro:page-load'](); flush();
assert.equal(nodes.at(-1).nodeValue, 'Hell', 'Hydrated theme controls use the selected locale');
window.__sixmmPrepareInterfaceSwap(document, 'de');
assert.equal(nodes.at(-1).nodeValue, 'Light', 'Added theme translations must normalize back to native markup before hydration');
window.location.pathname = '/sdk/overview'; listeners['astro:page-load'](); flush();
assert.equal(nodes.at(-1).nodeValue, 'Light', 'Returning to English restores hydrated theme labels');
for (const [lang, expected] of [['id', 'Asisten'], ['uk', 'Помічник'], ['vi', 'Trợ lý']]) {
nodes[1].nodeValue = 'Assistant';
window.location.pathname = '/' + lang + '/sdk/overview'; listeners['astro:page-load'](); flush();
Expand Down
32 changes: 14 additions & 18 deletions scripts/check-widget-sync.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -784,29 +784,25 @@ const incomingIsland = {
setAttribute: (name, value) => incomingIslandAttributes.set(name, value),
};
function prepareIncomingLocale(from, to) {
adapterDocumentListeners["astro:before-swap"]({
adapterDocumentListeners["astro:before-swap"]?.({
from: new URL(from, adapterWindow.location.origin),
to: new URL(to, adapterWindow.location.origin),
newDocument: { querySelectorAll: () => [incomingIsland] },
});
}
prepareIncomingLocale("/zh-CN/sdk/overview", "/zh-CN/trading/overview");
assert.equal(incomingIslandAttributes.get("client"), "load", "Ordinary page navigation must keep normal SSR hydration");
prepareIncomingLocale("/sdk/overview", "/zh-CN/sdk/overview");
assert.equal(incomingIslandAttributes.get("client"), "only", "Cross-locale navigation must not hydrate against stale-locale state");
assert.equal(JSON.parse(incomingIslandAttributes.get("opts")).value, "react");
assert.equal(incomingIsland.innerHTML, "<astro-slot>Localized article content</astro-slot>", "Locale remounting must preserve article slots");
incomingIslandAttributes.set("client", "load");
incomingIslandAttributes.set("opts", JSON.stringify({ name: "PageHeaderIsland", value: true }));
prepareIncomingLocale("/zh-CN/sdk/overview", "/zh-CN/developer-api/overview");
assert.equal(incomingIslandAttributes.get("client"), "load", "Ordinary navigation keeps the original loading strategy");
assert.equal(incomingIsland.innerHTML, "<astro-slot>Localized article content</astro-slot>", "Subsequent navigation must preserve article slots");
let bridgeCalls=0;
adapterWindow.__sixmmPrepareInterfaceSwap=()=>{bridgeCalls++;};
incomingIslandAttributes.set('client','lazy');
prepareIncomingLocale('/sdk/overview','/zh-CN/sdk/overview');
assert.equal(incomingIslandAttributes.get('client'),'lazy','A ready interface bridge preserves deferred and lazy hydration');
assert.equal(bridgeCalls,1);
for (const strategy of ['load', 'idle', 'visible', 'lazy', 'only']) {
incomingIslandAttributes.set('client', strategy);
const before = [...incomingIslandAttributes];
for (const [from, to] of [
['/zh-CN/sdk/overview', '/zh-CN/trading/overview'],
['/sdk/overview', '/zh-CN/sdk/overview'],
['/zh-CN/sdk/overview', '/ja/sdk/overview'],
]) {
prepareIncomingLocale(from, to);
assert.deepEqual([...incomingIslandAttributes], before, 'Navigation must preserve Fern SSR hydration options');
assert.equal(incomingIsland.innerHTML, '<astro-slot>Localized article content</astro-slot>', 'Navigation must preserve incoming content');
}
}
assert.equal(
adapterRoot.dataset.sixmmDocsLocale,
"en",
Expand Down
64 changes: 64 additions & 0 deletions tests/browser/regression.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,42 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) {
});
});

await t.test('locale swaps preserve incoming SSR labels and hydration strategies at every loading phase', async () => {
const page = await browser.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
try {
await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><html lang="en"><body></body></html>' }));
await page.goto(origin);
for (const script of ['language-modal.js', 'docs-interface.js']) {
await page.addScriptTag({ content: await readFile(new URL('../../fern/' + script, import.meta.url), 'utf8') });
const results = await page.evaluate(locales => {
return locales.flatMap(locale => {
const target = locale.default ? '' : '/' + locale.code;
return [target, '', '/ja', '/ar'].map(source => {
const incoming = new DOMParser().parseFromString('<!doctype html><html><body></body></html>', 'text/html');
incoming.documentElement.lang = locale.code;
incoming.body.innerHTML = ['load', 'idle', 'visible', 'lazy', 'only'].map((strategy, index) =>
`<astro-island client="${strategy}" opts='{"name":"PageHeaderIsland","value":true}'>
<header id="${index ? 'header-' + index : 'fern-header'}"><button aria-label="搜索">搜索</button></header>
<div class="fern-page-actions"><button title="Copy page">Copy page</button><button>编辑此页面</button></div>
<p>${locale.label}</p><astro-slot>Localized content</astro-slot>
</astro-island>`).join('');
const before = incoming.documentElement.outerHTML;
const event = new Event('astro:before-swap');
Object.assign(event, { from: new URL(source + '/guide', location.origin), to: new URL(target + '/guide', location.origin), newDocument: incoming });
document.dispatchEvent(event);
return { locale: locale.code, source, preserved: incoming.documentElement.outerHTML === before };
});
});
}, locales);
assert.equal(results.length, locales.length * 4);
assert.deepEqual(results.filter(result => !result.preserved), [], `${script}: incoming text, attributes and loading strategies must survive until native hydration`);
}
assert.deepEqual(errors, []);
} finally { await page.close(); }
});

await t.test('nested hydration and excluded content preserve server text', async () => {
const markup = `<astro-island id="layout"><astro-island id="header-island"><header id="fern-header"><button id="search">Search</button></header></astro-island></astro-island>
<div id="fern-ask-ai-panel"><pre><code>${'<span>Search</span>'.repeat(100)}</code></pre>
Expand Down Expand Up @@ -168,6 +204,34 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) {
});
});

await t.test('outer readiness does not translate React content before deferred host bindings attach', async () => {
await withPage(browser, { pathname: '/uk/guide' }, async page => {
await page.evaluate(() => {
const island = document.createElement('astro-island');
island.setAttribute('data-fern-hydrated', '');
island.__reactContainer$fixture = {};
island.setAttribute('component-url', '/FooterIsland.fixture.js');
island.innerHTML = '<div id="fern-search-panel"><button id="deferred-label" aria-label="Search">Search</button></div>';
island.firstElementChild.__reactProps$fixture = {};
const outer = document.createElement('astro-island');
outer.setAttribute('data-fern-hydrated', '');
outer.__reactContainer$outer = {};
outer.appendChild(island);
document.body.appendChild(outer);
document.dispatchEvent(new Event('fern:island-hydrated'));
});
await page.waitForTimeout(120);
const label = page.locator('#deferred-label');
assert.equal(await label.textContent(), 'Search');
assert.equal(await label.getAttribute('aria-label'), 'Search');
// React attaches host bindings without changing matching server markup.
await label.evaluate(node => { node.__reactProps$fixture = {}; });
await page.waitForFunction(() => document.getElementById('deferred-label').textContent === 'Пошук');
assert.equal(await label.getAttribute('aria-label'), 'Пошук');
await label.evaluate(node => node.closest('astro-island').remove());
});
});

await t.test('late cards retain their existing effects after body replacements', async () => {
await withPage(browser, {}, async page => {
for (let swap = 0; swap < 2; swap++) {
Expand Down
Loading