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.

feat(ui): allow overriding custom fonts in configuration (#6375)

白熱c3d75e36f596
diff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png
index c2211e199c..21b8448f5e 100644
Binary files a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png and b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png differ
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 7c78d92109..c2829409c4 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -125,10 +125,13 @@ function createNewInstance() {
[UniverUIPlugin, {
container: 'app',
// ribbonType: 'classic',
- customFontFamily: [
- { value: 'PingFang SC', label: '苹方(简)', category: 'sans-serif' },
- { value: 'Helvetica Neue', label: 'Helvetica Neue', category: 'sans-serif' },
- ],
+ customFontFamily: {
+ list: [
+ { value: 'PingFang SC', label: '苹方(简)', category: 'sans-serif' },
+ { value: 'Helvetica Neue', label: 'Helvetica Neue', category: 'sans-serif' },
+ ],
+ // override: true,
+ },
}],
[UniverWebComponentAdapterPlugin],
[UniverVue3AdapterPlugin],
diff --git a/packages/ui/src/controllers/config.schema.ts b/packages/ui/src/controllers/config.schema.ts
index 5f70ca37d9..44f2de49a9 100644
--- a/packages/ui/src/controllers/config.schema.ts
+++ b/packages/ui/src/controllers/config.schema.ts
@@ -15,7 +15,6 @@
*/
import type { DependencyOverride } from '@univerjs/core';
-import type { IFontConfig } from '../services/font.service';
import type { MenuConfig } from '../services/menu/menu';
import type { IWorkbenchOptions } from './ui/ui.controller';
@@ -31,11 +30,6 @@ export interface IUniverUIConfig extends IWorkbenchOptions {
menu?: MenuConfig;
- /**
- * Custom font family list to be added to the font service.
- */
- customFontFamily?: IFontConfig[];
-
popupRootId?: string;
/**
diff --git a/packages/ui/src/controllers/ui/ui.controller.ts b/packages/ui/src/controllers/ui/ui.controller.ts
index 32fa654cf8..6830246e2f 100644
--- a/packages/ui/src/controllers/ui/ui.controller.ts
+++ b/packages/ui/src/controllers/ui/ui.controller.ts
@@ -40,7 +40,10 @@ export interface IWorkbenchOptions {
/**
* Custom font family list to be added to the font service.
*/
- customFontFamily?: IFontConfig[];
+ customFontFamily?: IFontConfig[] | {
+ override?: boolean;
+ list: IFontConfig[];
+ };
/**
* If Univer should make the footer bar visible.
diff --git a/packages/ui/src/facade/f-univer.ts b/packages/ui/src/facade/f-univer.ts
index 183e518403..75af40604b 100644
--- a/packages/ui/src/facade/f-univer.ts
+++ b/packages/ui/src/facade/f-univer.ts
@@ -533,10 +533,7 @@ export class FUniverUIMixin extends FUniver implements IFUniverUIMixin {
override addFonts(fonts: IFontConfig[]): void {
const fontService = this._injector.get(IFontService);
fonts.forEach((font) => {
- fontService.addFont({
- ...font,
- isCustom: true,
- });
+ fontService.addFont(font);
});
}
}
diff --git a/packages/ui/src/services/__tests__/font.spec.ts b/packages/ui/src/services/__tests__/font.spec.ts
new file mode 100644
index 0000000000..ada474c23f
--- /dev/null
+++ b/packages/ui/src/services/__tests__/font.spec.ts
@@ -0,0 +1,160 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { IConfigService, Injector } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { FontService } from '../font.service';
+
+describe('FontService', () => {
+ let injector: Injector;
+ let fontService: FontService;
+ let configService: IConfigService;
+
+ beforeEach(() => {
+ injector = new Injector();
+ configService = {
+ getConfig: vi.fn(),
+ } as unknown as IConfigService;
+
+ injector.add([IConfigService, { useValue: configService }]);
+ injector.add([FontService]);
+ });
+
+ it('should initialize with default fonts when no config is provided', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ const fonts = fontService.getFonts();
+ expect(fonts.length).toBe(13);
+ expect(fonts.find((f) => f.value === 'Arial')).toBeDefined();
+ });
+
+ it('should initialize with custom fonts (array)', () => {
+ const customFonts = [{ value: 'Custom', label: 'Custom Font' }];
+ vi.mocked(configService.getConfig).mockReturnValue({
+ customFontFamily: customFonts,
+ });
+ fontService = injector.get(FontService);
+ const fonts = fontService.getFonts();
+ expect(fonts).toHaveLength(14); // Default (13) + Custom (1)
+ expect(fonts.find((f) => f.value === 'Custom')).toBeDefined();
+ });
+
+ it('should initialize with custom fonts (override)', () => {
+ const customFonts = {
+ override: true,
+ list: [{ value: 'Custom', label: 'Custom Font' }],
+ };
+ vi.mocked(configService.getConfig).mockReturnValue({
+ customFontFamily: customFonts,
+ });
+ fontService = injector.get(FontService);
+ const fonts = fontService.getFonts();
+ expect(fonts).toHaveLength(1);
+ expect(fonts[0].value).toBe('Custom');
+ });
+
+ it('should initialize with custom fonts (append)', () => {
+ const customFonts = {
+ override: false,
+ list: [{ value: 'Custom', label: 'Custom Font' }],
+ };
+ vi.mocked(configService.getConfig).mockReturnValue({
+ customFontFamily: customFonts,
+ });
+ fontService = injector.get(FontService);
+ const fonts = fontService.getFonts();
+ expect(fonts).toHaveLength(14);
+ expect(fonts.find((f) => f.value === 'Custom')).toBeDefined();
+ expect(fonts.find((f) => f.value === 'Arial')).toBeDefined();
+ });
+
+ it('should add a font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ const newFont = { value: 'New', label: 'New Font' };
+ fontService.addFont(newFont);
+ expect(fontService.getFontByValue('New')).toEqual(newFont);
+ });
+
+ it('should throw error when adding existing font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ expect(() => fontService.addFont({ value: 'Arial', label: 'Arial' })).toThrow();
+ });
+
+ it('should update a font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ fontService.updateFont('Arial', { label: 'New Arial' });
+ expect(fontService.getFontByValue('Arial')?.label).toBe('New Arial');
+ });
+
+ it('should throw error when updating non-existing font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ expect(() => fontService.updateFont('NotExist', { label: 'New' })).toThrow();
+ });
+
+ it('should remove a font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ expect(fontService.removeFont('Arial')).toBe(true);
+ expect(fontService.getFontByValue('Arial')).toBeUndefined();
+ });
+
+ it('should return false when removing non-existing font', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ expect(fontService.removeFont('NotExist')).toBe(false);
+ });
+
+ it('should reset to defaults', () => {
+ vi.mocked(configService.getConfig).mockReturnValue(undefined);
+ fontService = injector.get(FontService);
+ fontService.removeFont('Arial');
+ fontService.resetToDefaults();
+ 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 c44ad13ea0..e0b9f528fe 100644
--- a/packages/ui/src/services/font.service.ts
+++ b/packages/ui/src/services/font.service.ts
@@ -42,12 +42,6 @@ export interface IFontConfig {
* Font category for UI grouping (optional)
*/
category?: 'sans-serif' | 'serif' | 'monospace' | 'display' | 'handwriting';
-
- /**
- * Mark whether the font is user-added
- * (Used to distinguish built-in fonts to prevent accidental deletion of core fonts)
- */
- isCustom?: boolean;
}
const DEFAULT_FONT_LIST: IFontConfig[] = [{
@@ -159,17 +153,28 @@ export interface IFontService {
}
export class FontService implements IFontService, IDisposable {
- readonly fonts$: BehaviorSubject<IFontConfig[]> = new BehaviorSubject<IFontConfig[]>([...DEFAULT_FONT_LIST]);
+ readonly fonts$: BehaviorSubject<IFontConfig[]> = new BehaviorSubject<IFontConfig[]>([]);
constructor(@IConfigService protected readonly _configService: IConfigService) {
+ // Initialize font list from configuration
const config = this._configService.getConfig<IUniverUIConfig>(UI_PLUGIN_CONFIG_KEY);
- const { customFontFamily = [] } = config ?? {};
- if (customFontFamily.length) {
- customFontFamily.forEach((font) => this.addFont({
- ...font,
- isCustom: true,
- }));
+ const { customFontFamily } = config ?? {};
+
+ let fonts: IFontConfig[] = [];
+
+ if (customFontFamily) {
+ if (Array.isArray(customFontFamily)) {
+ fonts = [...DEFAULT_FONT_LIST, ...customFontFamily];
+ } else if (customFontFamily.override) {
+ fonts = [...customFontFamily.list];
+ } else {
+ fonts = [...DEFAULT_FONT_LIST, ...customFontFamily.list];
+ }
+ } else {
+ fonts = [...DEFAULT_FONT_LIST];
}
+
+ this.fonts$.next(fonts);
}
dispose() {
@@ -238,12 +243,6 @@ export class FontService implements IFontService, IDisposable {
return false;
}
- const fontToRemove = fonts[fontIndex];
- if (!fontToRemove.isCustom) {
- // Prevent removal of built-in fonts
- return false;
- }
-
const updatedFonts = fonts.filter((font) => font.value !== value);
this.fonts$.next(updatedFonts);
return true;