fix(fonts): bound catalogue waits for optional faces

Publish catalogue stages after three seconds when optional fonts stall, and clear completed deadlines. Reuse the common startup glyph warmup instead of loading it twice; cover stalled and completed font loads.
This commit is contained in:
Zakk committed 2026-10-28 06:58:10 +00:00
1 parent 0c40175370
commit 64f78155f0
9 files changed
+77 -14

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
Fixed
- Render translated pages with fallback fonts after a three-second wait when optional fonts stall.
+1 -1
View File
@@ -29,7 +29,7 @@ In development, the loader skips the probe and uses the installed Fontsource pac
Before publishing each catalogue stage (core, Activity and later pages), the loader awaits `document.fonts.load` for every message in that stage, including plural forms. The text comes from the catalogue, not a separate glyph list. Each subset is variable across weights 100–900, so loading it once makes it available at every UI weight. This also applies when changing languages.
Declaring the stylesheets or waiting for `document.fonts.ready` after rendering is not enough: `font-display: optional` can retain a system fallback for a late subset beside already-loaded Noto glyphs within one title. Loading the stage's glyphs before rendering avoids that mixture without a later font swap. A slow font archive delays the stage; an absent archive or a failed font request still allows system-font rendering.
Declaring the stylesheets or waiting for `document.fonts.ready` after rendering is not enough: `font-display: optional` can retain a system fallback for a late subset beside already-loaded Noto glyphs within one title. Loading the stage's glyphs before rendering avoids that mixture without a later font swap. Each stage waits at most three seconds for the archive, stylesheets and fonts, then renders with the system fallback if they are still pending. An absent archive or a failed font request also allows system-font rendering.
Only subsets intersecting the loaded catalogue stages are fetched, rather than the whole archive. This can fetch more subsets than the currently visible page uses. Segmented-control labels remain regular weight (400), as defined in [segmented.css](../src/ui/styles/segmented.css). [e2e/flag-font.spec.ts](../e2e/flag-font.spec.ts) checks actual Chromium title faces with delayed subsets in both Chinese languages at weights 400, 500, 600, 700 and 800.
+9
View File
@@ -116,6 +116,15 @@ const localeChunk = (lang?: string) =>
test.describe('language loading', () => {
// Chunks fetched by the service worker would bypass page.route.
test.use({serviceWorkers: 'block'});
test('renders translated navigation when optional font loads never settle', async ({page}) => {
await page.addInitScript(() => {
document.fonts.load = () => new Promise(() => {});
});
await page.goto('/#/activity');
await expect(page.locator('.rp-nav[href="#/activity"]')).toContainText(translate('en', 'nav.activity'), {timeout: 10000});
await expect(page.locator(`.rp-content ${loadingState}`)).toHaveCount(0);
});
test('fetches only the saved language, and only the parts Activity shows', async ({page}) => {
// The idle warm-up fetches the other pages' part once the browser is idle; held back, only rendering fetches remain.
await page.addInitScript(() => (window.requestIdleCallback = () => 0));
+3 -3
View File
@@ -3,9 +3,9 @@
`optional` rather than `swap`: a subset that arrives after the first paint would re-measure every label and shift
table columns sideways. The service worker caches each subset as it is fetched, so from the second visit the
fonts are in place before the page renders in its language and are used. Only the Latin, Cyrillic and Vietnamese faces are here,
for every language; the ideograph subsets are in fonts-tc.css and fonts-sc.css. Each catalogue stage waits for its
message glyphs before rendering, so a cold load cannot mix late optional subsets with system fallbacks. src/fonts.ts attaches all three only when the optional font
archive is installed. */
for every language; the ideograph subsets are in fonts-tc.css and fonts-sc.css. Each catalogue stage gives its
message glyphs up to three seconds to arrive before rendering, then permits system fallbacks if they are still pending.
src/fonts.ts attaches all three only when the optional font archive is installed. */
@font-face { font-family: 'Noto Sans TC'; font-style: normal; font-weight: 100 900; font-display: optional; src: url(@fontsource-variable/noto-sans-tc/files/noto-sans-tc-cyrillic-wght-normal.woff2) format('woff2'); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; ascent-override: 100%; descent-override: 20%; line-gap-override: 0%; }
@font-face { font-family: 'Noto Sans TC'; font-style: normal; font-weight: 100 900; font-display: optional; src: url(@fontsource-variable/noto-sans-tc/files/noto-sans-tc-vietnamese-wght-normal.woff2) format('woff2'); unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; ascent-override: 100%; descent-override: 20%; line-gap-override: 0%; }
@font-face { font-family: 'Noto Sans TC'; font-style: normal; font-weight: 100 900; font-display: optional; src: url(@fontsource-variable/noto-sans-tc/files/noto-sans-tc-latin-ext-wght-normal.woff2) format('woff2'); unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; ascent-override: 100%; descent-override: 20%; line-gap-override: 0%; }
+2 -2
View File
@@ -18,11 +18,11 @@ const commonFaces = () => (common ??= import('./fonts.css').then(() => globalThi
// Await the current catalogue part's glyphs before it renders. With optional faces, merely awaiting the stylesheet
// lets late subsets stay on a system fallback beside earlier Noto subsets, even after document.fonts.ready.
// One load covers every weight: each face is variable across 100–900. Missing archives or failed fonts stay optional.
export function loadFaces(fonts: string | null, face: string, text: string): Promise<unknown> {
export function loadFaces(fonts: string | null, face?: string, text?: string): Promise<unknown> {
return fontsInstalled().then(ok =>
ok
? Promise.all([commonFaces(), fonts && import(`./fonts-${fonts}.css`)])
.then(() => globalThis.document?.fonts?.load(`1em '${face}'`, text))
.then(() => (face ? globalThis.document?.fonts?.load(`1em '${face}'`, text) : undefined))
.catch(() => undefined)
: undefined
);
+44
View File
@@ -0,0 +1,44 @@
import {afterEach, beforeEach, expect, it, vi} from 'vitest';
// Reset the module boundary: setup has already loaded catalogues and cached the common font promise.
beforeEach(() => {
vi.resetModules();
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('publishes translated text after three seconds when the font load stalls', async () => {
const i18n = await import('./index');
let requested!: () => void;
const started = new Promise<void>(resolve => (requested = resolve));
vi.stubGlobal('document', {
fonts: {
load: () => {
requested();
return new Promise(() => {});
}
}
});
const language = i18n.loadLanguage('en');
await started;
await vi.advanceTimersByTimeAsync(2999);
expect(i18n.isLoaded('en')).toBe(false);
expect(i18n.translate('en', 'nav.activity')).toBe('nav.activity');
await vi.advanceTimersByTimeAsync(1);
await language;
expect(i18n.isLoaded('en')).toBe(true);
expect(i18n.translate('en', 'nav.activity')).toBe('Activity');
expect(vi.getTimerCount()).toBe(0);
});
it('publishes immediately and clears the deadline when optional fonts finish', async () => {
const i18n = await import('./index');
vi.stubGlobal('document', {fonts: {load: () => Promise.resolve([])}});
await i18n.loadLanguage('en');
expect(i18n.translate('en', 'nav.activity')).toBe('Activity');
expect(vi.getTimerCount()).toBe(0);
});
+10 -3
View File
@@ -49,9 +49,10 @@ const partLoaders = () =>
activity: import.meta.glob<Partial<Catalogue>>('./locales/*.json', {query: {part: 'activity'}, import: 'default'}),
rest: import.meta.glob<Partial<Catalogue>>('./locales/*.json', {query: {part: 'rest'}, import: 'default'})
});
// Each part is its own chunk, loaded on first use; translate reads only what has loaded. Its glyphs are ready before
// the part is published, including later pages and language switches, so optional subsets cannot mix with fallbacks.
// Each part is its own chunk, loaded on first use; translate reads only what has loaded. Give its optional glyphs
// a short head start, then publish even if the font host stalls so the page can render with the system fallback.
type Reader = (lang: Lang, stage: Stage) => Promise<Partial<Catalogue>>;
const FONT_WAIT_MS = 3000;
function readCatalogue(lang: Lang, stage: Stage): Promise<Partial<Catalogue>> {
const part = partLoaders()[stage][`./locales/${lang}.json`]();
const {fonts, faces} = languages.find(language => language.id === lang)!;
@@ -59,7 +60,13 @@ function readCatalogue(lang: Lang, stage: Stage): Promise<Partial<Catalogue>> {
const text = Object.values(messages)
.flatMap(message => (typeof message === 'string' ? message : Object.values(message)))
.join('');
return loadFaces(fonts, faces[0], text).then(() => messages);
let timer: ReturnType<typeof setTimeout>;
const deadline = new Promise<void>(resolve => {
timer = setTimeout(resolve, FONT_WAIT_MS);
});
return Promise.race([loadFaces(fonts, faces[0], text), deadline])
.then(() => messages)
.finally(() => clearTimeout(timer));
});
}
const catalogues = new Map<Lang, Partial<Catalogue>>();
+4 -4
View File
@@ -105,13 +105,13 @@ it('retries a failed stage after its reader recovers', async () => {
? Promise.resolve({})
: offline
? Promise.reject(new Error('offline'))
: Promise.resolve({'ui.activity': 'Activity'});
: Promise.resolve({'ui.activity': 'Activity'} as Partial<Catalogue>);
try {
await i18n.loadLanguage('en', read);
await expect(i18n.loadStage('activity')).rejects.toThrow('offline');
offline = false;
await i18n.loadStage('activity');
expect(i18n.translate('en', 'ui.activity')).toBe('Activity');
expect(i18n.translate('en', 'ui.activity' as Key)).toBe('Activity');
} finally {
vi.unstubAllGlobals();
}
@@ -124,7 +124,7 @@ it('waits for the requested stage but not a later stage already in flight', asyn
const activity = new Promise<void>(resolve => (releaseActivity = resolve));
const rest = new Promise<void>(resolve => (releaseRest = resolve));
const read = (_lang: string, stage: string): Promise<Partial<Catalogue>> =>
stage === 'core' ? Promise.resolve({}) : (stage === 'activity' ? activity : rest).then(() => ({'ui.activity': 'Activity'}));
stage === 'core' ? Promise.resolve({}) : (stage === 'activity' ? activity : rest).then(() => ({'ui.activity': 'Activity'}) as Partial<Catalogue>);
await i18n.loadLanguage('en', read);
let restReady = false;
const later = i18n.loadStage('rest').then(() => {
@@ -139,7 +139,7 @@ it('waits for the requested stage but not a later stage already in flight', asyn
expect(activityReady).toBe(false);
releaseActivity();
await earlier;
expect(i18n.translate('en', 'ui.activity')).toBe('Activity');
expect(i18n.translate('en', 'ui.activity' as Key)).toBe('Activity');
expect(restReady).toBe(false);
} finally {
releaseActivity();
+1 -1
View File
@@ -22,7 +22,7 @@ if (document.documentElement.dataset.family === 'glass')
if (isChunkLoadError(error)) reloadForStaleChunk();
});
// The font archive check starts now, so it overlaps the catalogue fetch the language load waits on.
void loadFaces(null, 'Noto Sans TC', 'doona');
void loadFaces(null);
// The saved language, or the default when its catalogue cannot be fetched; rejects only when neither loads.
function startLanguage(): Promise<Lang> {
const saved = readLang();