fix(sdk): 字体加载失败重试与状态恢复加固

This commit is contained in:
崮生(子虚) 2026-11-04 19:07:28 +08:00
parent 61c1f56aac
commit d6a6b5feac
2 changed files with 53 additions and 12 deletions

View File

@ -119,17 +119,39 @@ export class WebFontCSSMode {
list.push(style)
this.injectedStyles.set(key, list)
/** 注入后等待字体真正可用于渲染,让 document.fonts 状态机推进(无 API 时定时器兑底) */
this.waitFontLoaded(family)
this.waitFontLoaded(key, family, style)
}
}
/** 用 document.fonts.load 触发加载与就绪状态推进(无 API 时定时器兑底) */
private waitFontLoaded(family: string): void {
if (document.fonts && document.fonts.load) {
void document.fonts.load(`16px "${family}"`)
} else {
setTimeout(() => {}, 3000)
}
/**
* 用 document.fonts.load 触发加载与就绪状态推进。
* 浏览器 fetch 字体文件瞬时失败(网络/代理抖动)时 @font-face 会静默 fallback 且不会自愈,
* 检测到该 face 处于 error 状态则重建 style 触发浏览器重新拉取(每个 face 至多重试一次)
*/
private waitFontLoaded(key: string, family: string, style: HTMLStyleElement): void {
if (!(document.fonts && document.fonts.load)) return
void document.fonts.load(`16px "${family}"`).then(() => {
/** 同名 family 可能有多个 face(多 chunk),只要有 error 就重试本 chunk 这一份 */
const failed = [...document.fonts].some(
(f) => f.status === 'error' && f.family.replace(/"/g, '') === family,
)
if (!failed || style.dataset.webfontRetried) return
style.dataset.webfontRetried = '1'
setTimeout(() => {
if (!style.isConnected) return // 该字体已 dispose
const retry = document.createElement('style')
retry.textContent = style.textContent
retry.dataset.webfontRetried = '1'
style.remove()
document.head.appendChild(retry)
const list = this.injectedStyles.get(key)
if (list) {
const i = list.indexOf(style)
if (i >= 0) list[i] = retry
}
void document.fonts.load(`16px "${family}"`)
}, 1200)
})
}
private resolveDefaults(options: IWebFontOptions): { baseUrl: string; family: string; key: string } {

View File

@ -8,6 +8,28 @@
import { IncrementalEngine, createHttpProvider, type SubsetProvider, type LoadedChunk, type IFontState } from './engine'
import { NodeFontRegistry, loadGlobalFonts, isNodeEnvironment } from './node-registry'
/**
* fetch 字体 buffer 并注册 FontFace;网络/代理瞬时抖动导致 fetch 或解码失败时自动重试一次
* (@font-face 依赖浏览器 fetch 无重试会静默 fallback,这里由 SDK 显式控制重试)
*/
async function loadFaceWithRetry(url: string, family: string, unicodeRange: string): Promise<FontFace> {
let lastErr: unknown
for (let attempt = 0; attempt < 2; attempt++) {
try {
const res = await fetch(url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const buffer = await res.arrayBuffer()
const face = new FontFace(family, buffer, { unicodeRange })
await face.load()
return face
} catch (err) {
lastErr = err
await new Promise((r) => setTimeout(r, 1200))
}
}
throw lastErr
}
export interface IFontFaceOptions {
/** 字体文件名(如 '令东齐伋复刻体.ttf'),支持模糊匹配 */
fontName: string
@ -88,10 +110,7 @@ export class WebFontFontFaceMode {
const unicodeRanges = chunk.chars
.map((c) => 'U+' + c.codePointAt(0)!.toString(16).padStart(4, '0'))
.join(', ')
const res = await fetch(chunk.url)
const buffer = await res.arrayBuffer()
const face = new FontFace(family, buffer, { unicodeRange: unicodeRanges })
await face.load()
const face = await loadFaceWithRetry(chunk.url, family, unicodeRanges)
document.fonts.add(face)
const list = this.faces.get(family) ?? []
list.push(face)