From 64f78155f0de49ac00a1fd4cabbc6f1ec8a4ea27 Mon Sep 17 00:00:00 2001 From: Zakk Date: Wed, 28 Oct 2026 04:16:14 +0000 Subject: [PATCH] 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. --- changes/fix-font-wait.md | 3 +++ docs/fonts.md | 2 +- e2e/language.spec.ts | 9 ++++++++ src/fonts.css | 6 +++--- src/fonts.ts | 4 ++-- src/i18n/fonts.test.ts | 44 ++++++++++++++++++++++++++++++++++++++++ src/i18n/index.ts | 13 +++++++++--- src/i18n/load.test.ts | 8 ++++---- src/main.tsx | 2 +- 9 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 changes/fix-font-wait.md create mode 100644 src/i18n/fonts.test.ts diff --git a/changes/fix-font-wait.md b/changes/fix-font-wait.md new file mode 100644 index 00000000..fc3764ac --- /dev/null +++ b/changes/fix-font-wait.md @@ -0,0 +1,3 @@ +Fixed + +- Render translated pages with fallback fonts after a three-second wait when optional fonts stall. diff --git a/docs/fonts.md b/docs/fonts.md index 35cfeb5c..6d78b9a5 100644 --- a/docs/fonts.md +++ b/docs/fonts.md @@ -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. diff --git a/e2e/language.spec.ts b/e2e/language.spec.ts index 8e85b6a5..6c1fb835 100644 --- a/e2e/language.spec.ts +++ b/e2e/language.spec.ts @@ -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)); diff --git a/src/fonts.css b/src/fonts.css index b3f8b571..c45af556 100644 --- a/src/fonts.css +++ b/src/fonts.css @@ -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%; } diff --git a/src/fonts.ts b/src/fonts.ts index fb6fa456..e6adbadd 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -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 { +export function loadFaces(fonts: string | null, face?: string, text?: string): Promise { 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 ); diff --git a/src/i18n/fonts.test.ts b/src/i18n/fonts.test.ts new file mode 100644 index 00000000..fce6c7f6 --- /dev/null +++ b/src/i18n/fonts.test.ts @@ -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(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); +}); diff --git a/src/i18n/index.ts b/src/i18n/index.ts index e7fad92e..700bbc6c 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -49,9 +49,10 @@ const partLoaders = () => activity: import.meta.glob>('./locales/*.json', {query: {part: 'activity'}, import: 'default'}), rest: import.meta.glob>('./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>; +const FONT_WAIT_MS = 3000; function readCatalogue(lang: Lang, stage: Stage): Promise> { 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> { 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; + const deadline = new Promise(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>(); diff --git a/src/i18n/load.test.ts b/src/i18n/load.test.ts index 271bb27f..3d5d5cee 100644 --- a/src/i18n/load.test.ts +++ b/src/i18n/load.test.ts @@ -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); 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(resolve => (releaseActivity = resolve)); const rest = new Promise(resolve => (releaseRest = resolve)); const read = (_lang: string, stage: string): Promise> => - 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); 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(); diff --git a/src/main.tsx b/src/main.tsx index 9ccc1edc..94436a6a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -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 { const saved = readLang();