fontFaces.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * 字体面注入 —— 规格 11 授权门禁在浏览器里的落点。
  3. *
  4. * 为什么是运行时注入而不是静态 @font-face 写进 tokens.css:
  5. * 静态声明只能表达「有一个字体名字」,无法承载授权门禁。这里逐条向
  6. * `resolveFont(key)` 要结果,**门禁不通过的字体根本不会生成 @font-face 规则**,
  7. * 于是「无证据字体不可被解析为运行时字体」不是靠约定,而是结构上做不到——
  8. * 没有 @font-face 就没有这个字族可用,浏览器只能落到系统回退链。
  9. *
  10. * 路径由统一资产解析层拼(含 BASE_URL / qiankun 注入路径),本模块不拼路径。
  11. */
  12. import { resolveFont } from './runtimeAssets.js'
  13. /** 需要注入的字体条目(语义 key)。与 runtimeAssets.FONT_SLOTS 的消费点一一对应。 */
  14. const FONT_FACE_KEYS = [
  15. 'font.body.regular',
  16. 'font.body.bold',
  17. 'font.num.regular',
  18. 'font.num.bold',
  19. 'font.num.mono',
  20. // 票 17 第七轮:'font.title' 已撤销(无界黑无消费点,见 runtimeAssets.FONT_SLOTS 注释)。
  21. ]
  22. const STYLE_ID = 'cockpit-font-faces'
  23. /** 生成 @font-face 规则文本。纯函数:输入已解析的字体描述,输出 CSS 文本,便于自查脚本复算。 */
  24. export function buildFontFaceCss(descriptors) {
  25. return descriptors
  26. .filter((d) => d.available && d.url)
  27. .map((d) => [
  28. '@font-face {',
  29. ` font-family: "${d.family}";`,
  30. ` font-style: ${d.style};`,
  31. ` font-weight: ${d.weight};`,
  32. ` font-display: swap;`, // 首屏不被字体阻塞:先用回退字体渲染,字体到位再换
  33. ` src: url("${d.url}") format("${d.format || 'woff2'}");`,
  34. '}',
  35. ].join('\n'))
  36. .join('\n')
  37. }
  38. /** 收集门禁通过的字体描述(不可用的被过滤掉——这正是门禁的可见后果)。 */
  39. export function fontFaceDescriptors(options = {}) {
  40. return FONT_FACE_KEYS.map((key) => resolveFont(key, options))
  41. }
  42. /**
  43. * 注入字体面。幂等:同一文档重复调用只保留一份 style 节点。
  44. * 返回注入的描述列表,供宿主 data-* 读数与走查断言。
  45. */
  46. export function installFontFaces(options = {}) {
  47. const descriptors = fontFaceDescriptors(options)
  48. const css = buildFontFaceCss(descriptors)
  49. if (typeof document === 'undefined') return descriptors
  50. let node = document.getElementById(STYLE_ID)
  51. if (!node) {
  52. node = document.createElement('style')
  53. node.id = STYLE_ID
  54. document.head.appendChild(node)
  55. }
  56. node.textContent = css
  57. node.dataset.fontFaces = String(descriptors.filter((d) => d.available).length)
  58. return descriptors
  59. }