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.

refactor(engine-render): remove unused opentype shaping (#7367)

白熱3ffd9c4e8a4f
diff --git a/packages/engine-render/package.json b/packages/engine-render/package.json
index 387fdbe4b5..a3ee068132 100644
--- a/packages/engine-render/package.json
+++ b/packages/engine-render/package.json
@@ -71,11 +71,9 @@
"@floating-ui/dom": "^1.8.0",
"@floating-ui/utils": "^0.2.12",
"@univerjs/core": "workspace:*",
- "franc-min": "^6.2.0",
- "opentype.js": "^2.0.0"
+ "franc-min": "^6.2.0"
},
"devDependencies": {
- "@types/opentype.js": "^1.3.10",
"@univerjs-infra/shared": "workspace:*",
"jest-canvas-mock": "^2.5.8",
"rollup-plugin-polyfill-node": "^0.13.0",
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
index 07ad9cdd1f..0eee5c599c 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
@@ -19,8 +19,6 @@ import { BooleanNumber, CustomRangeType, DataStreamTreeTokenType, PositionedObje
import { describe, expect, it, vi } from 'vitest';
import { Lang } from '../../../hyphenation/lang';
import { createSkeletonLetterGlyph } from '../../../model/glyph';
-import { fontLibrary } from '../../../shaping-engine/font-library';
-import * as textShapingModule from '../../../shaping-engine/text-shaping';
import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
@@ -434,125 +432,6 @@ describe('shaping', () => {
expect(customBlockGlyph!.bBox.ba + customBlockGlyph!.bBox.bd).toBe(0);
});
- it('shapes text with useOpenType when font library is ready', () => {
- const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello');
- const originalIsReady = fontLibrary.isReady;
- fontLibrary.isReady = true;
-
- try {
- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig, true);
- expect(result.length).toBeGreaterThan(0);
- } finally {
- fontLibrary.isReady = originalIsReady;
- }
- });
-
- it('shapes a measured whole entity atomically with useOpenType', () => {
- const source = String.raw`x+y`;
- const prefix = 'A ';
- const content = `${prefix}${source} B`;
- const range: ICustomRangeForInterceptor = {
- startIndex: prefix.length,
- endIndex: prefix.length + source.length - 1,
- rangeId: 'formula-1',
- rangeType: CustomRangeType.CUSTOM,
- wholeEntity: true,
- show: false,
- glyphAscentEm: 1,
- glyphDescentEm: 0.25,
- glyphWidthEm: 2,
- };
- const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
- body: { customRanges: [range] },
- });
- vi.spyOn(viewModel, 'getCustomRange').mockImplementation((index) =>
- index >= range.startIndex && index <= range.endIndex ? range : undefined
- );
- const originalIsReady = fontLibrary.isReady;
- fontLibrary.isReady = true;
- const spy = vi.spyOn(textShapingModule, 'textShape').mockReturnValue(
- `${content}${DataStreamTreeTokenType.PARAGRAPH}`.split('').map((char, start) => ({
- char,
- start,
- end: start + 1,
- glyph: null,
- font: null,
- kerning: 0,
- boundingBox: null,
- }))
- );
-
- try {
- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig, true);
- const formulaGlyphs = result.flatMap((item) => item.glyphs).filter((glyph) => glyph.raw === source);
-
- expect(formulaGlyphs).toHaveLength(1);
- expect(formulaGlyphs[0].count).toBe(source.length);
- expect(formulaGlyphs[0].content).toBe('\u200B');
- } finally {
- spy.mockRestore();
- fontLibrary.isReady = originalIsReady;
- }
- });
-
- it('shapes tab with useOpenType when font library is ready', () => {
- const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello\tworld');
- const originalIsReady = fontLibrary.isReady;
- fontLibrary.isReady = true;
-
- const spy = vi.spyOn(textShapingModule, 'textShape').mockReturnValue([
- { char: 'H', start: 0, end: 1, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'e', start: 1, end: 2, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'l', start: 2, end: 3, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'l', start: 3, end: 4, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'o', start: 4, end: 5, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: '\t', start: 5, end: 6, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'w', start: 6, end: 7, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'o', start: 7, end: 8, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'r', start: 8, end: 9, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'l', start: 9, end: 10, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'd', start: 10, end: 11, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: '\r', start: 11, end: 12, glyph: null, font: null, kerning: 0, boundingBox: null },
- ]);
-
- try {
- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig, true);
- const allGlyphs = result.flatMap((r) => r.glyphs);
- const tabGlyph = allGlyphs.find((g) => g.content === '\t');
- expect(tabGlyph).toBeDefined();
- } finally {
- spy.mockRestore();
- fontLibrary.isReady = originalIsReady;
- }
- });
-
- it('shapes emoji with useOpenType when font library is ready', () => {
- const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello \uD83D\uDE00');
- const originalIsReady = fontLibrary.isReady;
- fontLibrary.isReady = true;
-
- const spy = vi.spyOn(textShapingModule, 'textShape').mockReturnValue([
- { char: 'H', start: 0, end: 1, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'e', start: 1, end: 2, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'l', start: 2, end: 3, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'l', start: 3, end: 4, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: 'o', start: 4, end: 5, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: ' ', start: 5, end: 6, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: '\uD83D\uDE00', start: 6, end: 8, glyph: null, font: null, kerning: 0, boundingBox: null },
- { char: '\r', start: 8, end: 9, glyph: null, font: null, kerning: 0, boundingBox: null },
- ]);
-
- try {
- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig, true);
- const allGlyphs = result.flatMap((r) => r.glyphs);
- const emojiGlyph = allGlyphs.find((g) => g.content === '\uD83D\uDE00');
- expect(emojiGlyph).toBeDefined();
- } finally {
- spy.mockRestore();
- fontLibrary.isReady = originalIsReady;
- }
- });
-
it('loads hyphen pattern when language pattern is not available', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('test');
sectionBreakConfig.autoHyphenation = BooleanNumber.TRUE;
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
index 841b1a6268..212367efae 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
@@ -20,7 +20,6 @@ import type { ISectionBreakConfig } from '../../../../../basics/interfaces';
import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../../../view-model/document-view-model';
import type { IBreakPoints } from '../../line-breaker/line-breaker';
-import type { IOpenTypeGlyphInfo } from '../../shaping-engine/text-shaping';
import type { ILayoutContext } from '../../tools';
import { BooleanNumber, DataStreamTreeTokenType, GridType, PositionedObjectLayoutType } from '@univerjs/core';
import { cjk } from '../../../../../basics/cjk-regexp';
@@ -49,9 +48,6 @@ import {
glyphShrinkRight,
} from '../../model/glyph';
import { getBoundingBox } from '../../model/line';
-import { fontLibrary } from '../../shaping-engine/font-library';
-import { textShape } from '../../shaping-engine/text-shaping';
-import { prepareParagraphBody } from '../../shaping-engine/utils';
import {
getCharSpaceApply,
getCustomRangeGlyphMetrics,
@@ -201,8 +197,7 @@ export function shaping(
content: string,
viewModel: DocumentViewModel,
paragraphNode: DataStreamTreeNode,
- sectionBreakConfig: ISectionBreakConfig,
- useOpenType = false // Temporarily disable using opentype for shaping.
+ sectionBreakConfig: ISectionBreakConfig
): IShapedText[] {
const {
gridType = GridType.LINES,
@@ -227,20 +222,9 @@ export function shaping(
let measuredWholeEntityRangeIndex = 0;
let last = 0;
let bk;
- let lastGlyphIndex = 0;
const { hyphen, languageDetector } = ctx;
- const paragraphBody = prepareParagraphBody(viewModel.getBody()!, endIndex);
-
- // const now = +new Date();
- let glyphInfos: IOpenTypeGlyphInfo[] = [];
-
- if (useOpenType) {
- glyphInfos = textShape(paragraphBody);
- }
- // console.log('Text Shaping Time:', +new Date() - now);
-
// Add custom extension for linebreak.
tabLineBreakExtension(lineBreaker);
customBlockLineBreakExtension(lineBreaker);
@@ -272,243 +256,179 @@ export function shaping(
const word = content.slice(last, bk.position);
const shapedGlyphs: IDocumentSkeletonGlyph[] = [];
- if (fontLibrary.isReady && useOpenType) {
- const glyphInfosInWord = [];
-
- let i = 0;
- for (i = lastGlyphIndex; i < glyphInfos.length; i++) {
- const glyphInfo = glyphInfos[i];
- const { end } = glyphInfo;
-
- if (end > bk.position) {
- break;
- }
-
- glyphInfosInWord.push(glyphInfo);
+ let src = word;
+ let i = last;
+ while (src.length > 0) {
+ while (
+ measuredWholeEntityRangeIndex < measuredWholeEntityRangeStarts.length &&
+ measuredWholeEntityRangeStarts[measuredWholeEntityRangeIndex] < i
+ ) {
+ measuredWholeEntityRangeIndex++;
}
- lastGlyphIndex = i;
-
- for (let glyphInfoIndex = 0; glyphInfoIndex < glyphInfosInWord.length; glyphInfoIndex++) {
- const glyphInfo = glyphInfosInWord[glyphInfoIndex];
- const { start, char } = glyphInfo;
- const measuredRange = measuredWholeEntityRangeByStart.get(start);
-
- if (measuredRange) {
- const glyph = createMeasuredWholeEntityGlyph(
- content,
- measuredRange,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- if (glyph) {
- shapedGlyphs.push(glyph);
- const relativeEndIndex = measuredRange.endIndex - paragraphNode.startIndex + 1;
- while (
- glyphInfoIndex + 1 < glyphInfosInWord.length &&
- glyphInfosInWord[glyphInfoIndex + 1].start < relativeEndIndex
- ) {
- glyphInfoIndex++;
- }
- continue;
- }
- }
- const config = getFontCreateConfig(start, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ const char = src.match(/^[\s\S]/gu)?.[0];
- if (char === DataStreamTreeTokenType.TAB) {
- const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- const newSpan = createSkeletonTabGlyph(config, charSpaceApply);
- shapedGlyphs.push(newSpan);
- } else if (startWithEmoji(char)) {
- const newSpan = createSkeletonLetterGlyph(char, config);
- shapedGlyphs.push(newSpan);
- } else {
- const newSpan = createSkeletonLetterGlyph(
- char,
- config,
- getCustomRangeGlyphMetrics(start, viewModel, paragraphNode, config),
- glyphInfo
- );
- shapedGlyphs.push(newSpan);
- }
+ if (char == null) {
+ break;
}
- } else {
- let src = word;
- let i = last;
- while (src.length > 0) {
- while (
- measuredWholeEntityRangeIndex < measuredWholeEntityRangeStarts.length &&
- measuredWholeEntityRangeStarts[measuredWholeEntityRangeIndex] < i
- ) {
+
+ const measuredRange = measuredWholeEntityRangeByStart.get(i);
+ if (measuredRange) {
+ const glyph = createMeasuredWholeEntityGlyph(
+ content,
+ measuredRange,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ if (glyph) {
+ shapedGlyphs.push(glyph);
+ const count = measuredRange.endIndex - measuredRange.startIndex + 1;
+ i += count;
+ src = src.substring(count);
measuredWholeEntityRangeIndex++;
+ continue;
}
+ measuredWholeEntityRangeIndex++;
+ }
- const char = src.match(/^[\s\S]/gu)?.[0];
-
- if (char == null) {
- break;
+ if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
+ const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
+ const customBlock = viewModel.getCustomBlockWithoutSetCurrentIndex(paragraphNode.startIndex + i);
+
+ if (customBlock != null) {
+ const { blockId } = customBlock;
+ const drawingOrigin = drawings[blockId];
+ if (drawingOrigin?.layoutType === PositionedObjectLayoutType.INLINE) {
+ const { angle } = drawingOrigin.docTransform;
+ const { width = 0, height = 0 } = drawingOrigin.docTransform.size;
+ const top = 0;
+ const left = 0;
+ const boundingBox = getBoundingBox(angle, left, width, top, height);
+ const viewport = getDocsCustomBlockRenderViewport(
+ viewModel.getDataModel().getUnitId?.() ?? '',
+ drawingOrigin.drawingId,
+ {
+ fallbackHeight: boundingBox.height ?? 0,
+ fallbackWidth: boundingBox.width ?? 0,
+ }
+ );
+
+ newGlyph = createSkeletonCustomBlockGlyph(
+ config,
+ viewport?.layoutWidth ?? viewport?.width ?? boundingBox.width,
+ viewport?.height ?? boundingBox.height,
+ drawingOrigin.drawingId
+ );
+ } else if (drawingOrigin != null) {
+ newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);
+ }
}
- const measuredRange = measuredWholeEntityRangeByStart.get(i);
- if (measuredRange) {
- const glyph = createMeasuredWholeEntityGlyph(
- content,
- measuredRange,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- if (glyph) {
- shapedGlyphs.push(glyph);
- const count = measuredRange.endIndex - measuredRange.startIndex + 1;
- i += count;
- src = src.substring(count);
- measuredWholeEntityRangeIndex++;
- continue;
- }
- measuredWholeEntityRangeIndex++;
+ if (newGlyph == null) {
+ newGlyph = createSkeletonLetterGlyph(char, config);
}
- if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
- const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
- const customBlock = viewModel.getCustomBlockWithoutSetCurrentIndex(paragraphNode.startIndex + i);
-
- if (customBlock != null) {
- const { blockId } = customBlock;
- const drawingOrigin = drawings[blockId];
- if (drawingOrigin?.layoutType === PositionedObjectLayoutType.INLINE) {
- const { angle } = drawingOrigin.docTransform;
- const { width = 0, height = 0 } = drawingOrigin.docTransform.size;
- const top = 0;
- const left = 0;
- const boundingBox = getBoundingBox(angle, left, width, top, height);
- const viewport = getDocsCustomBlockRenderViewport(
- viewModel.getDataModel().getUnitId?.() ?? '',
- drawingOrigin.drawingId,
- {
- fallbackHeight: boundingBox.height ?? 0,
- fallbackWidth: boundingBox.width ?? 0,
- }
- );
-
- newGlyph = createSkeletonCustomBlockGlyph(
- config,
- viewport?.layoutWidth ?? viewport?.width ?? boundingBox.width,
- viewport?.height ?? boundingBox.height,
- drawingOrigin.drawingId
- );
- } else if (drawingOrigin != null) {
- newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);
- }
- }
+ shapedGlyphs.push(newGlyph);
+ i += char.length;
+ src = src.substring(char.length);
+ } else if (/\s/.test(char) || cjk.hasCJK(char)) {
+ const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
- if (newGlyph == null) {
- newGlyph = createSkeletonLetterGlyph(char, config);
- }
+ if (char === DataStreamTreeTokenType.TAB) {
+ const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
+ newGlyph = createSkeletonTabGlyph(config, charSpaceApply);
+ } else if (char === DataStreamTreeTokenType.PARAGRAPH) {
+ const zeroWidthParagraphBreak = sectionBreakConfig.renderConfig?.zeroWidthParagraphBreak;
- shapedGlyphs.push(newGlyph);
- i += char.length;
- src = src.substring(char.length);
- } else if (/\s/.test(char) || cjk.hasCJK(char)) {
- const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
-
- if (char === DataStreamTreeTokenType.TAB) {
- const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- newGlyph = createSkeletonTabGlyph(config, charSpaceApply);
- } else if (char === DataStreamTreeTokenType.PARAGRAPH) {
- const zeroWidthParagraphBreak = sectionBreakConfig.renderConfig?.zeroWidthParagraphBreak;
-
- if (zeroWidthParagraphBreak === BooleanNumber.TRUE) {
- newGlyph = createSkeletonLetterGlyph(char, config, 0);
- } else {
- newGlyph = createSkeletonLetterGlyph(
- char,
- config,
- getCustomRangeGlyphMetrics(i, viewModel, paragraphNode, config)
- );
- }
+ if (zeroWidthParagraphBreak === BooleanNumber.TRUE) {
+ newGlyph = createSkeletonLetterGlyph(char, config, 0);
} else {
- newGlyph = createSkeletonLetterGlyph(char, config);
+ newGlyph = createSkeletonLetterGlyph(
+ char,
+ config,
+ getCustomRangeGlyphMetrics(i, viewModel, paragraphNode, config)
+ );
}
-
- shapedGlyphs.push(newGlyph);
- i += char.length;
- src = src.substring(char.length);
- } else if (startWithEmoji(src)) {
- const { step, glyphGroup } = emojiHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasArabic(char)) {
- const { step, glyphGroup } = ArabicHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasTibetan(char)) {
- const { step, glyphGroup } = TibetanHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasThai(char)) {
- const { step, glyphGroup } = ThaiHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
} else {
- const nextMeasuredRangeStart = measuredWholeEntityRangeStarts[measuredWholeEntityRangeIndex];
- const sourceBeforeMeasuredRange = nextMeasuredRangeStart == null
- ? src
- : src.slice(0, nextMeasuredRangeStart - i);
- const { step, glyphGroup } = otherHandler(
- i,
- sourceBeforeMeasuredRange,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
+ newGlyph = createSkeletonLetterGlyph(char, config);
}
+
+ shapedGlyphs.push(newGlyph);
+ i += char.length;
+ src = src.substring(char.length);
+ } else if (startWithEmoji(src)) {
+ const { step, glyphGroup } = emojiHandler(
+ i,
+ src,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ shapedGlyphs.push(...glyphGroup);
+ i += step;
+
+ src = src.substring(step);
+ } else if (hasArabic(char)) {
+ const { step, glyphGroup } = ArabicHandler(
+ i,
+ src,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ shapedGlyphs.push(...glyphGroup);
+ i += step;
+
+ src = src.substring(step);
+ } else if (hasTibetan(char)) {
+ const { step, glyphGroup } = TibetanHandler(
+ i,
+ src,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ shapedGlyphs.push(...glyphGroup);
+ i += step;
+
+ src = src.substring(step);
+ } else if (hasThai(char)) {
+ const { step, glyphGroup } = ThaiHandler(
+ i,
+ src,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ shapedGlyphs.push(...glyphGroup);
+ i += step;
+
+ src = src.substring(step);
+ } else {
+ const nextMeasuredRangeStart = measuredWholeEntityRangeStarts[measuredWholeEntityRangeIndex];
+ const sourceBeforeMeasuredRange = nextMeasuredRangeStart == null
+ ? src
+ : src.slice(0, nextMeasuredRangeStart - i);
+ const { step, glyphGroup } = otherHandler(
+ i,
+ sourceBeforeMeasuredRange,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph
+ );
+ shapedGlyphs.push(...glyphGroup);
+ i += step;
+
+ src = src.substring(step);
}
}
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index 4cdff65efa..908318c50b 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -22,7 +22,6 @@ import type {
IDocumentSkeletonGlyph,
} from '../../../../basics/i-document-skeleton-cached';
import type { IFontCreateConfig } from '../../../../basics/interfaces';
-import type { IOpenTypeGlyphInfo } from '../shaping-engine/text-shaping';
import { BooleanNumber, BulletAlignment, DataStreamTreeTokenType, GridType } from '@univerjs/core';
import { cjk } from '../../../../basics/cjk-regexp';
import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
@@ -30,7 +29,6 @@ import {
isCjkCenterAlignedPunctuation,
isCjkLeftAlignedPunctuation,
isCjkRightAlignedPunctuation,
- ptToPixel,
} from '../../../../basics/tools';
import { applyFontMetricCompatibility, getDocumentCompatibilityPolicy } from '../../document-compatibility';
import { FontCache } from '../shaping-engine/font-cache';
@@ -94,11 +92,10 @@ export function createSkeletonWordGlyph(
export function createSkeletonLetterGlyph(
content: string,
config: IFontCreateConfig,
- glyphMetrics?: number | { ascent?: number; descent?: number; width?: number },
- glyphInfo?: IOpenTypeGlyphInfo
+ glyphMetrics?: number | { ascent?: number; descent?: number; width?: number }
): IDocumentSkeletonGlyph {
const glyphWidth = typeof glyphMetrics === 'number' ? glyphMetrics : glyphMetrics?.width;
- const glyph = _createSkeletonWordOrLetter(GlyphType.LETTER, content, config, glyphWidth, glyphInfo);
+ const glyph = _createSkeletonWordOrLetter(GlyphType.LETTER, content, config, glyphWidth);
if (typeof glyphMetrics === 'object') {
if (glyphMetrics.ascent != null) {
@@ -190,8 +187,7 @@ export function _createSkeletonWordOrLetter(
glyphType: GlyphType,
content: string,
config: IFontCreateConfig,
- glyphWidth?: number,
- glyphInfo?: IOpenTypeGlyphInfo
+ glyphWidth?: number
): IDocumentSkeletonGlyph {
const { fontStyle, textStyle, charSpace = 1, gridType = GridType.LINES, snapToGrid = BooleanNumber.FALSE } = config;
const skipWidthList: string[] = [
@@ -253,11 +249,7 @@ export function _createSkeletonWordOrLetter(
let bBox = null;
let xOffset = 0;
- if (glyphInfo && glyphInfo.boundingBox && glyphInfo.font) {
- bBox = FontCache.getBBoxFromGlyphInfo(glyphInfo, fontStyle);
- } else {
- bBox = FontCache.getTextSize(content, fontStyle);
- }
+ bBox = FontCache.getTextSize(content, fontStyle);
bBox = applyFontMetricCompatibility(
content,
fontStyle,
@@ -277,15 +269,6 @@ export function _createSkeletonWordOrLetter(
}
}
- // Handle kerning.
- if (glyphInfo && glyphInfo.kerning !== 0 && glyphInfo.font) {
- const radio = ptToPixel(fontStyle.fontSize) / glyphInfo.font.unitsPerEm;
- const delta = glyphInfo.kerning * radio;
-
- width += delta;
- xOffset += delta;
- }
-
return {
content,
ts: textStyle,
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
index 09caa4347f..aa0560915e 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
@@ -159,31 +159,5 @@ describe('font cache', () => {
fontCache: '11px Other Font',
} as any);
expect(byMeasure.width).toBeGreaterThanOrEqual(0);
-
- const fromGlyphInfo = FontCache.getBBoxFromGlyphInfo({
- glyph: {
- advanceWidth: 500,
- },
- font: {
- unitsPerEm: 1000,
- ascender: 800,
- descender: -200,
- },
- boundingBox: {
- x1: 0,
- y1: -120,
- x2: 510,
- y2: 710,
- },
- } as any, {
- fontString: '12px Arial',
- fontSize: 12,
- originFontSize: 12,
- fontFamily: 'Arial',
- fontCache: '12px Arial',
- } as any);
-
- expect(fromGlyphInfo.width).toBeGreaterThan(0);
- expect(fromGlyphInfo.aba).toBeGreaterThan(0);
});
});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts
deleted file mode 100644
index 647d4b6af2..0000000000
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * 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 { BooleanNumber } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { fontLibrary } from '../font-library';
-
-describe('font library', () => {
- it('matches best local font variant by style distance', () => {
- const book = new Map([
- ['My Sans', new Map([
- ['Regular', {
- font: {
- family: 'My Sans',
- fullName: 'My Sans Regular',
- postscriptName: 'MySans-Regular',
- style: 'Regular',
- },
- buffer: new ArrayBuffer(8),
- }],
- ['Bold', {
- font: {
- family: 'My Sans',
- fullName: 'My Sans Bold',
- postscriptName: 'MySans-Bold',
- style: 'Bold',
- },
- buffer: new ArrayBuffer(8),
- }],
- ['Italic', {
- font: {
- family: 'My Sans',
- fullName: 'My Sans Italic',
- postscriptName: 'MySans-Italic',
- style: 'Italic',
- },
- buffer: new ArrayBuffer(8),
- }],
- ])],
- ]);
-
- (fontLibrary as any)._fontBook = book;
-
- const regular = fontLibrary.findBestMatchFontByStyle({
- ff: 'My Sans',
- bl: BooleanNumber.FALSE,
- it: BooleanNumber.FALSE,
- });
- expect(regular?.font.fullName).toBe('My Sans Regular');
-
- const bold = fontLibrary.findBestMatchFontByStyle({
- ff: 'My Sans',
- bl: BooleanNumber.TRUE,
- it: BooleanNumber.FALSE,
- });
- expect(bold?.font.fullName).toBe('My Sans Bold');
-
- const italic = fontLibrary.findBestMatchFontByStyle({
- ff: 'My Sans',
- bl: BooleanNumber.FALSE,
- it: BooleanNumber.TRUE,
- });
- expect(italic?.font.fullName).toBe('My Sans Italic');
-
- expect(fontLibrary.findBestMatchFontByStyle({ ff: 'Unknown Family' })).toBeUndefined();
- });
-
- it('filters valid font families from current font book', () => {
- (fontLibrary as any)._fontBook = new Map([
- ['A', new Map()],
- ['B', new Map()],
- ]);
-
- expect(fontLibrary.getValidFontFamilies(['A', 'C', 'B'])).toEqual(['A', 'B']);
- expect(fontLibrary.getValidFontFamilies([])).toEqual([]);
- });
-});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts
deleted file mode 100644
index 9e1be22b61..0000000000
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * 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 { BooleanNumber } from '@univerjs/core';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { textShape } from '../text-shaping';
-
-const h = vi.hoisted(() => {
- const getKerningValue = vi.fn((prev: any, next: any) => (prev?.index === 1 && next?.index === 2 ? -20 : 0));
- const mockFont = {
- unitsPerEm: 1000,
- stringToGlyphs: vi.fn((content: string) => {
- return content.split('').map((char, index) => ({
- index: char === '?' ? 0 : index + 1,
- advanceWidth: 520,
- getBoundingBox: () => ({
- x1: 0,
- y1: -120,
- x2: 520,
- y2: 720,
- }),
- }));
- }),
- getKerningValue,
- };
-
- return {
- parse: vi.fn(() => mockFont),
- fontLibrary: {
- isReady: true,
- getValidFontFamilies: vi.fn((families: string[]) => families),
- findBestMatchFontByStyle: vi.fn(() => ({
- font: {
- family: 'Arial',
- fullName: 'Arial Regular',
- postscriptName: 'Arial-Regular',
- style: 'Regular',
- },
- buffer: new ArrayBuffer(8),
- })),
- },
- getKerningValue,
- };
-});
-
-vi.mock('opentype.js', () => ({
- parse: h.parse,
-}));
-
-vi.mock('../font-library', () => ({
- fontLibrary: h.fontLibrary,
-}));
-
-describe('text shaping runtime', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- h.fontLibrary.isReady = true;
- h.fontLibrary.getValidFontFamilies.mockImplementation((families: string[]) => families);
- h.fontLibrary.findBestMatchFontByStyle.mockReturnValue({
- font: {
- family: 'Arial',
- fullName: 'Arial Regular',
- postscriptName: 'Arial-Regular',
- style: 'Regular',
- },
- buffer: new ArrayBuffer(8),
- });
- });
-
- it('returns empty result when font library is not ready', () => {
- h.fontLibrary.isReady = false;
- const result = textShape({
- dataStream: 'AB',
- } as any);
- expect(result).toEqual([]);
- });
-
- it('shapes text chunks with kerning and caches results', () => {
- const body = {
- dataStream: 'AB\r',
- textRuns: [{
- st: 0,
- ed: 2,
- ts: {
- ff: 'Arial',
- bl: BooleanNumber.FALSE,
- it: BooleanNumber.FALSE,
- },
- }],
- } as any;
-
- const first = textShape(body);
- expect(first.length).toBeGreaterThanOrEqual(2);
- expect(first[0].glyph).toBeTruthy();
- expect(first[1].kerning).toBe(-20);
- expect(h.parse).toHaveBeenCalledTimes(1);
-
- const second = textShape(body);
- expect(second).toBe(first);
- expect(h.parse).toHaveBeenCalledTimes(1);
- });
-
- it('keeps rtl text runs in logical order for canvas shaping', () => {
- const result = textShape({
- dataStream: 'ABC\r',
- textRuns: [{
- st: 0,
- ed: 3,
- ts: {
- ff: 'Arial',
- rtl: BooleanNumber.TRUE,
- },
- }],
- } as any);
-
- expect(result.slice(0, 3).map((glyph) => glyph.char)).toEqual(['A', 'B', 'C']);
- });
-
- it('falls back to null glyph when no valid font family exists', () => {
- h.fontLibrary.getValidFontFamilies.mockReturnValueOnce([]);
- const result = textShape({
- dataStream: 'A',
- } as any);
-
- expect(result).toHaveLength(1);
- expect(result[0].glyph).toBeNull();
- expect(result[0].font).toBeNull();
- });
-});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
index 1a865b6bdb..b6e4af6e88 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
@@ -19,8 +19,6 @@ import type {
IDocumentSkeletonBoundingBox,
IDocumentSkeletonFontStyle,
} from '../../../../basics/i-document-skeleton-cached';
-import type { IOpenTypeGlyphInfo } from './text-shaping';
-import { ptToPixel } from '../../../../basics/tools';
export const DEFAULT_MEASURE_TEXT = '0';
@@ -204,23 +202,6 @@ export class FontCache {
return bBox;
}
- static getBBoxFromGlyphInfo(glyphInfo: IOpenTypeGlyphInfo, fontStyle: IDocumentSkeletonFontStyle) {
- const glyph = glyphInfo.glyph!;
- const font = glyphInfo.font!;
- const { y1, y2 } = glyphInfo.boundingBox!;
- const scale = ptToPixel(fontStyle.fontSize) / font.unitsPerEm;
-
- const { ascender, descender } = font;
-
- return this._calculateBoundingBoxByMeasureText({
- width: (glyph.advanceWidth ?? 0) * scale,
- fontBoundingBoxAscent: ascender * scale,
- fontBoundingBoxDescent: Math.abs(descender * scale),
- actualBoundingBoxAscent: y2 * scale,
- actualBoundingBoxDescent: Math.abs(y1 * scale),
- }, fontStyle);
- }
-
/**
* Measure text on another canvas.
* @param content
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/font-library.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/font-library.ts
deleted file mode 100644
index f010598b9e..0000000000
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/font-library.ts
+++ /dev/null
@@ -1,317 +0,0 @@
-/**
- * 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 type { IStyleBase, Nullable } from '@univerjs/core';
-import { BooleanNumber } from '@univerjs/core';
-
-interface IFontData {
- readonly family: string;
- readonly fullName: string;
- readonly postscriptName: string;
- readonly style: string;
-}
-
-interface IFontWithBuffer {
- readonly font: IFontData;
- readonly buffer: ArrayBuffer;
-}
-
-type FontDistance = [number, number];
-
-enum CompareResult {
- // a is equal to b.
- EQUAL,
-
- // a is greater than b.
- GREATER,
-
- // a is less than b.
- LESS,
-}
-
-enum FontStyle {
- // The default, typically upright style.
- Normal,
-
- // A cursive style with custom letterform.
- Italic,
-
- // Just a slanted version of the normal style.
- Oblique,
-}
-
-enum FontWeight {
- // Thin weight (100).
- THIN = 100,
-
- // Extra light weight (200).
- EXTRALIGHT = 200,
-
- // Light weight (300).
- LIGHT = 300,
-
- // Regular weight (400).
- REGULAR = 400,
-
- // Medium weight (500).
- MEDIUM = 500,
-
- // Semibold weight (600).
- SEMIBOLD = 600,
-
- // Bold weight (700).
- BOLD = 700,
-
- // Extrabold weight (800).
- EXTRABOLD = 800,
-
- // Black weight (900).
- BLACK = 900,
-}
-
-interface IFontVariant {
- // The style of the font (normal / italic).
- style: FontStyle;
- /// How heavy the font is normal / bold.
- weight: FontWeight;
- // How condensed or expanded the font is (0.5 - 2.0).
- // stretch: FontStretch,
-}
-
-export interface IFontInfo {
- // The typographic font family this font is part of.
- family: string;
- // Properties that distinguish this font from other fonts in the same family.
- variant: IFontVariant;
-}
-
-function getFontInfoFromFontData(fontData: IFontData): IFontInfo {
- const { family, style: styleString } = fontData;
-
- let style = FontStyle.Normal;
- let weight = FontWeight.REGULAR;
-
- if (/italic/i.test(styleString)) {
- style = FontStyle.Italic;
- }
-
- switch (true) {
- case /thin|hairline/i.test(styleString): {
- weight = FontWeight.THIN;
- break;
- }
-
- case /(extra|ultra) *light/i.test(styleString): {
- weight = FontWeight.EXTRALIGHT;
- break;
- }
-
- case /light/i.test(styleString): {
- weight = FontWeight.LIGHT;
- break;
- }
-
- case /medium/i.test(styleString): {
- weight = FontWeight.MEDIUM;
- break;
- }
-
- case /(semi|demi) *bold/i.test(styleString): {
- weight = FontWeight.SEMIBOLD;
- break;
- }
-
- case /bold/i.test(styleString): {
- weight = FontWeight.BOLD;
- break;
- }
-
- case /(extra|ultra) *bold/i.test(styleString): {
- weight = FontWeight.EXTRABOLD;
- break;
- }
-
- case /black|heavy/i.test(styleString): {
- weight = FontWeight.BLACK;
- break;
- }
- }
-
- return {
- family,
- variant: {
- style,
- weight,
- },
- };
-}
-
-function getFontInfoFromTextStyle(style: IStyleBase): IFontInfo {
- const { ff, bl = BooleanNumber.FALSE, it = BooleanNumber.FALSE } = style;
-
- return {
- family: ff ?? 'Arial',
- variant: {
- style: it === BooleanNumber.TRUE ? FontStyle.Italic : FontStyle.Normal,
- weight: bl === BooleanNumber.TRUE ? FontWeight.BOLD : FontWeight.REGULAR,
- },
- };
-}
-
-function fontInfoDistance(a: IFontInfo, b: IFontInfo): FontDistance {
- let styleDistance = Number.POSITIVE_INFINITY;
-
- if (a.variant.style === b.variant.style) {
- styleDistance = 0;
- } else if (a.variant.style !== FontStyle.Normal && b.variant.style !== FontStyle.Normal) {
- styleDistance = 1;
- } else {
- styleDistance = 2;
- }
-
- const weightDistance = Math.abs(a.variant.weight - b.variant.weight);
-
- return [
- styleDistance,
- weightDistance,
- ];
-}
-
-function compareFontInfoDistance(a: FontDistance, b: FontDistance) {
- if (a[0] === b[0] && a[1] === b[1]) {
- return CompareResult.EQUAL;
- }
-
- if (a[0] === b[0]) {
- return a[1] > b[1] ? CompareResult.GREATER : CompareResult.LESS;
- }
-
- return a[0] > b[0] ? CompareResult.GREATER : CompareResult.LESS;
-}
-
-async function checkLocalFontsPermission() {
- if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
- return false;
- }
-
- if (typeof window === 'undefined') {
- return false;
- }
- if (window.navigator == null || window.navigator?.permissions == null) {
- return false;
- }
-
- try {
- const status = await window.navigator.permissions.query({ name: 'local-fonts' as PermissionName });
-
- return status.state === 'granted';
- // eslint-disable-next-line unused-imports/no-unused-vars
- } catch (_err) {
- return false;
- }
-}
-
-class FontLibrary {
- isReady = false;
- private _fontBook: Map<string, Map<string, IFontWithBuffer>> = new Map();
-
- constructor() {
- this._loadFontsToBook();
- }
-
- private async _loadFontsToBook() {
- if (this.isReady) return;
-
- const permissionStatus = await checkLocalFontsPermission();
- if (!permissionStatus || !('queryLocalFonts' in window)) {
- return;
- }
-
- // If running in Electron, we should not use the Local Font Access API
- if (typeof navigator === 'object' && navigator.userAgent.includes('Electron')) {
- return;
- }
-
- try {
- // @ts-expect-error queryLocalFonts is an experimental API and may not be available in all environments.
- const availableFonts = await window.queryLocalFonts({
- postscriptNames: [],
- });
-
- for (const font of availableFonts) {
- const { family, style } = font;
- let fontMap = this._fontBook.get(family);
-
- if (fontMap == null) {
- fontMap = new Map();
- this._fontBook.set(family, fontMap);
- }
-
- const blob = await font.blob();
- const buffer = await blob.arrayBuffer();
-
- fontMap.set(style, {
- font,
- buffer,
- });
- }
-
- this.isReady = true;
- } catch (err) {
- console.error(err);
- }
- }
-
- findBestMatchFontByStyle(style: IStyleBase): Nullable<IFontWithBuffer> {
- const ff = style.ff!;
- const fontMap = this._fontBook.get(ff);
-
- if (fontMap == null) {
- // TODO: @jocs use font family to match the best.
- return;
- }
-
- let bestFont: Nullable<IFontWithBuffer> = null;
- let bestDistance: FontDistance = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
-
- for (const fontWithBuffer of fontMap.values()) {
- const { font } = fontWithBuffer;
- const currentFontInfo = getFontInfoFromFontData(font);
- const targetFontInfo = getFontInfoFromTextStyle(style);
- const distance = fontInfoDistance(currentFontInfo, targetFontInfo);
-
- if (bestFont == null) {
- bestFont = fontWithBuffer;
- bestDistance = distance;
- } else {
- const result = compareFontInfoDistance(bestDistance, distance);
-
- if (result === CompareResult.GREATER) {
- bestFont = fontWithBuffer;
- bestDistance = distance;
- }
- }
- }
-
- return bestFont;
- }
-
- getValidFontFamilies(families: string[]): string[] {
- return families.filter((family) => this._fontBook.has(family));
- }
-}
-
-export const fontLibrary = new FontLibrary();
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/text-shaping.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/text-shaping.ts
deleted file mode 100644
index 4f8ff06579..0000000000
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/text-shaping.ts
+++ /dev/null
@@ -1,262 +0,0 @@
-/**
- * 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 type { IDocumentBody, IStyleBase, Nullable } from '@univerjs/core';
-import type Opentype from 'opentype.js';
-import { BooleanNumber } from '@univerjs/core';
-import { parse } from 'opentype.js';
-import { DEFAULT_FONTFACE_PLANE } from '../../../../basics/const';
-import { getFirstGrapheme, isEmojiGrapheme } from '../../../../basics/tools';
-import { fontLibrary } from './font-library';
-import { prepareTextChunks } from './utils';
-
-interface IBoundingBox {
- x1: number;
- y1: number;
- x2: number;
- y2: number;
-
-}
-
-export interface IOpenTypeGlyphInfo {
- char: string;
- start: number;
- end: number;
- glyph: Nullable<Opentype.Glyph>;
- font: Nullable<Opentype.Font>;
- kerning: number;
- boundingBox: Nullable<IBoundingBox>;
-}
-
-const fontCache = new Map<string, Opentype.Font>();
-const glyphCache: Map<string, IOpenTypeGlyphInfo[]> = new Map();
-const fontFamilyCache = new Map<string, string[]>();
-
-function trimOuterQuotes(value: string): string {
- const firstChar = value.charCodeAt(0);
- const lastChar = value.charCodeAt(value.length - 1);
- const hasLeadingQuote = firstChar === 34 || firstChar === 39;
- const hasTrailingQuote = lastChar === 34 || lastChar === 39;
-
- if (hasLeadingQuote && hasTrailingQuote) {
- return value.slice(1, -1);
- }
-
- if (hasLeadingQuote) {
- return value.slice(1);
- }
-
- if (hasTrailingQuote) {
- return value.slice(0, -1);
- }
-
- return value;
-}
-
-function expandFontFamilies(fontFamily: Nullable<string>): string[] {
- if (!fontFamily?.trim()) {
- return [];
- }
-
- let families = fontFamilyCache.get(fontFamily);
-
- if (families) {
- return families;
- }
-
- families = fontFamily
- .split(',')
- .map((family) => trimOuterQuotes(family.trim()))
- .filter(Boolean);
-
- fontFamilyCache.set(fontFamily, families);
-
- return families;
-}
-
-const defaultFontFamilies = expandFontFamilies(DEFAULT_FONTFACE_PLANE);
-
-function shapeChunk(
- content: string,
- charPosition: number,
- used: Set<string>,
- families: string[],
- style: IStyleBase
-): IOpenTypeGlyphInfo[] {
- let fi = 0;
- let fontFamily = families[fi];
-
- while (used.has(fontFamily)) {
- fi++;
- fontFamily = families[fi];
- }
-
- if (!fontFamily) {
- return [{
- char: content,
- start: charPosition,
- end: charPosition + content.length,
- glyph: null,
- font: null,
- kerning: 0,
- boundingBox: null,
- }];
- }
-
- used.add(fontFamily);
-
- const { font: fontInfo, buffer: fontBuffer } = fontLibrary.findBestMatchFontByStyle({
- ff: fontFamily,
- bl: style.bl ?? BooleanNumber.FALSE,
- it: style.it ?? BooleanNumber.FALSE,
- })!;
-
- let font = fontCache.get(fontInfo.fullName);
- if (!font) {
- font = parse(fontBuffer) as Opentype.Font;
- fontCache.set(fontInfo.fullName, font);
- }
-
- // const option = {
- // kerning: true,
- // features: {
- // liga: false,
- // },
- // };
-
- const results = [];
-
- const glyphs = font.stringToGlyphs(content);
- const chars = content.match(/[\s\S]/gu) ?? [];
-
- let gi = 0;
- let startIndex = 0;
-
- while (gi < glyphs.length) {
- const glyph = glyphs[gi];
- if (glyph.index !== 0) {
- results.push({
- char: chars[gi],
- start: startIndex + charPosition,
- end: startIndex + charPosition + chars[gi].length,
- glyph,
- font,
- kerning: 0,
- boundingBox: glyph.getBoundingBox(),
- });
- } else {
- const start = startIndex;
- const subStr = content.substring(start);
- const firstGrapheme = getFirstGrapheme(subStr);
-
- if (firstGrapheme && isEmojiGrapheme(firstGrapheme)) {
- let acc = 0;
- do {
- acc += chars[gi].length;
- startIndex += chars[gi].length;
- gi++;
- } while (acc < firstGrapheme.length);
-
- results.push(...shapeChunk(content.slice(start, start + firstGrapheme.length), charPosition + start, used, families, style));
-
- continue;
- } else {
- let nextGlyph = glyphs[gi + 1];
- let nextChar = chars[gi + 1];
-
- while (nextGlyph?.index === 0 && !isEmojiGrapheme(nextChar)) {
- startIndex += chars[gi].length;
- gi++;
- nextGlyph = glyphs[gi + 1];
- nextChar = chars[gi + 1];
- }
-
- results.push(...shapeChunk(content.slice(start, startIndex + chars[gi].length), charPosition + start, used, families, style));
- }
- }
-
- startIndex += chars[gi]?.length;
- gi++;
- }
-
- used.delete(fontFamily);
-
- return results;
-}
-
-function kerningAdjustment(glyphs: IOpenTypeGlyphInfo[]) {
- if (glyphs.length < 2) {
- return;
- }
-
- let lastFont = glyphs[0].font;
- let lastGlyph = glyphs[0].glyph;
-
- for (let i = 1; i < glyphs.length; i++) {
- const { font, glyph } = glyphs[i];
- if (lastFont !== font || font == null || lastGlyph == null || glyph == null) {
- lastFont = font;
- lastGlyph = glyph;
- continue;
- }
-
- const kerning = font.getKerningValue(lastGlyph, glyph);
-
- if (kerning !== 0) {
- glyphs[i].kerning = kerning;
- }
-
- lastFont = font;
- lastGlyph = glyph;
- }
-}
-
-export function textShape(body: IDocumentBody) {
- if (!fontLibrary.isReady) {
- return [];
- }
-
- const key = JSON.stringify(body);
-
- if (glyphCache.has(key)) {
- return glyphCache.get(key)!;
- }
-
- const chunks = prepareTextChunks(body);
-
- const glyphs = [];
- let charPosition = 0;
-
- for (const chunk of chunks) {
- const { content, style = {} } = chunk;
- let fontFamilies = [
- ...expandFontFamilies(style.ff ?? 'Arial'),
- ...defaultFontFamilies,
- ];
-
- fontFamilies = fontLibrary.getValidFontFamilies(fontFamilies);
-
- glyphs.push(...shapeChunk(content, charPosition, new Set(), fontFamilies, style));
-
- charPosition += content.length;
- }
-
- kerningAdjustment(glyphs);
-
- glyphCache.set(key, glyphs);
-
- return glyphs;
-}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 53d8988fff..9eff0dc278 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1441,13 +1441,7 @@ importers:
franc-min:
specifier: ^6.2.0
version: 6.2.0
- opentype.js:
- specifier: ^2.0.0
- version: 2.0.0
devDependencies:
- '@types/opentype.js':
- specifier: ^1.3.10
- version: 1.3.10
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
@@ -6617,9 +6611,6 @@ packages:
resolution: {integrity: sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ==}
-
resolution: {integrity: sha512-+N+2H39P8X+Hy1I5mC6awlTX54k3FhiUmvt7HWzGJZvF+syUAAxP/stwppS8JE84YHqFgRMv6fCy31202CMFxQ==}
@@ -9832,10 +9823,6 @@ packages:
resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-kCyjv6xdDY1W/jLWZ/L3QhhTlKUqDZMQ5+Jdlw12b3dXkKNpYBqqlMMj0YDQPShWFTMwgZI1hG14kN3XUDSg/A==}
- hasBin: true
-
resolution: {integrity: sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==}
engines: {node: '>= 0.8.0'}
@@ -14272,8 +14259,6 @@ snapshots:
dependencies:
undici-types: 8.3.0
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
@@ -17890,8 +17875,6 @@ snapshots:
is-inside-container: 1.0.0
wsl-utils: 0.1.0
-
dependencies:
deep-is: 0.1.4