From 31ccdf0828e043ad1d80d46d33f511c710da63bb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 11:13:25 +0000 Subject: [PATCH 1/2] fix(landing): keep the site top bar sticky while scrolling Long homepage and content pages scrolled the brand, language switcher, and GitHub links out of reach. Stick both chrome bars to the viewport, clear the content-page rail under the bar, and drop overflow-x from #landing-hero so sticky can attach to the viewport rather than the section. Co-authored-by: ZhouHang --- CHANGELOG.md | 2 ++ docs/design-system.md | 10 +++++-- .../2026-11-22-sticky-site-header.md | 27 +++++++++++++++++++ docs/ops/cloudflare-and-webmcp-checklist.md | 5 ++-- public/home.css | 15 +++++++++-- public/landing.css | 19 +++++++++---- test/e2e/site-design-consistency.spec.ts | 19 +++++++++++++ test/unit/design-contract.test.ts | 17 ++++++++++++ 8 files changed, 103 insertions(+), 11 deletions(-) create mode 100644 docs/explorations/2026-11-22-sticky-site-header.md diff --git a/CHANGELOG.md b/CHANGELOG.md index fcc470822..da8e4945b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ notes. Entries describe what users experience, not internal refactors. ### Changed +- The site top bar stays fixed while you scroll the homepage and content pages, + so language, GitHub and brand links remain reachable past the first screen. - Nightly CI now runs the API surface, keyboard shortcut, and seeded monkey sweeps (previously documented as nightly but never scheduled). diff --git a/docs/design-system.md b/docs/design-system.md index a61449f03..717343bcf 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -73,15 +73,21 @@ Notion 正文 708)。**不存在"一个正确的宽度",只存在按内容 | ----------------- | ------------------------ | -------------------------------- | -------------------------- | | h1 | 64/700(hero,刻意更重) | 40/700,`letter-spacing: -1.2px` | 同内容页 | | body | 16px / 1.65 | 16px / 1.65 | 16px / 1.65 | -| 顶栏 `header.bar` | 有 | 有 | 有 | +| 顶栏 `header.bar` | 有(sticky) | 有(sticky) | 有(sticky) | | 页脚 | 有 | 有 | **无** | **"应用页有顶栏、无页脚"是有意的**:`/history` 和 `/embed-demo.html` 是来办事的地方, 不是浏览站点的地方;页脚的站内导航在那里只会挡路。这与 Gmail / Notion / Linear 一致。 但顶栏必须有——用户是从首页走过来的,顶栏消失会让人以为跳到了别的站。 +**顶栏滚动时固定**(`position: sticky; top: 0`):首页与内容页都够长,滚过首屏后 +仍要够得到语言切换与 GitHub。背景用 `--ran-color-bg` 实底,不透内容。首页的 +`#landing-hero` **不能**设 `overflow-x`(非 visible 的 overflow 会让 sticky 贴在 +区块上而不是视口上)。内容页右侧目录栏的 `top` 要清过这条约 4.5rem 的固定顶栏。 + 顶栏和页脚的样式**只有一份**(`landing.css`),页面复用它的类名与结构, -而不是抄一遍数值。`/history` 因此直接 `` 了 `landing.css`。 +而不是抄一遍数值。`/history` 因此直接 `` 了 `landing.css`。首页自己的那份 +在 `home.css`(不加载 `landing.css`),两份由 `design-contract` 钉住一致。 ## 四、按钮两档 diff --git a/docs/explorations/2026-11-22-sticky-site-header.md b/docs/explorations/2026-11-22-sticky-site-header.md new file mode 100644 index 000000000..243e8a891 --- /dev/null +++ b/docs/explorations/2026-11-22-sticky-site-header.md @@ -0,0 +1,27 @@ +# Sticky site header on home and content pages (2026-11-22) + +## Why + +The homepage and long content pages scroll past the first viewport. Without a +fixed top bar, brand / language / GitHub disappear — the controls people still +need after reading the hero. + +## What changed + +- `public/home.css` `#landing-hero .bar` and `public/landing.css` `header.bar`: + `position: sticky; top: 0; z-index: 20; background: var(--ran-color-bg)`. +- Removed `overflow-x: hidden` from `#landing-hero`. Any non-visible overflow on + that ancestor makes sticky stick to the section instead of the viewport, so + the bar still scrolled away. Horizontal spill is already contained on the + pieces that can overflow (docwin, wordmark ellipsis); body keeps + `overflow-wrap: break-word` for long Latin runs. +- Content-page `.side` sticky `top` / `max-height` now clear the ~4.5rem sticky + bar; the old `top: space-8` parked the rail behind the chrome once the bar stuck. +- `docs/design-system.md` records the sticky rule; `design-contract` and + `site-design-consistency` pin both stylesheets and the scroll behavior. + +## Reverse verification + +Temporarily drop `position: sticky` from either bar rule: the new unit pin in +`design-contract` fails, and the E2E "top bar stays pinned…" case reports +`bar.top` leaving 0 after `scrollBy(900)`. diff --git a/docs/ops/cloudflare-and-webmcp-checklist.md b/docs/ops/cloudflare-and-webmcp-checklist.md index 370f3419d..f5e44cfae 100644 --- a/docs/ops/cloudflare-and-webmcp-checklist.md +++ b/docs/ops/cloudflare-and-webmcp-checklist.md @@ -77,5 +77,6 @@ Boolean(document.modelContext ?? navigator.modelContext); `edit.chaxus.com/fonts` + wasm URL. Deleted slot `/fonts/017` no longer serves old proprietary bytes. - [x] WebMCP token in `_headers` / `sws.toml` (live after next production deploy) -- [ ] Production `curl -sI` shows `Origin-Trial` and console `modelContext` is truthy - (needs #309 / token commit deployed to `edit.chaxus.com`) +- [x] Production `curl -sI https://edit.chaxus.com/editor` shows `Origin-Trial` + (verified 2026-11-22). Console `modelContext` still needs a Chrome ≥ 149 + hand check on `/editor?new=docx`. diff --git a/public/home.css b/public/home.css index a6f1c124e..543ee9647 100644 --- a/public/home.css +++ b/public/home.css @@ -66,7 +66,10 @@ body { line-height: 1.65; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; - overflow-x: hidden; + /* Do not set overflow-x here: any non-visible overflow on this ancestor + makes position:sticky on .bar stick to #landing-hero instead of the + viewport, so the top bar scrolls away with the page. Horizontal spill is + contained on the sections that can overflow (main / foot / docwin). */ } #landing-hero * { box-sizing: border-box; @@ -245,9 +248,17 @@ body { --ran-dropdown-arrow-display: none; } -/* ---------- top bar ---------- */ +/* ---------- top bar ---------- + Sticky on scroll so Open / language / GitHub stay reachable past the hero. + Opaque site background (not translucent blur): content must not read through + the bar, and the rest of the chrome is flat token surfaces. Kept in step with + landing.css `header.bar` — design-contract pins both. */ #landing-hero .bar { + position: sticky; + top: 0; + z-index: 20; border-bottom: 1px solid var(--ran-color-border); + background: var(--ran-color-bg); } #landing-hero .bar .wrap { display: flex; diff --git a/public/landing.css b/public/landing.css index e2e5b4280..09bbf9db1 100644 --- a/public/landing.css +++ b/public/landing.css @@ -33,14 +33,21 @@ a:focus-visible { outline-offset: 2px; } -/* ---------- top bar (mirrors the homepage bar) ---------- */ +/* ---------- top bar (mirrors the homepage bar) ---------- + Sticky on scroll so brand / GitHub / language stay reachable on long pages. + Opaque site background (not translucent blur). Kept in step with + `#landing-hero .bar` in home.css — design-contract pins both. */ header.bar { + position: sticky; + top: 0; + z-index: 20; display: flex; align-items: center; justify-content: space-between; gap: var(--ran-space-4); padding: var(--ran-space-4) clamp(20px, 5vw, 56px); border-bottom: 1px solid var(--ran-color-border); + background: var(--ran-color-bg); } header.bar .brand { display: inline-flex; @@ -299,13 +306,15 @@ header.bar nav a:hover { .side { display: block; position: sticky; - /* clears the top bar and leaves the same air the article has */ - top: var(--ran-space-8); + /* Clears the sticky top bar (~4.5rem / 72px measured) then leaves the same + air the article has. Before the bar stuck, `top: space-8` was enough; + under a sticky bar that value parks the rail behind the chrome. */ + top: calc(4.5rem + var(--ran-space-4)); align-self: start; padding-top: var(--ran-space-6); /* /help lists nine sections; a rail taller than the viewport would clip - its last links with no way to reach them. */ - max-height: calc(100vh - var(--ran-space-16)); + its last links with no way to reach them. Subtract the sticky bar too. */ + max-height: calc(100vh - 4.5rem - var(--ran-space-8)); overflow-y: auto; scrollbar-width: thin; } diff --git a/test/e2e/site-design-consistency.spec.ts b/test/e2e/site-design-consistency.spec.ts index 544c90903..0e286f50d 100644 --- a/test/e2e/site-design-consistency.spec.ts +++ b/test/e2e/site-design-consistency.spec.ts @@ -132,6 +132,25 @@ test('all seven localized generated headers keep their localized accessible home } }); +test('top bar stays pinned to the viewport while the page scrolls', async ({ page }) => { + // Homepage and a long content page: without sticky the bar's y leaves 0 after + // scroll. Reverse: remove position:sticky from home.css / landing.css and this + // goes red (bar.top jumps with scrollY). + await page.setViewportSize({ width: 1280, height: 800 }); + for (const route of ['/', '/help']) { + await page.goto(route); + const header = page.locator('header.bar'); + await expect(header).toBeVisible(); + await expect(header).toHaveCSS('position', 'sticky'); + const before = (await header.boundingBox())!; + expect(before.y).toBeLessThanOrEqual(1); + await page.evaluate(() => window.scrollBy(0, 900)); + const after = (await header.boundingBox())!; + expect(after.y, `${route} bar left the viewport top after scroll`).toBeLessThanOrEqual(1); + await expect(header.locator('.brand')).toBeVisible(); + } +}); + for (const scheme of ['light', 'dark'] as const) { test(`history uses the actual modal heading and semantic danger states in ${scheme}`, async ({ page }) => { await observeComponents(page); diff --git a/test/unit/design-contract.test.ts b/test/unit/design-contract.test.ts index 98c7fa19d..8dd9e8cd5 100644 --- a/test/unit/design-contract.test.ts +++ b/test/unit/design-contract.test.ts @@ -112,6 +112,23 @@ describe('page width scale', () => { expect(declaration(landing, 'body', 'line-height')).toBe('1.65'); expect(declaration(home, '#landing-hero', 'line-height')).toBe('1.65'); }); + + it('keeps the top bar sticky and opaque in both chrome stylesheets', () => { + // Long pages (home, help, convert) scroll past the first viewport; without + // sticky the brand / language / GitHub controls disappear. Both bars must + // stick the same way -- the homepage does not load landing.css. + for (const [name, css, selector] of [ + ['home.css', home, '#landing-hero .bar'], + ['landing.css', landing, 'header.bar'], + ] as Array<[string, string, string]>) { + expect(declaration(css, selector, 'position'), `${name} sticky`).toBe('sticky'); + expect(declaration(css, selector, 'top'), `${name} top`).toBe('0'); + expect(declaration(css, selector, 'background'), `${name} opaque`).toBe('var(--ran-color-bg)'); + } + // overflow-x on #landing-hero would make sticky stick to the section, not + // the viewport -- the bar would still scroll away. + expect(declaration(home, '#landing-hero', 'overflow-x')).toBeUndefined(); + }); }); describe('page chrome', () => { From d3aea774fbd360ec1b0a726ad8ee981d5b9e5e61 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 11:27:43 +0000 Subject: [PATCH 2/2] perf(fonts): clamp open-time NeedStyles from Document_CreateFontMap Skip unused italic/bold/BI face downloads on Word/Slide open by rewriting LogicDocument.Fonts after CheckFontNeeds from CreateFontMap bits, keep Regular+Italic for chrome, leave paste and map-absent extras alone, and honor the same bits in x2t fontSources. Unit + embed-regression cover it; reverse verify: disable rewrite and Arial stays at 15. Co-authored-by: ZhouHang --- CHANGELOG.md | 3 + .../2026-11-22-font-needstyles-clamp.md | 44 +++ lib/onlyoffice/guards/font-loading.ts | 293 ++++++++++++++---- lib/onlyoffice/guards/x2t-worker.ts | 15 +- lib/onlyoffice/iframe-guards.ts | 8 +- test/e2e/embed-regression.spec.ts | 47 ++- test/unit/font-need-styles.test.ts | 105 +++++++ 7 files changed, 456 insertions(+), 59 deletions(-) create mode 100644 docs/explorations/2026-11-22-font-needstyles-clamp.md create mode 100644 test/unit/font-need-styles.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index da8e4945b..9c43e0525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ notes. Entries describe what users experience, not internal refactors. ### Changed +- Opening a Word or PowerPoint file downloads only the font faces the document + actually uses (regular / bold / italic), instead of every face of every + family up front. Pasting or applying a new style still fetches what it needs. - The site top bar stays fixed while you scroll the homepage and content pages, so language, GitHub and brand links remain reachable past the first screen. - Nightly CI now runs the API surface, keyboard shortcut, and seeded monkey diff --git a/docs/explorations/2026-11-22-font-needstyles-clamp.md b/docs/explorations/2026-11-22-font-needstyles-clamp.md new file mode 100644 index 000000000..3c52babfe --- /dev/null +++ b/docs/explorations/2026-11-22-font-needstyles-clamp.md @@ -0,0 +1,44 @@ +# Open-time NeedStyles clamp (font-load guard 15c) — 2026-11-22 + +## Why + +`CheckFontNeeds` builds `new AscFonts.CFont(name)` from name-only +`Document_Get_AllFontNames`, and the CFont ctor turns a missing style into +**NeedStyles = 15** (every face). A Regular-only Latin one-pager still queued +Italic/Bold/BI files for every family that had them. Style-aware data already +existed in `Document_CreateFontMap` (Style 0..3) but the open path never used it. + +## What we did + +- `lib/onlyoffice/guards/font-loading.ts`: wrap `DrawingDocument.CheckFontNeeds` + (primary) and `LoadDocumentFonts` (belt). Read + `Document_CreateFontMap()`, map Style → face bits (0→1, 1→4, 2→2, 3→8, + always `| 1`), rewrite `LogicDocument.Fonts`. Families **in** the map are + narrowed to `known | Regular | Italic` (Italic covers chrome / placeholders + that never appear in CreateFontMap). Families only on the open list + (style-sheet / theme extras) **keep the vendor NeedStyles** (usually 15) — + clamping those to Regular-only caused `asc_onError -25`. Dropping Italic on + mapped families also surfaced tip-level `-25` on first paint. + `LoadDocumentFonts2` (paste) does not go through CheckFontNeeds, so it stays + unclamped. The iframe poll waits for the CheckFontNeeds hook on word/slide. +- `fontSources()` in `x2t-worker.ts` now honors the same bits so conversion does + not re-pull every face after the open clamp. +- Pure helpers + bit filtering pinned in `test/unit/font-need-styles.test.ts`; + live clamp in `embed-regression` "open-time NeedStyles is clamped…" + (expects Arial NeedStyles === 7 for a Regular+Bold sample). + +## Reverse verification + +Temporarily short-circuit `rewriteFontsNeedStyles` so it returns without writing: +the new E2E fails with Arial NeedStyles still **15** (expected **7**). Restoring +the rewrite turns it green again. Unit tests for `fontSources(NeedStyles=1)` fail +if the bit check in `x2t-worker.ts` is removed. + +Keeping Italic on mapped families also removed the tip-level `asc_onError -25` +that appeared when the clamp was Regular|Bold only (5). + +## Out of scope + +Cell editor (no useful CreateFontMap on open). Changing vendor x2t / rebuilding +wasm. Interactive `LoadFont` still requests 15 when the user first applies a +new face — that is intentional. diff --git a/lib/onlyoffice/guards/font-loading.ts b/lib/onlyoffice/guards/font-loading.ts index b81eee927..7fc8b139f 100644 --- a/lib/onlyoffice/guards/font-loading.ts +++ b/lib/onlyoffice/guards/font-loading.ts @@ -1,49 +1,197 @@ /** - * 15. Font-load acceleration. The SDK's CFontLoader works through fonts_loading - * strictly one family at a time (LoadFontAsync for the faces of - * fonts_loading[0], poll every 50ms until they land, shift, repeat), so a real - * CJK deck's 30 families cost 30 serial round trips of multi-MB downloads -- - * minutes on a cold CDN path. Two coordinated patches, both - * semantics-preserving: - * 15a. IsNeedDefaultFonts -> false: the Word/Slide editors preload - * Arial/Symbol/Wingdings/Courier/Times (12 files, 3.2 MB) on every open - * "just in case"; the runtime path (LoadDocumentFonts2) already fetches any - * of them on first actual use. - * 8b. after the vendor enqueues the document's fonts, kick off LoadFontAsync - * for every still-unloaded face of every queued family at once, so the - * browser downloads them in parallel and the serial poll finds each one - * already in flight or done. + * 15. Font-load acceleration + face narrowing. + * + * The SDK's CFontLoader works through fonts_loading strictly one family at a + * time (LoadFontAsync for the faces of fonts_loading[0], poll every 50ms until + * they land, shift, repeat), so a real CJK deck's 30 families cost 30 serial + * round trips of multi-MB downloads -- minutes on a cold CDN path. + * + * Coordinated patches, all semantics-preserving on the happy path: + * 15a. IsNeedDefaultFonts -> false: Word/Slide preload Arial/Symbol/Wingdings/ + * Courier/Times (12 files, 3.2 MB) on every open "just in case"; the runtime + * path (LoadDocumentFonts2) already fetches any of them on first actual use. + * 15b. After the vendor enqueues the document's fonts, kick off LoadFontAsync + * for every still-unloaded face of every queued family at once. + * 15c. Clamp NeedStyles after CheckFontNeeds from Document_CreateFontMap + * (Style 0..3 → face bits) instead of the open path's perpetual 15. Known + * families keep map bits | Regular | Italic (Italic covers chrome / + * placeholders that never appear in CreateFontMap). Families on the load + * list but absent from the map keep the vendor request (usually 15). Paste + * goes through LoadDocumentFonts2 without CheckFontNeeds, so it stays + * unclamped. Conversion savings need fontSources() to honor the same bits. */ -export function installFontLoadAcceleration(win: Window): boolean { - const fontWin = win as unknown as { - Asc?: { - editor?: { - IsNeedDefaultFonts?: () => boolean; - FontLoader?: { - fonts_loading?: Array<{ - indexR: number; - indexI: number; - indexB: number; - indexBI: number; - needR?: boolean; - needI?: boolean; - needB?: boolean; - needBI?: boolean; - NeedStyles?: number; - }>; - fontFiles?: Array<{ CheckLoaded: () => boolean; LoadFontAsync: (path: string, cb: unknown) => unknown }>; - fontFilesPath?: string; - LoadDocumentFonts?: (...args: unknown[]) => unknown; - LoadDocumentFonts2?: (...args: unknown[]) => unknown; - }; + +/** NeedStyles face bits used by AscFonts / CFontLoader. */ +export const NEED_STYLE_R = 1; +export const NEED_STYLE_I = 2; +export const NEED_STYLE_B = 4; +export const NEED_STYLE_BI = 8; +export const NEED_STYLE_ALL = 15; + +/** CreateFontMap Style (Bold?1:0)+(Italic?2:0) → NeedStyles face bit. */ +export function styleFlagToNeedStyles(style: number): number { + switch (style & 3) { + case 1: + return NEED_STYLE_B; + case 2: + return NEED_STYLE_I; + case 3: + return NEED_STYLE_BI; + default: + return NEED_STYLE_R; + } +} + +/** + * Collapse Document_CreateFontMap() output into family → NeedStyles. + * Always includes Regular so a family never lands with NeedStyles 0 (vendor + * treats 0 as 15 via `x || 15` in the CFont constructor). + */ +export function needStylesByFamilyFromFontMap(fontMap: Record): Record { + const out: Record = {}; + for (const [key, value] of Object.entries(fontMap)) { + if (value && typeof value === 'object' && 'Name' in (value as object)) { + const entry = value as { Name: unknown; Style?: unknown }; + const name = String(entry.Name ?? ''); + if (!name) continue; + const style = typeof entry.Style === 'number' ? entry.Style : 0; + out[name] = (out[name] ?? 0) | styleFlagToNeedStyles(style) | NEED_STYLE_R; + continue; + } + // AscFormat.checkThemeFonts replaces +mj-lt placeholders with real family + // names whose value is the number 1 (not a {Name,Style} entry). + if (value === 1 || value === true) { + if (!key || key.startsWith('+')) continue; + out[key] = (out[key] ?? 0) | NEED_STYLE_R; + } + } + return out; +} + +export function clampNeedStylesForFamily(requested: number | undefined, known: number | undefined): number { + if (known !== undefined) { + // Always keep Regular. Also keep Italic: the word/slide chrome and some + // theme placeholders render italic without a body run that CreateFontMap + // would have seen; dropping it produced tip-level asc_onError -25 on open. + return known | NEED_STYLE_R | NEED_STYLE_I; + } + // Fonts on the open list but absent from CreateFontMap are often style-sheet + // / theme faces that Get_AllFontNames saw and CreateFontMap has not walked + // yet. Keep the vendor request (usually 15) so a heading style that is bold + // in the stylesheet but unused in body text still has its face. + if (requested === undefined || requested === 0) return NEED_STYLE_ALL; + return requested; +} + +type FontLoader = { + fonts_loading?: Array<{ + indexR: number; + indexI: number; + indexB: number; + indexBI: number; + needR?: boolean; + needI?: boolean; + needB?: boolean; + needBI?: boolean; + NeedStyles?: number; + }>; + fontFiles?: Array<{ CheckLoaded: () => boolean; LoadFontAsync: (path: string, cb: unknown) => unknown }>; + fontFilesPath?: string; + AddLoadFonts?: (name: string, styles?: number) => unknown; + LoadDocumentFonts?: (...args: unknown[]) => unknown; + LoadDocumentFonts2?: (...args: unknown[]) => unknown; +}; + +type LogicDocument = { + Document_CreateFontMap?: () => Record; + Fonts?: unknown; +}; + +type EditorApi = { + IsNeedDefaultFonts?: () => boolean; + FontLoader?: FontLoader; + WordControl?: { + m_oLogicDocument?: LogicDocument; + m_oDrawingDocument?: { CheckFontNeeds?: (...args: unknown[]) => unknown }; + }; +}; + +type FontWindow = Window & { + Asc?: { editor?: EditorApi }; + AscCommon?: { g_font_loader?: FontLoader }; + __ooFontLoadAccelerated?: boolean; + __ooFontNeedStylesHooked?: boolean; + __ooFontNeedStylesClamped?: boolean; + __ooFontNeedStylesDebug?: unknown; +}; + +function collectOpenNeedStyles(api: EditorApi): Record | null { + try { + const create = api.WordControl?.m_oLogicDocument?.Document_CreateFontMap; + if (typeof create !== 'function') return null; + const map = create.call(api.WordControl!.m_oLogicDocument); + if (!map || typeof map !== 'object') return null; + const needs = needStylesByFamilyFromFontMap(map); + return Object.keys(needs).length > 0 ? needs : null; + } catch { + return null; + } +} + +function rewriteFontsNeedStyles(fonts: unknown, needs: Record): void { + if (!fonts || typeof fonts !== 'object') return; + for (const key of Object.keys(fonts as object)) { + const font = (fonts as Record)[key]; + if (!font || typeof font !== 'object') continue; + const name = font.name ?? font.Name; + if (typeof name !== 'string' || !name) continue; + font.NeedStyles = clampNeedStylesForFamily(font.NeedStyles, needs[name]); + } +} + +/** Primary 15c hook: runs after Fonts is built, before LoadDocumentFonts reads it. */ +function installNeedStylesClamp(fontWin: FontWindow, fontApi: EditorApi): boolean { + if (fontWin.__ooFontNeedStylesHooked) return true; + const drawing = fontApi.WordControl?.m_oDrawingDocument; + if (!drawing || typeof drawing.CheckFontNeeds !== 'function') return false; + const origCheck = drawing.CheckFontNeeds.bind(drawing); + drawing.CheckFontNeeds = (...args: unknown[]) => { + const out = origCheck(...args); + try { + const needs = collectOpenNeedStyles(fontApi); + const fonts = fontApi.WordControl?.m_oLogicDocument?.Fonts; + fontWin.__ooFontNeedStylesDebug = { + via: 'CheckFontNeeds', + hasMap: needs !== null, + familyCount: needs ? Object.keys(needs).length : 0, + sample: needs ? Object.entries(needs).slice(0, 8) : [], + fontsType: fonts == null ? 'null' : Array.isArray(fonts) ? 'array' : typeof fonts, }; - }; - __ooFontLoadAccelerated?: boolean; + if (needs && fonts) { + rewriteFontsNeedStyles(fonts, needs); + fontWin.__ooFontNeedStylesClamped = true; + } + } catch { + // best-effort: open still works with NeedStyles 15 + } + return out; }; + fontWin.__ooFontNeedStylesHooked = true; + return true; +} + +export function installFontLoadAcceleration(win: Window): boolean { + const fontWin = win as FontWindow; const fontApi = fontWin.Asc?.editor; - const loader = fontApi?.FontLoader; - if (fontApi && loader && typeof loader.LoadDocumentFonts === 'function' && !fontWin.__ooFontLoadAccelerated) { + if (!fontApi) return false; + + // DrawingDocument appears after FontLoader; keep trying on each poll. + installNeedStylesClamp(fontWin, fontApi); + + const loader = fontWin.AscCommon?.g_font_loader ?? fontApi.FontLoader; + if (loader && typeof loader.LoadDocumentFonts === 'function' && !fontWin.__ooFontLoadAccelerated) { fontApi.IsNeedDefaultFonts = () => false; + if (fontApi.FontLoader !== loader) fontApi.FontLoader = loader; const prefetchQueued = () => { const files = loader.fontFiles; @@ -51,10 +199,11 @@ export function installFontLoadAcceleration(win: Window): boolean { if (!files || typeof path !== 'string') return; let started = 0; for (const info of loader.fonts_loading || []) { - // NeedStyles 15 (all faces) is what the loader itself resolves - // to when it later inspects the entry; mirror that superset so - // no face the poll will wait for is left un-requested. - const wantAll = info.NeedStyles === undefined || (info.NeedStyles & 15) === 15; + // NeedStyles 15 (all faces) is what the loader itself resolves to when + // it later inspects the entry; mirror that superset so no face the poll + // will wait for is left un-requested. After 15c clamping, NeedStyles is + // usually a subset and need* flags from CheckFontLoadStyles drive this. + const wantAll = info.NeedStyles === undefined || (info.NeedStyles & NEED_STYLE_ALL) === NEED_STYLE_ALL; const faces: Array<[boolean | undefined, number]> = [ [wantAll || info.needR, info.indexR], [wantAll || info.needI, info.indexI], @@ -66,8 +215,8 @@ export function installFontLoadAcceleration(win: Window): boolean { const file = files[idx]; if (!file || file.CheckLoaded()) continue; try { - // LoadFontAsync is idempotent per file: it returns early - // once a fetch is in flight (Status !== -1). + // LoadFontAsync is idempotent per file: it returns early once a + // fetch is in flight (Status !== -1). file.LoadFontAsync(path, null); started++; } catch { @@ -78,13 +227,37 @@ export function installFontLoadAcceleration(win: Window): boolean { if (started) console.log(`[OO] font prefetch: ${started} face(s) requested in parallel`); }; - for (const name of ['LoadDocumentFonts', 'LoadDocumentFonts2'] as const) { - const orig = loader[name]; - if (typeof orig !== 'function') continue; - loader[name] = function (this: typeof loader, ...args: unknown[]) { - const out = orig.apply(this, args); - // The vendor has now filled fonts_loading and started family #1; - // request everything else too. + const origLoad = loader.LoadDocumentFonts.bind(loader); + loader.LoadDocumentFonts = (...args: unknown[]) => { + // Belt: if CheckFontNeeds was missed (PDF / unusual path), clamp here too. + try { + const needs = collectOpenNeedStyles(fontApi); + if (needs) { + rewriteFontsNeedStyles(args[0] ?? fontApi.WordControl?.m_oLogicDocument?.Fonts, needs); + fontWin.__ooFontNeedStylesClamped = true; + fontWin.__ooFontNeedStylesDebug = { + via: 'LoadDocumentFonts', + hasMap: true, + familyCount: Object.keys(needs).length, + sample: Object.entries(needs).slice(0, 8), + }; + } + } catch { + // best-effort + } + const out = origLoad(...args); + try { + prefetchQueued(); + } catch { + // acceleration is best-effort + } + return out; + }; + + if (typeof loader.LoadDocumentFonts2 === 'function') { + const origLoad2 = loader.LoadDocumentFonts2.bind(loader); + loader.LoadDocumentFonts2 = (...args: unknown[]) => { + const out = origLoad2(...args); try { prefetchQueued(); } catch { @@ -93,8 +266,18 @@ export function installFontLoadAcceleration(win: Window): boolean { return out; }; } + fontWin.__ooFontLoadAccelerated = true; - console.log('[OO] font-load acceleration installed (no default-font preload, parallel prefetch of queued faces)'); + console.log( + '[OO] font-load acceleration installed (no default-font preload, parallel prefetch, open NeedStyles clamp)', + ); } - return Boolean(fontWin.__ooFontLoadAccelerated); + // Ready for the poll to stop only once both the loader wrap and the + // CheckFontNeeds clamp are in place. Spreadsheet / PDF frames never grow a + // word-style DrawingDocument.CheckFontNeeds -- treat the clamp as satisfied + // there so the iframe poll does not spin forever. + const path = String(fontWin.location?.pathname ?? ''); + const clampOptional = /spreadsheeteditor|pdfeditor|celleditor/i.test(path); + const clampReady = Boolean(fontWin.__ooFontNeedStylesHooked) || clampOptional; + return Boolean(fontWin.__ooFontLoadAccelerated && clampReady); } diff --git a/lib/onlyoffice/guards/x2t-worker.ts b/lib/onlyoffice/guards/x2t-worker.ts index b95e2ad61..ea98d5537 100644 --- a/lib/onlyoffice/guards/x2t-worker.ts +++ b/lib/onlyoffice/guards/x2t-worker.ts @@ -54,6 +54,14 @@ const FONT_STYLE_SUFFIX: Record = { indexI: '_Italic', }; +/** NeedStyles face bits (same as AscFonts / font-loading guard 15c). */ +const FONT_FACE_NEED_BIT: Record = { + indexR: 1, + indexI: 2, + indexB: 4, + indexBI: 8, +}; + type FontSource = { fileName: string; url: string; bytes?: Uint8Array }; type MediaPayload = { bytes: Uint8Array; mime: string }; @@ -185,8 +193,13 @@ export function fontSources(win: FrameScope): FontSource[] { const base = loader.fontFilesPath || ''; const sources: FontSource[] = []; for (const info of infos) { - if (!info || !info.NeedStyles) continue; + const needStyles = Number(info?.NeedStyles); + if (!info || !needStyles) continue; for (const field of Object.keys(FONT_STYLE_SUFFIX)) { + const bit = FONT_FACE_NEED_BIT[field] ?? 0; + // Guard 15c clamps NeedStyles to used faces on open; without this bit + // check, conversion still pulled every indexR/I/B/BI file for the family. + if (!(needStyles & bit)) continue; const index = info[field]; if (typeof index !== 'number' || index === -1) continue; const file = loader.fontFiles[index]; diff --git a/lib/onlyoffice/iframe-guards.ts b/lib/onlyoffice/iframe-guards.ts index 7c8de3920..d790e5cb9 100644 --- a/lib/onlyoffice/iframe-guards.ts +++ b/lib/onlyoffice/iframe-guards.ts @@ -54,7 +54,7 @@ export function prepareEditorIframe(): boolean { const longActionGuarded = installLongActionLeakGuard(win); installSeriesSettingsGuard(win); - installFontLoadAcceleration(win); + const fontLoadAccelerated = installFontLoadAcceleration(win); installCommentSelectionGuard(win); installCanvasLossGuard(win, doc); installSingleUnloadPrompt(win); @@ -75,7 +75,11 @@ export function prepareEditorIframe(): boolean { longActionGuarded && x2tWorkerProxied && wasmBinaryHandled && - assistantFocusGuarded + assistantFocusGuarded && + // Font acceleration also attaches the NeedStyles clamp once + // DrawingDocument exists; stopping the poll before that leaves open + // on the unclamped path (NeedStyles 15 forever). + fontLoadAccelerated ) { fullyApplied = true; } diff --git a/test/e2e/embed-regression.spec.ts b/test/e2e/embed-regression.spec.ts index 5297382c1..1e2283901 100644 --- a/test/e2e/embed-regression.spec.ts +++ b/test/e2e/embed-regression.spec.ts @@ -1,5 +1,5 @@ import { expect, test } from './lib/l0'; -import { toBase64 } from './lib/ooxml'; +import { buildDocx, toBase64 } from './lib/ooxml'; import { buildPptx, buildXlsx } from './actions/fixtures'; import { waitForEditorReady, saveAndCapture, SAVE_FORMAT_CODE } from './actions/editor'; @@ -716,6 +716,51 @@ test.describe('embed regression (real editor)', () => { expect(stats.dispatchSpreadMs).toBeLessThan(1500); }); + test('open-time NeedStyles is clamped from Document_CreateFontMap (font-load 15c)', async ({ page, l0 }) => { + // Without the clamp, CheckFontNeeds builds CFont(name) so NeedStyles is + // always 15 and every face file of every family is queued. Reverse: disable + // installNeedStylesClamp / LoadDocumentFonts rewrite in font-loading.ts and + // this asserts __ooFontNeedStylesClamped false or Arial stays at 15. + l0.allowConsole(/font prefetch|font-load acceleration|NeedStyles clamp/); + const body = + '' + + 'Bold Arial' + + '' + + 'Regular Arial'; + await page.evaluate( + async ({ b64 }) => { + const bin = atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i); + await post('document:open-buffer', { fileName: 'need-styles.docx', buffer: arr.buffer, readonly: false }); + }, + { b64: toBase64(buildDocx('need styles', body)) }, + ); + const ready = await waitForEditorReady(page); + expect(ready.kind).toBe('word'); + + const stats = await page.evaluate(() => { + const win = window.__ooFrames.editor() as any; + if (!win) return { clamped: false, hooked: false, arial: null as number | null }; + const infos: Array<{ Name?: string; NeedStyles?: number }> = win.AscFonts?.g_font_infos || []; + const arial = infos.find((info) => info?.Name === 'Arial'); + return { + clamped: !!win.__ooFontNeedStylesClamped, + hooked: !!win.__ooFontNeedStylesHooked, + arial: typeof arial?.NeedStyles === 'number' ? arial.NeedStyles : null, + }; + }); + expect(stats.hooked).toBe(true); + expect(stats.clamped).toBe(true); + // CreateFontMap saw Regular + Bold; clamp also keeps Italic for chrome. + // Regular (1) | Italic (2) | Bold (4) = 7; must not stay at all-faces 15. + expect(stats.arial).not.toBeNull(); + expect(stats.arial! & 1).toBe(1); + expect(stats.arial! & 2).toBe(2); + expect(stats.arial! & 4).toBe(4); + expect(stats.arial).toBe(7); + }); + test('opens a PDF through the vendor pdf editor', async ({ page }) => { await page.evaluate(async () => { // Build a minimal but structurally valid single-page PDF, computing the diff --git a/test/unit/font-need-styles.test.ts b/test/unit/font-need-styles.test.ts new file mode 100644 index 000000000..ee7721bcb --- /dev/null +++ b/test/unit/font-need-styles.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import { + NEED_STYLE_ALL, + NEED_STYLE_B, + NEED_STYLE_BI, + NEED_STYLE_I, + NEED_STYLE_R, + clampNeedStylesForFamily, + needStylesByFamilyFromFontMap, + styleFlagToNeedStyles, +} from '../../lib/onlyoffice/guards/font-loading'; +import { fontSources } from '../../lib/onlyoffice/guards/x2t-worker'; + +describe('styleFlagToNeedStyles', () => { + it.each([ + [0, NEED_STYLE_R], + [1, NEED_STYLE_B], + [2, NEED_STYLE_I], + [3, NEED_STYLE_BI], + [4, NEED_STYLE_R], // & 3 → 0 + ])('maps CreateFontMap Style %s to NeedStyles %s', (style, need) => { + expect(styleFlagToNeedStyles(style)).toBe(need); + }); +}); + +describe('needStylesByFamilyFromFontMap', () => { + it('ORs run styles per family and always keeps Regular', () => { + const needs = needStylesByFamilyFromFontMap({ + Arial_0_11: { Name: 'Arial', Style: 0, Size: 11 }, + Arial_1_11: { Name: 'Arial', Style: 1, Size: 11 }, + 'Times New Roman_2_12': { Name: 'Times New Roman', Style: 2, Size: 12 }, + }); + expect(needs.Arial).toBe(NEED_STYLE_R | NEED_STYLE_B); + expect(needs['Times New Roman']).toBe(NEED_STYLE_R | NEED_STYLE_I); + }); + + it('treats theme-resolved name keys (value 1) as Regular-only', () => { + const needs = needStylesByFamilyFromFontMap({ + Calibri: 1, + '+mj-lt': 1, + }); + expect(needs.Calibri).toBe(NEED_STYLE_R); + expect(needs['+mj-lt']).toBeUndefined(); + }); +}); + +describe('clampNeedStylesForFamily', () => { + it('uses the known map entry when present and keeps Regular + Italic', () => { + expect(clampNeedStylesForFamily(NEED_STYLE_ALL, NEED_STYLE_R | NEED_STYLE_B)).toBe( + NEED_STYLE_R | NEED_STYLE_I | NEED_STYLE_B, + ); + }); + + it('keeps the vendor request for open-list extras not in CreateFontMap', () => { + expect(clampNeedStylesForFamily(NEED_STYLE_ALL, undefined)).toBe(NEED_STYLE_ALL); + expect(clampNeedStylesForFamily(undefined, undefined)).toBe(NEED_STYLE_ALL); + expect(clampNeedStylesForFamily(0, undefined)).toBe(NEED_STYLE_ALL); + }); +}); + +describe('fontSources honors NeedStyles face bits', () => { + function scope(needStyles: number) { + return { + location: { href: 'https://editor.test/web-apps/apps/documenteditor/main/index.html' }, + AscCommon: { + g_font_loader: { + fontFilesPath: '../../../../fonts/', + fontFiles: [{ Id: '010' }, { Id: '011' }, { Id: '012' }, { Id: '013' }], + }, + }, + AscFonts: { + g_font_infos: [ + { + Name: 'Arial', + NeedStyles: needStyles, + indexR: 0, + indexI: 1, + indexB: 2, + indexBI: 3, + }, + ], + }, + } as unknown as Parameters[0]; + } + + it('emits every face when NeedStyles is 15', () => { + expect(fontSources(scope(NEED_STYLE_ALL)).map((s) => s.fileName)).toEqual([ + 'Arial.ttf', + 'Arial_Bold.ttf', + 'Arial_Bold_Italic.ttf', + 'Arial_Italic.ttf', + ]); + }); + + it('emits only Regular when NeedStyles is 1', () => { + expect(fontSources(scope(NEED_STYLE_R)).map((s) => s.fileName)).toEqual(['Arial.ttf']); + }); + + it('emits Regular + Bold when NeedStyles is R|B', () => { + expect(fontSources(scope(NEED_STYLE_R | NEED_STYLE_B)).map((s) => s.fileName)).toEqual([ + 'Arial.ttf', + 'Arial_Bold.ttf', + ]); + }); +});