cjkFontRuntime.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { readBinary, readText } from "#ui/assets.ts";
  2. import {
  3. CJK_UNICODE_RANGE,
  4. FALLBACK_FAMILY,
  5. FALLBACK_MANIFEST,
  6. LOCAL_FONTS,
  7. cjkFamilies,
  8. familyOf,
  9. withCjkFamilies,
  10. type FaceKey,
  11. type PdfFontLike,
  12. } from "#ui/cjkFonts.ts";
  13. /**
  14. * Registers the `zcode-cjk-*` faces and the bundled fallback for the PDF canvas. scripts/build.mjs
  15. * patches pdf.js so the canvas asks `pdfTypeface` for every font it sets.
  16. */
  17. let prepared: Promise<void> | undefined;
  18. let fallbackReady = false;
  19. /**
  20. * Look up the installed fonts behind every `zcode-cjk-*` face (local() only, nothing is
  21. * downloaded); with no CJK font installed at all, load the bundled fallback instead. Runs before a
  22. * PDF opens: the canvas never waits for a font, so every face must be ready before the first page
  23. * is drawn.
  24. */
  25. export function prepareCjkFonts(): Promise<void> {
  26. return (prepared ??= (async () => {
  27. const found = await Promise.all(
  28. Object.entries(LOCAL_FONTS).map(async ([key, names]) => {
  29. const face = new FontFace(
  30. familyOf(key as FaceKey),
  31. names.map((name) => `local("${name}")`).join(", "),
  32. { unicodeRange: CJK_UNICODE_RANGE },
  33. );
  34. try {
  35. await face.load();
  36. document.fonts.add(face);
  37. return true;
  38. } catch {
  39. return false;
  40. }
  41. }),
  42. );
  43. // 在首次绘制前决定并加载兜底字体:画布不会等字体,事后加载就得重画页面。
  44. if (!found.some(Boolean)) fallbackReady = await loadFallback();
  45. })());
  46. }
  47. /** Register the bundled Noto Sans SC slices as `zcode-cjk-fallback`; false when that failed. */
  48. async function loadFallback(): Promise<boolean> {
  49. try {
  50. const manifest = JSON.parse(await readText(FALLBACK_MANIFEST)) as {
  51. faces: { file: string; unicodeRange: string }[];
  52. };
  53. await Promise.all(
  54. manifest.faces.map(async ({ file, unicodeRange }) => {
  55. const face = new FontFace(FALLBACK_FAMILY, await readBinary(file), { unicodeRange });
  56. await face.load();
  57. document.fonts.add(face);
  58. }),
  59. );
  60. return true;
  61. } catch (error) {
  62. console.warn("CJK fallback font", error);
  63. return false;
  64. }
  65. }
  66. /**
  67. * The CSS font-family list for a font the PDF canvas sets. `css` is pdf.js's own list; fonts pdf.js
  68. * has no file for get the `zcode-cjk-*` faces before its generic family.
  69. */
  70. export function pdfTypeface(font: PdfFontLike, css: string): string {
  71. return withCjkFamilies(css, cjkFamilies(font, fallbackReady));
  72. }