返回 presentation-ai
utils.ts
根目录 / src / components / ui / font-picker / utils / utils.ts
1 import { type Font, type FourFonts, type Variant } from "../types";
2
3 // Helper to get the sprite number for a given font index
4 export function getSpriteNumber(index: number): number {
5 return Math.floor(index / 200) + 1;
6 }
7
8 export const getFourVariants = (variants: string[]) => {
9 const regularWeights = variants
10 .filter((v: string) => v.substring(0, 2) === "0,")
11 .map((v: string) => parseInt(v.substring(2), 10))
12 .sort((a, b) => a - b);
13 const italicWeights = variants
14 .filter((v: string) => v.substring(0, 2) === "1,")
15 .map((v: string) => parseInt(v.substring(2), 10))
16 .sort((a, b) => a - b);
17
18 const fourFonts: FourFonts = {};
19 fourFonts.regular = regularWeights
20 .sort((a, b) => Math.abs(399 - a) - Math.abs(399 - b))
21 .shift();
22 fourFonts.bold = regularWeights
23 .filter((v) => v > (fourFonts.regular || 0))
24 .sort((a, b) => Math.abs(700 - a) - Math.abs(700 - b))
25 .shift();
26 fourFonts.italic = italicWeights
27 .sort((a, b) => Math.abs(399 - a) - Math.abs(399 - b))
28 .shift();
29 fourFonts.boldItalic = italicWeights
30 .filter((v) => v > (fourFonts.italic || 0))
31 .sort((a, b) => Math.abs(700 - a) - Math.abs(700 - b))
32 .shift();
33
34 const fourVariants: string[] = [];
35 if (fourFonts.regular) {
36 fourVariants.push("0," + fourFonts.regular);
37 }
38 if (fourFonts.bold) {
39 fourVariants.push("0," + fourFonts.bold);
40 }
41 if (fourFonts.italic) {
42 fourVariants.push("1," + fourFonts.italic);
43 }
44 if (fourFonts.boldItalic) {
45 fourVariants.push("1," + fourFonts.boldItalic);
46 }
47 return fourVariants;
48 };
49
50 export const loadFontFromObject = (
51 font: Font,
52 loadAllVariants: boolean,
53 getFourVariants: (variants: string[]) => string[],
54 variants: Variant[] = [],
55 ) => {
56 if (font?.isLocal) {
57 return;
58 }
59 if (variants?.length > 0) {
60 variants = font.variants.filter((v: Variant) => variants.includes(v));
61 } else if (loadAllVariants) {
62 variants = font.variants;
63 } else {
64 variants = getFourVariants(font.variants.map((v) => v.toString()));
65 }
66
67 let cssId = "google-font-" + font.sane;
68 const cssIdAll = cssId + "-all";
69 if (variants.length === font.variants.length) {
70 cssId = cssIdAll;
71 } else {
72 cssId +=
73 "-" +
74 variants.sort().join("-").replaceAll("1,", "i").replaceAll("0,", "");
75 }
76
77 const existing = document.getElementById(cssId);
78 const existingAll = document.getElementById(cssIdAll);
79 if (!existing && !existingAll && font?.name && variants?.length > 0) {
80 const link = document.createElement("link");
81 link.rel = "stylesheet";
82 link.id = cssId;
83 link.href =
84 "https://fonts.googleapis.com/css2?family=" +
85 font.name +
86 ":ital,wght@" +
87 variants.sort().join(";") +
88 "&display=swap";
89 link.setAttribute("data-testid", cssId);
90 document.head.appendChild(link);
91 }
92 };
93
93 lines TYPESCRIPT