Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: fix font support detection (#6607)

wpxp123456a3ad609d79ab
diff --git a/packages/ui/src/services/__tests__/font.spec.ts b/packages/ui/src/services/__tests__/font.spec.ts
index ada474c23f..78c24b9a52 100644
--- a/packages/ui/src/services/__tests__/font.spec.ts
+++ b/packages/ui/src/services/__tests__/font.spec.ts
@@ -129,32 +129,4 @@ describe('FontService', () => {
expect(fontService.getFontByValue('Arial')).toBeDefined();
expect(fontService.getFonts()).toHaveLength(13);
});
-
- it('should check if font is supported', () => {
- vi.mocked(configService.getConfig).mockReturnValue(undefined);
- fontService = injector.get(FontService);
-
- const mockContext = {
- measureText: vi.fn(),
- font: '',
- };
- const mockCanvas = {
- getContext: vi.fn(() => mockContext),
- };
- vi.spyOn(document, 'createElement').mockReturnValue(mockCanvas as any);
-
- // Test supported: different widths
- mockContext.measureText
- .mockReturnValueOnce({ width: 10 } as any) // baseline
- .mockReturnValueOnce({ width: 20 } as any); // new font
-
- expect(fontService.isFontSupported('SupportedFont')).toBe(true);
-
- // Test unsupported: same widths
- mockContext.measureText
- .mockReturnValueOnce({ width: 10 } as any) // baseline
- .mockReturnValueOnce({ width: 10 } as any); // new font (fallback)
-
- expect(fontService.isFontSupported('UnsupportedFont')).toBe(false);
- });
});
diff --git a/packages/ui/src/services/font.service.ts b/packages/ui/src/services/font.service.ts
index e0b9f528fe..d7f38c57cb 100644
--- a/packages/ui/src/services/font.service.ts
+++ b/packages/ui/src/services/font.service.ts
@@ -198,18 +198,24 @@ export class FontService implements IFontService, IDisposable {
isFontSupported(fontValue: string): boolean {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
- if (!context) {
- return false;
- }
+ if (!context) return false;
+
+ const text = 'abcdefghijklmnopqrstuvwxyz0123456789';
+ const size = '72px';
- const testString = 'abcdefghijklmnopqrstuvwxyz0123456789';
- context.font = '12px monospace';
- const baselineWidth = context.measureText(testString).width;
+ const baseFonts = ['monospace', 'serif', 'sans-serif'];
+ const defaultWidths: Record<string, number> = {};
- context.font = `12px "${fontValue}", monospace`;
- const newWidth = context.measureText(testString).width;
+ baseFonts.forEach((base) => {
+ context.font = `${size} ${base}`;
+ defaultWidths[base] = context.measureText(text).width;
+ });
- return newWidth !== baselineWidth;
+ return baseFonts.some((base) => {
+ context.font = `${size} "${fontValue}", ${base}`;
+ const width = context.measureText(text).width;
+ return width !== defaultWidths[base];
+ });
}
addFont(font: IFontConfig): void {