Skip to content

Commit a2da99d

Browse files
committed
Fix the font loading behaviour
1 parent 0634a1a commit a2da99d

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

packages/replicad/src/text.ts

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,30 @@ const FONT_REGISTER: Record<string, opentype.Font> = {};
1414
*
1515
* The font should be in TTF
1616
*/
17-
export const loadFont = async (fontPath: string, fontFamily = "default") => {
18-
// @ts-expect-error missing info in the types
19-
const font: opentype.Font = await opentype.load(fontPath, null, {
20-
isUrl: true,
21-
});
17+
export async function loadFont(
18+
fontPath: string | ArrayBuffer,
19+
fontFamily = "default",
20+
force = false
21+
) {
22+
if (!force && FONT_REGISTER[fontFamily]) {
23+
console.log(`Font ${fontFamily} already loaded`);
24+
return FONT_REGISTER[fontFamily];
25+
}
26+
27+
let fontData: ArrayBuffer;
28+
if (typeof fontPath === "string") {
29+
const response = await fetch(fontPath);
30+
fontData = await response.arrayBuffer();
31+
} else {
32+
fontData = fontPath;
33+
}
34+
35+
const font: opentype.Font = opentype.parse(fontData);
2236
FONT_REGISTER[fontFamily] = font;
2337
if (!FONT_REGISTER.default) FONT_REGISTER.default = font;
2438

2539
return font;
26-
};
40+
}
2741

2842
export const getFont = (fontFamily = "default") => {
2943
return FONT_REGISTER[fontFamily];
@@ -88,7 +102,13 @@ export function textBlueprints(
88102
text: string,
89103
{ startX = 0, startY = 0, fontSize = 16, fontFamily = "default" } = {}
90104
): Blueprints {
91-
const font = getFont(fontFamily);
105+
let font = getFont(fontFamily);
106+
if (!font) {
107+
console.warn(
108+
`Font family "${fontFamily}" not found, please load it first, using the default`
109+
);
110+
font = getFont();
111+
}
92112
const writtenText = font.getPath(text, -startX, -startY, fontSize);
93113
const blueprints = Array.from(sketchFontCommands(writtenText.commands));
94114
return organiseBlueprints(blueprints).mirror([0, 0]);

0 commit comments

Comments
 (0)