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(doc): linebreak support extension and add before tab break (#1146)

Ran Luoa2ba82562aca
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 365cb0a6f3..e3209fc0fe 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -42,6 +42,7 @@
"Hiragino",
"ilvl",
"IRPC",
+ "Jamo",
"jikkai",
"Kaiti",
"KANBAN",
diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.ts
index 5eb48a26da..35397be759 100644
--- a/packages/core/src/docs/data-model/types.ts
+++ b/packages/core/src/docs/data-model/types.ts
@@ -51,7 +51,7 @@ export enum DataStreamTreeTokenType {
PAGE_BREAK = '\f', // 换页
DOCS_END = '\0', // 文档结尾
TAB = '\t', // 制表符
- CUSTOM_BLOCK = '\b', // 图片 mention等不参与文档流的场景
+ CUSTOM_BLOCK = '\b', // 图片 mention 等不参与文档流的场景
LETTER = '',
diff --git a/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts
index 6c21ed8769..9d452ca835 100644
--- a/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts
+++ b/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts
@@ -129,7 +129,6 @@ function _divideOperator(
if (preOffsetLeft + width > divide.width) {
// width 超过 divide 宽度
setDivideFullState(divide, true);
-
// 处理 word 或者数字串超过 divide width 的情况,主要分两种情况
// 1. 以段落符号结尾时候,即使超过 divide 宽度,也需要将换行符追加到 divide 结尾。
// 2. 空行中,英文单词或者连续数字超过 divide 宽度的情况,将把英文单词、数字串拆分,一部分追加到上一行,剩下的放在新的一行中,
diff --git a/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts b/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts
index f623f5dae1..4d8a787c0a 100644
--- a/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts
+++ b/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts
@@ -47,6 +47,7 @@ import {
lineIterator,
} from '../../common/tools';
import { LineBreaker } from '../../linebreak';
+import { tabLineBreakExtension } from '../../linebreak/extensions/tab-linebreak-extension';
import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../../view-model/document-view-model';
import { dealWithBullet } from './bullet';
@@ -160,6 +161,9 @@ export function dealWidthParagraph(
let last = 0;
let bk;
+ // Add custom extension for linebreak.
+ tabLineBreakExtension(breaker);
+
while ((bk = breaker.nextBreak())) {
// get the string between the last break and this one
const word = content.slice(last, bk.position);
@@ -190,33 +194,16 @@ export function dealWidthParagraph(
const char = src[0];
const charIndex = i + startIndex;
- if (char === DataStreamTreeTokenType.TAB) {
- const fontCreateConfig = getFontCreateConfig(
- i,
- bodyModel,
- paragraphNode,
- sectionBreakConfig,
- paragraphStyle
- );
- const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- const tabSpan = createSkeletonTabSpan(fontCreateConfig, charSpaceApply);
- pushPending();
- allPages = calculateParagraphLayout(
- [tabSpan],
- allPages,
- sectionBreakConfig,
- paragraphConfig,
- paragraphStart
- );
-
- i++;
- src = src.substring(1);
- continue;
- }
-
if (/\s/.test(char) || hasCJK(char)) {
const config = getFontCreateConfig(i, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);
- const newSpan = createSkeletonLetterSpan(char, config);
+ let newSpan: IDocumentSkeletonSpan;
+
+ if (char === DataStreamTreeTokenType.TAB) {
+ const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
+ newSpan = createSkeletonTabSpan(config, charSpaceApply);
+ } else {
+ newSpan = createSkeletonLetterSpan(char, config);
+ }
spanGroup.push(newSpan);
i++;
diff --git a/packages/engine-render/src/components/docs/linebreak/__tests__/linebreak.spec.ts b/packages/engine-render/src/components/docs/linebreak/__tests__/linebreak.spec.ts
index 238198b425..0a041fff36 100644
--- a/packages/engine-render/src/components/docs/linebreak/__tests__/linebreak.spec.ts
+++ b/packages/engine-render/src/components/docs/linebreak/__tests__/linebreak.spec.ts
@@ -19,9 +19,10 @@
import fs from 'fs';
import { describe, expect, it } from 'vitest';
+import { tabLineBreakExtension } from '../extensions/tab-linebreak-extension';
import { LineBreaker } from '../linebreaker';
-describe('unicode line break tests', function () {
+describe('unicode line break tests', () => {
// these tests are weird, possibly incorrect or just tailored differently. we skip them.
const skip = [
125, 127, 815, 1161, 1163, 1165, 1167, 1331, 2189, 2191, 2873, 2875, 3567, 3739, 4081, 4083, 4425, 4427, 4473,
@@ -33,7 +34,7 @@ describe('unicode line break tests', function () {
const data = fs.readFileSync(new URL('LineBreakTest.txt', import.meta.url), 'utf8');
const lines = data.split('\n');
- return lines.forEach(function (line, i) {
+ return lines.forEach((line, i) => {
const rowNumber = i + 1;
let bk;
if (!line || /^#/.test(line)) {
@@ -58,7 +59,7 @@ describe('unicode line break tests', function () {
const expected = cols
.split(/\s*÷\s*/)
.slice(0, -1)
- .map(function (c) {
+ .map((c) => {
let codes: string[] | number[] = c.split(/\s*×\s*/);
if (codes[0] === '') {
codes.shift();
@@ -68,10 +69,44 @@ describe('unicode line break tests', function () {
});
if (skip.includes(rowNumber)) {
- it.skip(cols, function () {});
+ it.skip(cols, () => {});
return;
}
expect(breaks).toStrictEqual(expected);
});
});
+
+describe('line break extensions tests', () => {
+ it('should break before tab in Chinese', () => {
+ const data = '中\t国';
+ const breaker = new LineBreaker(data);
+ tabLineBreakExtension(breaker);
+ const breaks: string[] = [];
+ let last = 0;
+ let bk;
+
+ while ((bk = breaker.nextBreak())) {
+ breaks.push(data.slice(last, bk.position));
+ last = bk.position;
+ }
+
+ expect(breaks).toStrictEqual(['中', '\t', '国']);
+ });
+
+ it('should break before tab in English', () => {
+ const data = 'hello\tworld';
+ const breaker = new LineBreaker(data);
+ tabLineBreakExtension(breaker);
+ const breaks: string[] = [];
+ let last = 0;
+ let bk;
+
+ while ((bk = breaker.nextBreak())) {
+ breaks.push(data.slice(last, bk.position));
+ last = bk.position;
+ }
+
+ expect(breaks).toStrictEqual(['hello', '\t', 'world']);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/linebreak/break.ts b/packages/engine-render/src/components/docs/linebreak/break.ts
new file mode 100644
index 0000000000..467286aaac
--- /dev/null
+++ b/packages/engine-render/src/components/docs/linebreak/break.ts
@@ -0,0 +1,22 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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.
+ */
+
+export class Break {
+ constructor(
+ public position: number,
+ public required = false
+ ) {}
+}
diff --git a/packages/engine-render/src/components/docs/linebreak/extensions/tab-linebreak-extension.ts b/packages/engine-render/src/components/docs/linebreak/extensions/tab-linebreak-extension.ts
new file mode 100644
index 0000000000..00428bbe68
--- /dev/null
+++ b/packages/engine-render/src/components/docs/linebreak/extensions/tab-linebreak-extension.ts
@@ -0,0 +1,25 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { LineBreaker } from '../linebreaker';
+
+const TAB_CODE_POINT = 9;
+
+export function tabLineBreakExtension(breaker: LineBreaker) {
+ breaker.addRule('break_before_tab', (codePoint) => {
+ return codePoint === TAB_CODE_POINT;
+ });
+}
diff --git a/packages/engine-render/src/components/docs/linebreak/linebreaker.ts b/packages/engine-render/src/components/docs/linebreak/linebreaker.ts
index b105c1e12f..5c9009ce07 100644
--- a/packages/engine-render/src/components/docs/linebreak/linebreaker.ts
+++ b/packages/engine-render/src/components/docs/linebreak/linebreaker.ts
@@ -14,13 +14,23 @@
* limitations under the License.
*/
+/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable no-magic-numbers */
+import type { Nullable } from '@univerjs/core';
+
+import { Break } from './break';
import { AI, AL, BA, BK, CJ, CR, HL, HY, LF, NL, NS, RI, SA, SG, SP, WJ, XX, ZWJ } from './classes';
import { CI_BRK, CP_BRK, DI_BRK, IN_BRK, pairTable, PR_BRK } from './pairs';
+import type { ILineBreakRule } from './rule';
+import { Rule } from './rule';
import data from './trie-data';
import UnicodeTrie from './unicode-trie';
+interface ILineBreakExtension {
+ (breaker: LineBreaker): void;
+}
+
const classTrie = new UnicodeTrie(data);
function mapClass(c: number) {
@@ -54,74 +64,126 @@ function mapFirst(c: number) {
return c;
}
}
+export class LineBreaker {
+ private _pos: number = 0;
+ private _lastPos: number = 0;
+ private _curClass: Nullable<number> = null;
+ private _codePoint: Nullable<number> = null;
+ private _nextClass: Nullable<number> = null;
+ private _LB8a: boolean = false;
+ private _LB21a: boolean = false;
+ private _LB30a: number = 0;
+ private _rule: Rule = new Rule();
+
+ constructor(public string: string) {}
+
+ use(extension: ILineBreakExtension) {
+ extension(this);
+
+ return this;
+ }
-class Break {
- constructor(
- public position: number,
- public required = false
- ) {}
-}
+ addRule(key: string, rule: ILineBreakRule) {
+ this._rule.add(key, rule);
-export class LineBreaker {
- pos: number;
- lastPos: number;
- curClass: number | null;
- nextClass: number | null;
- LB8a: boolean;
- LB21a: boolean;
- LB30a: number;
-
- constructor(public string: string) {
- this.pos = 0;
- this.lastPos = 0;
- this.curClass = null;
- this.nextClass = null;
- this.LB8a = false;
- this.LB21a = false;
- this.LB30a = 0;
+ return this;
+ }
+
+ nextBreak() {
+ // get the first char if we're at the beginning of the string
+ if (this._curClass == null) {
+ const firstClass = this._nextCharClass();
+ this._curClass = mapFirst(firstClass);
+ this._nextClass = firstClass;
+ this._LB8a = firstClass === ZWJ;
+ this._LB30a = 0;
+ }
+
+ while (this._pos < this.string.length) {
+ this._lastPos = this._pos;
+ const lastClass = this._nextClass;
+ this._nextClass = this._nextCharClass();
+
+ // explicit newline
+ if (this._curClass === BK || (this._curClass === CR && this._nextClass !== LF)) {
+ this._curClass = mapFirst(mapClass(this._nextClass));
+ return new Break(this._lastPos, true);
+ }
+
+ if (this._rule.shouldBreak(this._codePoint!, this._nextClass)) {
+ this._curClass = mapFirst(mapClass(this._nextClass));
+ return new Break(this._lastPos);
+ }
+
+ let shouldBreak = this._getSimpleBreak();
+
+ if (shouldBreak === null) {
+ shouldBreak = this._getPairTableBreak(lastClass!);
+ }
+
+ // Rule _LB8a
+ this._LB8a = this._nextClass === ZWJ;
+
+ if (shouldBreak) {
+ return new Break(this._lastPos);
+ }
+ }
+
+ if (this._lastPos < this.string.length) {
+ this._lastPos = this.string.length;
+ return new Break(this.string.length);
+ }
+
+ return null;
}
- nextCodePoint() {
- const code = this.string.charCodeAt(this.pos++);
- const next = this.string.charCodeAt(this.pos);
+ private _getNextCodePoint() {
+ const code = this.string.charCodeAt(this._pos++);
+ const next = this.string.charCodeAt(this._pos);
// If a surrogate pair
if (code >= 0xd800 && code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
- this.pos++;
+ this._pos++;
return (code - 0xd800) * 0x400 + (next - 0xdc00) + 0x10000;
}
return code;
}
- nextCharClass() {
- return mapClass(classTrie.get(this.nextCodePoint()));
+ private _nextCharClass() {
+ const nextCodePoint = this._getNextCodePoint();
+ const rawClass = classTrie.get(nextCodePoint);
+
+ this._codePoint = nextCodePoint;
+
+ return mapClass(rawClass);
}
- getSimpleBreak() {
+ private _getSimpleBreak() {
// handle classes not handled by the pair table
- switch (this.nextClass) {
+ switch (this._nextClass) {
case SP:
return false;
case BK:
case LF:
case NL:
- this.curClass = BK;
+ this._curClass = BK;
return false;
case CR:
- this.curClass = CR;
+ this._curClass = CR;
return false;
}
return null;
}
- getPairTableBreak(lastClass: number) {
+ private _getPairTableBreak(lastClass: number) {
// if not handled already, use the pair table
let shouldBreak = false;
- switch (pairTable[this.curClass!][this.nextClass!]) {
+
+ switch (pairTable[this._curClass!][this._nextClass!]) {
case DI_BRK: // Direct break
shouldBreak = true;
break;
@@ -148,74 +210,31 @@ export class LineBreaker {
break;
}
- if (this.LB8a) {
+ if (this._LB8a) {
shouldBreak = false;
}
- // Rule LB21a
- if (this.LB21a && (this.curClass === HY || this.curClass === BA)) {
+ // Rule _LB21a
+ if (this._LB21a && (this._curClass === HY || this._curClass === BA)) {
shouldBreak = false;
- this.LB21a = false;
+ this._LB21a = false;
} else {
- this.LB21a = this.curClass === HL;
+ this._LB21a = this._curClass === HL;
}
- // Rule LB30a
- if (this.curClass === RI) {
- this.LB30a++;
- if (this.LB30a === 2 && this.nextClass === RI) {
+ // Rule _LB30a
+ if (this._curClass === RI) {
+ this._LB30a++;
+ if (this._LB30a === 2 && this._nextClass === RI) {
shouldBreak = true;
- this.LB30a = 0;
+ this._LB30a = 0;
}
} else {
- this.LB30a = 0;
+ this._LB30a = 0;
}
- this.curClass = this.nextClass;
+ this._curClass = this._nextClass;
return shouldBreak;
}
-
- nextBreak() {
- // get the first char if we're at the beginning of the string
- if (this.curClass == null) {
- const firstClass = this.nextCharClass();
- this.curClass = mapFirst(firstClass);
- this.nextClass = firstClass;
- this.LB8a = firstClass === ZWJ;
- this.LB30a = 0;
- }
-
- while (this.pos < this.string.length) {
- this.lastPos = this.pos;
- const lastClass = this.nextClass;
- this.nextClass = this.nextCharClass();
-
- // explicit newline
- if (this.curClass === BK || (this.curClass === CR && this.nextClass !== LF)) {
- this.curClass = mapFirst(mapClass(this.nextClass));
- return new Break(this.lastPos, true);
- }
-
- let shouldBreak = this.getSimpleBreak();
-
- if (shouldBreak === null) {
- shouldBreak = this.getPairTableBreak(lastClass!);
- }
-
- // Rule LB8a
- this.LB8a = this.nextClass === ZWJ;
-
- if (shouldBreak) {
- return new Break(this.lastPos);
- }
- }
-
- if (this.lastPos < this.string.length) {
- this.lastPos = this.string.length;
- return new Break(this.string.length);
- }
-
- return null;
- }
}
diff --git a/packages/engine-render/src/components/docs/linebreak/rule.ts b/packages/engine-render/src/components/docs/linebreak/rule.ts
new file mode 100644
index 0000000000..e44491bedd
--- /dev/null
+++ b/packages/engine-render/src/components/docs/linebreak/rule.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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.
+ */
+
+export interface ILineBreakRule {
+ (codePoint: number, className: number): boolean;
+}
+
+export class Rule {
+ private _rules = new Map();
+
+ add(key: string, rule: ILineBreakRule) {
+ this._rules.set(key, rule);
+ }
+
+ shouldBreak(codePoint: number, className: number) {
+ for (const rule of this._rules.values()) {
+ if (rule(codePoint, className)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}