fix(2d): preserve simple font aliases in canvas descriptors (#428)

* fix(2d): preserve simple font aliases in canvas descriptors

Use bare identifiers for simple generated _LABEL aliases in Label rendering and Web font loading. Keep quoting and escaping complex family names, and preserve system font expressions.

* test(2d): cover font aliases from Web registration to Label descriptors
This commit is contained in:
ChiaNing
2026-11-18 18:37:21 +08:00
committed by GitHub
parent af2b9e9ed9
commit 7995924100
4 changed files with 53 additions and 18 deletions
+7 -1
View File
@@ -45,6 +45,12 @@ export function quoteFontFamily (name: string): CssFontFamily {
return `${result}"` as CssFontFamily;
}
/** A simple generated alias is already a CSS identifier and cannot be a reserved family keyword. */
export function serializeFontFamily (name: string): CssFontFamily {
// Some Canvas implementations only recognize the bare alias registered by the font loader.
return /^[A-Za-z_][A-Za-z0-9_-]*_LABEL$/.test(name) ? name as CssFontFamily : quoteFontFamily(name);
}
interface FontFamilySource {
readonly useSystemFont: boolean;
readonly fontFamily: string;
@@ -56,7 +62,7 @@ export function getCanvasFontFamily (source: FontFamilySource): CssFontFamily {
const system = source.useSystemFont;
const value = system ? source.fontFamily : source.font?._nativeAsset;
const name = typeof value === 'string' && value ? value : DEFAULT_FONT_FAMILY;
return system ? name as CssFontFamily : quoteFontFamily(name);
return system ? name as CssFontFamily : serializeFontFamily(name);
}
/** Family is already serialized: changing size or style must never quote it again. */
+2 -2
View File
@@ -23,7 +23,7 @@
*/
import { warnID } from '../../core';
import { buildFontDesc, quoteFontFamily } from './font-family';
import { buildFontDesc, serializeFontFamily } from './font-family';
import downloader from '../../asset/asset-manager/downloader';
import factory from '../../asset/asset-manager/factory';
import { TTFFont } from '../assets/ttf-font';
@@ -169,7 +169,7 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
}
// Default width reference to test whether new font is loaded correctly
const familyCss = quoteFontFamily(fontFamilyName);
const familyCss = serializeFontFamily(fontFamilyName);
const fontDesc = buildFontDesc(40, familyCss);
// Setup font face style
+17 -7
View File
@@ -1,4 +1,4 @@
import { buildFontDesc, CssFontFamily, getCanvasFontFamily, quoteFontFamily } from '../../cocos/2d/utils/font-family';
import { buildFontDesc, CssFontFamily, getCanvasFontFamily, quoteFontFamily, serializeFontFamily } from '../../cocos/2d/utils/font-family';
import { TTFFont } from '../../cocos/2d/assets/ttf-font';
import type { Label } from '../../cocos/2d/components/label';
import { TTFUtils } from '../../cocos/2d/assembler/label/ttfUtils';
@@ -57,13 +57,13 @@ describe('font family serialization', () => {
const descriptions = rawAliases.map((rawAlias) => {
const source = { useSystemFont: false, fontFamily: 'Arial', font: { _nativeAsset: rawAlias } };
// A migrated manual caller uses the original registered alias, not its old ctx.font text.
const migrated = buildFontDesc(40, quoteFontFamily(rawAlias));
const migrated = buildFontDesc(40, serializeFontFamily(rawAlias));
expect(migrated).toBe(buildFontDesc(40, getCanvasFontFamily(source)));
expect(source.font._nativeAsset).toBe(rawAlias);
return migrated;
});
expect(descriptions).toEqual([
'40px "Example_LABEL"',
'40px Example_LABEL',
'40px "\\"Example_LABEL\\""',
'40px "\\"My Font_LABEL\\""',
]);
@@ -84,15 +84,25 @@ describe('Label font consumers', () => {
}
}
test('TTF and CHAR resolve the same raw asset without modifying it', () => {
test.each([
['KenneyPixel_LABEL', 'KenneyPixel_LABEL'],
['AlibabaPuHuiTi-3-105-Heavy_LABEL', 'AlibabaPuHuiTi-3-105-Heavy_LABEL'],
['sans-serif_LABEL', 'sans-serif_LABEL'],
['中文字体_LABEL', '"中文字体_LABEL"'],
['阿里普惠体-Heavy_LABEL', '"阿里普惠体-Heavy_LABEL"'],
['Alibaba PuHuiTi 3.0 105 Heavy', '"Alibaba PuHuiTi 3.0 105 Heavy"'],
['3Font_LABEL', '"3Font_LABEL"'],
['Font.3_LABEL', '"Font.3_LABEL"'],
['A,B_LABEL', '"A,B_LABEL"'],
])('TTF and CHAR select the family for %p without modifying the asset', (raw, expected) => {
const font = new TTFFont();
font._nativeAsset = 'Alibaba PuHuiTi 3.0 105 Heavy';
font._nativeAsset = raw;
const label = { font, useSystemFont: false, fontFamily: 'Arial' } as unknown as Label;
const ttf = new TTFUtils();
const char = new ExposedLetterFont();
expect(ttf._updateFontFamily(label)).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"');
expect(ttf._updateFontFamily(label)).toBe(expected);
expect(char.familyFor(label)).toBe(ttf._updateFontFamily(label));
expect(font._nativeAsset).toBe('Alibaba PuHuiTi 3.0 105 Heavy');
expect(font._nativeAsset).toBe(raw);
});
test('Web EditBox applies a custom family as CSS and preserves system lists', () => {
+27 -8
View File
@@ -1,4 +1,9 @@
import { TTFFont } from '../../cocos/2d/assets/ttf-font';
import { TTFUtils } from '../../cocos/2d/assembler/label/ttfUtils';
import type { Label } from '../../cocos/2d/components/label';
import { buildFontDesc } from '../../cocos/2d/utils/font-family';
import { getFontFamily, loadFont } from '../../cocos/2d/utils/font-loader';
import factory from '../../cocos/asset/asset-manager/factory';
test.each([
['fonts/Alibaba PuHuiTi 3.0.ttf', 'Alibaba PuHuiTi 3.0_LABEL'],
@@ -8,7 +13,14 @@ test.each([
expect(getFontFamily(url)).toBe(expected);
});
test('Web registration and FontFaceSet loading share one CSS family and return a raw alias', async () => {
test.each([
// URL, raw asset alias, expected CSS family for registration and drawing.
['fonts/Web Family 3.0.ttf', 'Web Family 3.0_LABEL', '"Web Family 3.0_LABEL"'],
['fonts/KenneyPixel.ttf', 'KenneyPixel_LABEL', 'KenneyPixel_LABEL'],
['fonts/sans-serif.ttf', 'sans-serif_LABEL', 'sans-serif_LABEL'],
['fonts/My Font.ttf', 'My Font_LABEL', '"My Font_LABEL"'],
['fonts/中文字体.ttf', '中文字体_LABEL', '"中文字体_LABEL"'],
])('Web registration, font loading and the TTF Label descriptor agree for %s', async (url, alias, familyCss) => {
jest.useFakeTimers();
const faceDescriptor = Object.getOwnPropertyDescriptor(window, 'FontFace');
const fontsDescriptor = Object.getOwnPropertyDescriptor(document, 'fonts');
@@ -28,23 +40,30 @@ test('Web registration and FontFaceSet loading share one CSS family and return a
}) as typeof document.createElement);
try {
await new Promise<void>((resolve, reject) => {
loadFont('fonts/Web Family 3.0.ttf', {}, (error, family) => {
const font = await new Promise<TTFFont>((resolve, reject) => {
loadFont(url, {}, (error, family) => {
if (error) {
reject(error);
return;
}
callback(family);
resolve();
factory.create(url, family, '.ttf', { cacheAsset: false }, (err, asset) => {
if (err) reject(err);
else if (asset instanceof TTFFont) resolve(asset);
else reject(new Error('Expected the font factory to return a TTFFont'));
});
});
});
const style = nodes.find((node) => node.tagName === 'STYLE')!;
const preload = nodes.find((node) => node.tagName === 'DIV')!;
expect(style.textContent).toBe('@font-face { font-family:"Web Family 3.0_LABEL"; src:url("fonts/Web Family 3.0.ttf");}');
expect(preload.style.fontFamily).toBe('"Web Family 3.0_LABEL"');
expect(load).toHaveBeenCalledWith('40px "Web Family 3.0_LABEL"');
expect(style.textContent).toBe(`@font-face { font-family:${familyCss}; src:url("${url}");}`);
expect(preload.style.fontFamily).toBe(familyCss);
expect(load).toHaveBeenCalledWith(`40px ${familyCss}`);
expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith('Web Family 3.0_LABEL');
expect(callback).toHaveBeenCalledWith(alias);
expect(font._nativeAsset).toBe(alias);
const label: Pick<Label, 'font' | 'useSystemFont' | 'fontFamily'> = { font, useSystemFont: false, fontFamily: 'Arial' };
expect(buildFontDesc(40, new TTFUtils()._updateFontFamily(label as Label))).toBe(`40px ${familyCss}`);
expect(jest.getTimerCount()).toBe(0);
} finally {
create.mockRestore();