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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(core): unify the handler of get plain text from rich-text model (#3421)
zhangwe9395d2843c9
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.tsindex 2a108d98a7..a11cd82e38 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts@@ -15,7 +15,10 @@*/import { describe, expect, it } from 'vitest';-import { excludePointsFromRange } from '../custom-range'; // 替换为你的文件路径+import { excludePointsFromRange, getCustomRangesInterestsWithRange, shouldDeleteCustomRange } from '../custom-range'; // 替换为你的文件路径+import { CustomRangeType, type ICustomRange } from '../../../../../types/interfaces';+import { DataStreamTreeTokenType } from '../../../types';+import type { ITextRange } from '../../../../../sheets/typedef';describe('excludePointsFromRange function', () => {it('should handle empty points array', () => {@@ -59,4 +62,145 @@ describe('excludePointsFromRange function', () => {const points = [2, 4, 6, 8];expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [3, 3], [5, 5], [7, 7], [9, 10]]);});++ describe('excludePointsFromRange function', () => {+ it('should handle empty points array', () => {+ const range: [number, number] = [0, 10];+ const points: number[] = [];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 10]]);+ });++ it('should handle points at the beginning and end', () => {+ const range: [number, number] = [0, 10];+ const points = [0, 10];+ expect(excludePointsFromRange(range, points)).toEqual([[1, 9]]);+ });++ it('should handle overlapping points', () => {+ const range: [number, number] = [0, 10];+ const points = [2, 3, 3, 5];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [4, 4], [6, 10]]);+ });++ it('should handle points outside the range', () => {+ const range: [number, number] = [0, 10];+ const points = [-1, 12];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 10]]);+ });++ it('should handle a single point in the middle', () => {+ const range: [number, number] = [0, 10];+ const points = [5];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 4], [6, 10]]);+ });++ it('should handle multiple ranges', () => {+ const range: [number, number] = [0, 20];+ const points = [2, 5, 10, 15];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [3, 4], [6, 9], [11, 14], [16, 20]]);+ });++ it('should handle points in ascending order', () => {+ const range: [number, number] = [0, 10];+ const points = [2, 4, 6, 8];+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [3, 3], [5, 5], [7, 7], [9, 10]]);+ });+ });+});++describe('getCustomRangesInterestsWithRange function', () => {+ it('should return empty array if no custom ranges intersect', () => {+ const range: ITextRange = { startOffset: 5, endOffset: 10, collapsed: false };+ const customRanges: ICustomRange[] = [+ { startIndex: 0, endIndex: 4, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 11, endIndex: 15, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ ];+ expect(getCustomRangesInterestsWithRange(range, customRanges)).toEqual([]);+ });++ it('should return intersecting custom ranges', () => {+ const range: ITextRange = { startOffset: 5, endOffset: 10, collapsed: false };+ const customRanges: ICustomRange[] = [+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ ];+ expect(getCustomRangesInterestsWithRange(range, customRanges)).toEqual([+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ ]);+ });++ it('should handle collapsed range', () => {+ const range: ITextRange = { startOffset: 5, endOffset: 5, collapsed: true };+ const customRanges: ICustomRange[] = [+ { startIndex: 0, endIndex: 4, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 5, endIndex: 10, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ ];+ expect(getCustomRangesInterestsWithRange(range, customRanges)).toEqual([]);+ });++ it('should handle multiple intersecting custom ranges', () => {+ const range: ITextRange = { startOffset: 5, endOffset: 15, collapsed: false };+ const customRanges: ICustomRange[] = [+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 14, endIndex: 20, rangeId: '3', rangeType: CustomRangeType.HYPERLINK },+ ];++ expect(getCustomRangesInterestsWithRange(range, customRanges)).toEqual([+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },+ { startIndex: 14, endIndex: 20, rangeId: '3', rangeType: CustomRangeType.HYPERLINK },+ ]);+ });+});++describe('shouldDeleteCustomRange function', () => {+ it('should return false if end is less than 0', () => {+ const deleteStart = 0;+ const deleteLen = 5;+ const customRange: ICustomRange = { startIndex: 10, endIndex: 20, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = 'some random data stream';+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(false);+ });++ it('should return true if start is 0 and end is greater than or equal to dataStreamSlice length', () => {+ const deleteStart = 0;+ const deleteLen = 11;+ const customRange: ICustomRange = { startIndex: 0, endIndex: 10, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = 'some random data stream';+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(true);+ });++ it('should return false if result contains non-split symbols', () => {+ const deleteStart = 1;+ const deleteLen = 1;+ const customRange: ICustomRange = { startIndex: 0, endIndex: 10, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = 'some random data stream';+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(false);+ });++ it('should return true if result contains only split symbols', () => {+ const deleteStart = 1;+ const deleteLen = 1;+ const customRange: ICustomRange = { startIndex: 0, endIndex: 10, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(true);+ });++ it('should handle deletion within the range', () => {+ const deleteStart = 2;+ const deleteLen = 3;+ const customRange: ICustomRange = { startIndex: 0, endIndex: 10, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}abc${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(false);+ });++ it('should handle deletion that spans the entire range', () => {+ const deleteStart = 0;+ const deleteLen = 11;+ const customRange: ICustomRange = { startIndex: 0, endIndex: 10, rangeId: '1', rangeType: CustomRangeType.HYPERLINK };+ const dataStream = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}abc${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;+ expect(shouldDeleteCustomRange(deleteStart, deleteLen, customRange, dataStream)).toBe(true);+ });});diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/selection.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/selection.spec.tsnew file mode 100644index 0000000000..245561d955--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/selection.spec.ts@@ -0,0 +1,83 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { makeSelection, normalizeSelection } from '../selection';+import type { ITextRange } from '../../../../../sheets/typedef';++describe('makeSelection', () => {+ it('should create a collapsed selection when only startOffset is provided', () => {+ const startOffset = 5;+ const expected: ITextRange = { startOffset, endOffset: startOffset, collapsed: true };+ const result = makeSelection(startOffset);+ expect(result).toEqual(expected);+ });++ it('should create a selection with startOffset and endOffset when both are provided', () => {+ const startOffset = 5;+ const endOffset = 10;+ const expected: ITextRange = { startOffset, endOffset, collapsed: false };+ const result = makeSelection(startOffset, endOffset);+ expect(result).toEqual(expected);+ });++ it('should create a collapsed selection when startOffset equals endOffset', () => {+ const startOffset = 5;+ const endOffset = 5;+ const expected: ITextRange = { startOffset, endOffset, collapsed: true };+ const result = makeSelection(startOffset, endOffset);+ expect(result).toEqual(expected);+ });++ it('should throw an error when endOffset is less than startOffset', () => {+ const startOffset = 10;+ const endOffset = 5;+ expect(() => makeSelection(startOffset, endOffset)).toThrowError(+ `Cannot make a doc selection when endOffset ${endOffset} is less than startOffset ${startOffset}.`+ );+ });+});++describe('normalizeSelection', () => {+ it('should normalize selection with startOffset less than endOffset', () => {+ const selection: ITextRange = { startOffset: 5, endOffset: 10, collapsed: false };+ const expected: ITextRange = { startOffset: 5, endOffset: 10, collapsed: false };+ const result = normalizeSelection(selection);+ expect(result).toEqual(expected);+ });++ it('should normalize selection with startOffset greater than endOffset', () => {+ const selection: ITextRange = { startOffset: 10, endOffset: 5, collapsed: false };+ const expected: ITextRange = { startOffset: 5, endOffset: 10, collapsed: false };+ const result = normalizeSelection(selection);+ expect(result).toEqual(expected);+ });++ it('should normalize selection with startOffset equal to endOffset', () => {+ const selection: ITextRange = { startOffset: 5, endOffset: 5, collapsed: true };+ const expected: ITextRange = { startOffset: 5, endOffset: 5, collapsed: true };+ const result = normalizeSelection(selection);+ expect(result).toEqual(expected);+ });++ it('should retain the collapsed property', () => {+ const selection: ITextRange = { startOffset: 10, endOffset: 5, collapsed: true };+ const expected: ITextRange = { startOffset: 5, endOffset: 10, collapsed: true };+ const result = normalizeSelection(selection);+ expect(result).toEqual(expected);+ });+});+diff --git a/packages/core/src/docs/data-model/text-x/build-utils/index.ts b/packages/core/src/docs/data-model/text-x/build-utils/index.tsindex e0953a9ce1..a9415ecaab 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/index.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/index.ts@@ -15,7 +15,8 @@*/import { copyCustomRange, getCustomRangesInterestsWithRange, isIntersecting, shouldDeleteCustomRange } from './custom-range';-import { getDeleteSelection, getInsertSelection, getRetainAndDeleteFromReplace, getSelectionWithNoSymbolSide, getSelectionWithSymbolMax, isSegmentIntersects, makeSelection, normalizeSelection } from './selection';+import { fromPlainText, getPlainText } from './parse';+import { getDeleteSelection, getInsertSelection, getRetainAndDeleteFromReplace, isSegmentIntersects, makeSelection, normalizeSelection } from './selection';import { addCustomRangeTextX, deleteCustomRangeTextX, getRetainAndDeleteAndExcludeLineBreak, replaceSelectionTextX } from './text-x-utils';export class BuildTextUtils {@@ -35,10 +36,9 @@ export class BuildTextUtils {makeSelection,normalizeSelection,- getSelectionWithSymbolMax,- getSelectionWithNoSymbolSide,getDeleteSelection,getInsertSelection,+getDeleteActions: getRetainAndDeleteFromReplace,getDeleteExculdeLastLineBreakActions: getRetainAndDeleteAndExcludeLineBreak,};@@ -46,6 +46,11 @@ export class BuildTextUtils {static range = {isIntersects: isSegmentIntersects,};++ static transform = {+ getPlainText,+ fromPlainText,+ };}export type { IAddCustomRangeTextXParam, IDeleteCustomRangeParam, IReplaceSelectionTextXParams } from './text-x-utils';diff --git a/packages/core/src/docs/data-model/text-x/build-utils/parse.ts b/packages/core/src/docs/data-model/text-x/build-utils/parse.tsnew file mode 100644index 0000000000..4420848392--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/parse.ts@@ -0,0 +1,101 @@+/**+ * 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 { generateRandomId, Tools } from '../../../../shared';+import { CustomRangeType } from '../../../../types/interfaces';+import { DataStreamTreeTokenType } from '../../types';+import type { ICustomRange, IDocumentBody, IParagraph } from '../../../../types/interfaces';++const tags = [+ // DataStreamTreeTokenType.PARAGRAPH, // 段落+ // DataStreamTreeTokenType.SECTION_BREAK, // 章节+ DataStreamTreeTokenType.TABLE_START, // 表格开始+ DataStreamTreeTokenType.TABLE_ROW_START, // 表格开始+ DataStreamTreeTokenType.TABLE_CELL_START, // 表格开始+ DataStreamTreeTokenType.TABLE_CELL_END, // 表格开始+ DataStreamTreeTokenType.TABLE_ROW_END, // 表格开始+ DataStreamTreeTokenType.TABLE_END, // 表格结束+ DataStreamTreeTokenType.CUSTOM_RANGE_START, // 自定义范围开始+ DataStreamTreeTokenType.CUSTOM_RANGE_END, // 自定义范围结束+ // DataStreamTreeTokenType.COLUMN_BREAK, // 换列+ // DataStreamTreeTokenType.PAGE_BREAK, // 换页+ // DataStreamTreeTokenType.DOCS_END, // 文档结尾+ // DataStreamTreeTokenType.TAB, // 制表符+ DataStreamTreeTokenType.CUSTOM_BLOCK, // 图片 mention 等不参与文档流的场景++];++export const getPlainText = (dataStream: string) => {+ const text = dataStream.endsWith('\r\n') ? dataStream.slice(0, -2) : dataStream;+ return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);+};++export const fromPlainText = (text: string): IDocumentBody => {+ const dataStream = text.replace(/\n/g, '\r');+ const paragraphs: IParagraph[] = [];+ const customRanges: ICustomRange[] = [];+ let cursor = 0;+ let newDataStream = '';+ let linkCount = 0;++ const loopParagraph = (i: number, insertP = true) => {+ const paragraphText = dataStream.slice(cursor, i);+ if (Tools.isLegalUrl(paragraphText)) {+ const id = generateRandomId();+ const urlText = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${paragraphText}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;+ const range: ICustomRange = {+ startIndex: cursor + linkCount * 2,+ endIndex: cursor + linkCount * 2 + urlText.length - 1,+ rangeId: id,+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: text,+ },+ };+ customRanges.push(range);+ newDataStream += urlText;+ cursor = i + 1;+ linkCount++;+ if (insertP) {+ newDataStream += '\r';+ paragraphs.push({ startIndex: i + linkCount * 2 });+ }+ } else {+ newDataStream += dataStream.slice(cursor, i + 1);+ cursor = i + 1;+ if (insertP) {+ paragraphs.push({ startIndex: i + linkCount * 2 });+ }+ }+ };++ let end = 0;+ for (let i = 0; i < dataStream.length; i++) {+ if (dataStream[i] === '\r') {+ loopParagraph(i);+ end = i;+ }+ }++ if (end !== dataStream.length - 1) {+ loopParagraph(dataStream.length, false);+ }+ return {+ dataStream: newDataStream,+ paragraphs,+ customRanges,+ };+};diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 555ca8e4de..c6d8b66fce 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -18,48 +18,54 @@ import { installShims } from './common/shims';installShims();-export type { Serializable } from './common/json';-export { DEFAULT_DOCUMENT_SUB_COMPONENT_ID } from './docs/data-model/subdocument';-export { type UnitType, UnitModel, UniverInstanceType } from './common/unit';-export { Registry, RegistryAsMap } from './common/registry';-export { CustomCommandExecutionError } from './common/error';-export { Univer } from './univer';-export { shallowEqual } from './common/equal';-export { isNumeric, isSafeNumeric } from './common/number';+export { dedupe, groupBy, makeArray, remove, rotate } from './common/array';export { isBooleanString } from './common/boolean';-export { dedupe, remove, rotate, groupBy, makeArray } from './common/array';-export { mergeSets } from './common/set';export {+ createInternalEditorID,DEFAULT_EMPTY_DOCUMENT_VALUE,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DOCS_ZEN_EDITOR_UNIT_ID_KEY,- createInternalEditorID,isInternalEditorID,} from './common/const';+export * from './common/di';+export { shallowEqual } from './common/equal';+export { CustomCommandExecutionError } from './common/error';export { throttle } from './common/function';+export type { IComposeInterceptors, IInterceptor, InterceptorHandler } from './common/interceptor';+export { composeInterceptors, createInterceptorKey, InterceptorManager } from './common/interceptor';+export type { Serializable } from './common/json';export { MemoryCursor } from './common/memory-cursor';+export { mixinClass } from './common/mixin';+export { isNumeric, isSafeNumeric } from './common/number';+export { Registry, RegistryAsMap } from './common/registry';export { requestImmediateMacroTask } from './common/request-immediate-macro-task';export { type ISequenceExecuteResult, sequence, sequenceAsync } from './common/sequence';+export { mergeSets } from './common/set';+export { UnitModel, type UnitType, UniverInstanceType } from './common/unit';export * from './docs/data-model';+export { JSON1, JSONX } from './docs/data-model/json-x/json-x';+export type { JSONXActions, JSONXPath } from './docs/data-model/json-x/json-x';+export { replaceInDocumentBody } from './docs/data-model/replacement';+export { DEFAULT_DOCUMENT_SUB_COMPONENT_ID } from './docs/data-model/subdocument';+export { ActionIterator } from './docs/data-model/text-x/action-iterator';export {- TextXActionType,- type TextXAction,type IDeleteAction,type IInsertAction,type IRetainAction,+ type TextXAction,+ TextXActionType,} from './docs/data-model/text-x/action-types';-export { DataValidationRenderMode } from './types/enum/data-validation-render-mode';-export { ActionIterator } from './docs/data-model/text-x/action-iterator';-export { getBodySlice, composeBody, SliceBodyType } from './docs/data-model/text-x/utils';+export { normalizeTextRuns } from './docs/data-model/text-x/apply-utils/common';+export { updateAttributeByDelete } from './docs/data-model/text-x/apply-utils/delete-apply';+export { updateAttributeByInsert } from './docs/data-model/text-x/apply-utils/insert-apply';export { TextX } from './docs/data-model/text-x/text-x';export type { TPriority } from './docs/data-model/text-x/text-x';-export { JSONX, JSON1 } from './docs/data-model/json-x/json-x';-export type { JSONXActions, JSONXPath } from './docs/data-model/json-x/json-x';-export { replaceInDocumentBody } from './docs/data-model/replacement';-export { type IEventObserver, EventState, EventSubject, fromEventSubject } from './observer/observable';-export { Plugin } from './services/plugin/plugin';-export { PluginService, DependentOn } from './services/plugin/plugin.service';+export { composeBody, getBodySlice, SliceBodyType } from './docs/data-model/text-x/utils';+export { getCustomDecorationSlice, getCustomRangeSlice, normalizeBody } from './docs/data-model/text-x/utils';+export { EventState, EventSubject, fromEventSubject, type IEventObserver } from './observer/observable';+export { AuthzIoLocalService } from './services/authz-io/authz-io-local.service';+export { IAuthzIoService } from './services/authz-io/type';export {type CommandListener,CommandService,@@ -79,26 +85,41 @@ export {sequenceExecuteAsync,} from './services/command/command.service';export { IConfigService } from './services/config/config.service';+export { ConfigService } from './services/config/config.service';export * from './services/context/context';export { ContextService, IContextService } from './services/context/context.service';export { ErrorService, type IError } from './services/error/error.service';export { IUniverInstanceService } from './services/instance/instance.service';+export { UniverInstanceService } from './services/instance/instance.service';export { LifecycleStages, OnLifecycle, runOnLifecycle } from './services/lifecycle/lifecycle';export { LifecycleService } from './services/lifecycle/lifecycle.service';+export { LifecycleInitializerService } from './services/lifecycle/lifecycle.service';export { ILocalStorageService } from './services/local-storage/local-storage.service';export { LocaleService } from './services/locale/locale.service';export { DesktopLogService, ILogService, LogLevel } from './services/log/log.service';+export { PermissionService } from './services/permission/permission.service';export {IPermissionService,PermissionStatus,} from './services/permission/type';export type { IPermissionParam } from './services/permission/type';++// #region sheet+export type { IPermissionPoint } from './services/permission/type';+export type { IPermissionTypes, RangePermissionPointConstructor, WorkbookPermissionPointConstructor, WorkSheetPermissionPointConstructor } from './services/permission/type';+export { Plugin } from './services/plugin/plugin';+export type { PluginCtor } from './services/plugin/plugin';+export { DependentOn, PluginService } from './services/plugin/plugin.service';+export { type DependencyOverride, mergeOverrideWithDependencies } from './services/plugin/plugin-override';export { IResourceLoaderService } from './services/resource-loader/type';export { ResourceManagerService } from './services/resource-manager/resource-manager.service';export type { IResourceHook } from './services/resource-manager/type';export { IResourceManagerService } from './services/resource-manager/type';export { type IStyleSheet, ThemeService } from './services/theme/theme.service';++// #region sheet+export {type IUndoRedoCommandInfos,type IUndoRedoCommandInfosByInterceptor,@@ -107,79 +128,58 @@ export {type IUndoRedoStatus,LocalUndoRedoService,RedoCommand,- UndoCommand,RedoCommandId,+ UndoCommand,UndoCommandId,} from './services/undoredo/undoredo.service';+export { createDefaultUser } from './services/user-manager/const';+export { type IUser, UserManagerService } from './services/user-manager/user-manager.service';export * from './shared';+export { isBlackColor, isWhiteColor } from './shared/color/color-kit';+export { cellToRange } from './shared/common';+export { nameCharacterCheck } from './shared/name';export { fromCallback, takeAfter } from './shared/rxjs';-export { UserManagerService, type IUser } from './services/user-manager/user-manager.service';--// #region sheet--export type { IComposeInterceptors, IInterceptor, InterceptorHandler } from './common/interceptor';-export { composeInterceptors, createInterceptorKey, InterceptorManager } from './common/interceptor';-export { normalizeTextRuns } from './docs/data-model/text-x/apply-utils/common';-export type { PluginCtor } from './services/plugin/plugin';-export { type DependencyOverride, mergeOverrideWithDependencies } from './services/plugin/plugin-override';-export * from './types/const';-export * from './types/enum';-export * from './types/interfaces';-export { UniverInstanceService } from './services/instance/instance.service';-export { LifecycleInitializerService } from './services/lifecycle/lifecycle.service';-export { ConfigService } from './services/config/config.service';--// #region sheet--export { isRangesEqual, isUnitRangesEqual } from './sheets/util';export { Range } from './sheets/range';-export { Styles } from './sheets/styles';export {DEFAULT_WORKSHEET_COLUMN_COUNT,DEFAULT_WORKSHEET_COLUMN_COUNT_KEY,- DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY,- DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY,- DEFAULT_WORKSHEET_ROW_COUNT_KEY,- DEFAULT_WORKSHEET_ROW_HEIGHT_KEY,- DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY,DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,+ DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY,DEFAULT_WORKSHEET_COLUMN_WIDTH,+ DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY,DEFAULT_WORKSHEET_ROW_COUNT,+ DEFAULT_WORKSHEET_ROW_COUNT_KEY,DEFAULT_WORKSHEET_ROW_HEIGHT,+ DEFAULT_WORKSHEET_ROW_HEIGHT_KEY,DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,+ DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY,mergeWorksheetSnapshotWithDefault,} from './sheets/sheet-snapshot-utils';-export { SheetViewModel } from './sheets/view-model';+export { Styles } from './sheets/styles';export * from './sheets/typedef';-export { getWorksheetUID, Workbook } from './sheets/workbook';-export { Worksheet, extractPureTextFromCell } from './sheets/worksheet';-export { SlideDataModel } from './slides/slide-model';-export * from './types/const';-export * from './types/enum';-export * from './types/interfaces';-export { isBlackColor, isWhiteColor } from './shared/color/color-kit';-export { cellToRange } from './shared/common';+export { isRangesEqual, isUnitRangesEqual } from './sheets/util';+export { SheetViewModel } from './sheets/view-model';// #endregion-export type { IDataValidationRule, IDataValidationRuleBase, IDataValidationRuleInfo, IDataValidationRuleOptions, ISheetDataValidationRule } from './types/interfaces/i-data-validation';-export type { ICellCustomRender, ICellRenderContext } from './types/interfaces/i-cell-custom-render';+export { getWorksheetUID, Workbook } from './sheets/workbook';+export { extractPureTextFromCell, getOriginCellValue, Worksheet } from './sheets/worksheet';+export { SlideDataModel } from './slides/slide-model';+export * from './types/const';+export * from './types/const';+export { skipParseTagNames } from './types/const/clipboard';+export * from './types/enum';+export * from './types/enum';export { DataValidationErrorStyle } from './types/enum/data-validation-error-style';export { DataValidationImeMode } from './types/enum/data-validation-ime-mode';export { DataValidationOperator } from './types/enum/data-validation-operator';-export { DataValidationType } from './types/enum/data-validation-type';+export { DataValidationRenderMode } from './types/enum/data-validation-render-mode';export { DataValidationStatus } from './types/enum/data-validation-status';-export type { IPermissionTypes, WorkbookPermissionPointConstructor, WorkSheetPermissionPointConstructor, RangePermissionPointConstructor } from './services/permission/type';-export { PermissionService } from './services/permission/permission.service';-export { AuthzIoLocalService } from './services/authz-io/authz-io-local.service';-export { IAuthzIoService } from './services/authz-io/type';-export { createDefaultUser } from './services/user-manager/const';-export { skipParseTagNames } from './types/const/clipboard';-export { normalizeBody, getCustomRangeSlice, getCustomDecorationSlice } from './docs/data-model/text-x/utils';-export { updateAttributeByDelete } from './docs/data-model/text-x/apply-utils/delete-apply';-export { updateAttributeByInsert } from './docs/data-model/text-x/apply-utils/insert-apply';-export { nameCharacterCheck } from './shared/name';-export { mixinClass } from './common/mixin';+export { DataValidationType } from './types/enum/data-validation-type';+export * from './types/interfaces';+export * from './types/interfaces';+export type { ICellCustomRender, ICellRenderContext } from './types/interfaces/i-cell-custom-render';+export type { IDataValidationRule, IDataValidationRuleBase, IDataValidationRuleInfo, IDataValidationRuleOptions, ISheetDataValidationRule } from './types/interfaces/i-data-validation';-export * from './common/di';+export { Univer } from './univer';diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 87589036a6..82bdc367b3 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DataStreamTreeTokenType } from '../docs';+import { BuildTextUtils } from '../docs';import { ObjectMatrix, Rectangle, Tools } from '../shared';import { createRowColIter } from '../shared/row-col-iter';import { type BooleanNumber, CellValueType } from '../types/enum';@@ -732,7 +732,7 @@ export function extractPureTextFromCell(cell: Nullable<ICellData>): string {const richTextValue = cell.p?.body?.dataStream;if (richTextValue) {- return richTextValue.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');+ return BuildTextUtils.transform.getPlainText(richTextValue);}const rawValue = cell.v;@@ -753,3 +753,23 @@ export function extractPureTextFromCell(cell: Nullable<ICellData>): string {return '';}++export function getOriginCellValue(cell: Nullable<ICellData>) {+ if (cell === null) {+ return '';+ }++ if (cell?.p) {+ const body = cell?.p.body;++ if (body == null) {+ return '';+ }++ const data = body.dataStream;+ const newDataStream = BuildTextUtils.transform.getPlainText(data);+ return newDataStream;+ }++ return cell?.v;+}diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsxindex 6222aec7aa..bcd891061c 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx@@ -14,10 +14,10 @@* limitations under the License.*/-import { getBodySlice, ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';+import { BuildTextUtils, getBodySlice, ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';import { Button, FormLayout, Input } from '@univerjs/design';import { DocSelectionManagerService } from '@univerjs/docs';-import { DocSelectionRenderService, getPlainTextFormBody } from '@univerjs/docs-ui';+import { DocSelectionRenderService } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { KeyCode } from '@univerjs/ui';import React, { useEffect, useState } from 'react';@@ -71,7 +71,7 @@ export const DocHyperLinkEdit = () => {const matchedRange = body?.customRanges?.find((i) => editing?.linkId === i.rangeId);if (doc && matchedRange) {setLink(matchedRange.properties?.url ?? '');- setLabel(getPlainTextFormBody(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex)));+ setLabel(BuildTextUtils.transform.getPlainText(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex).dataStream));}return;}diff --git a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.tsindex 4565fee378..6c42409508 100644--- a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts+++ b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';+import { BuildTextUtils, CommandType, ICommandService, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';-import { DocSelectionRenderService, getSelectionText } from '@univerjs/docs-ui';+import { DocSelectionRenderService } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { getDT, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';import { ISidebarService } from '@univerjs/ui';@@ -111,7 +111,8 @@ export const StartAddCommentOperation: ICommand = {commandService.executeCommand(ShowCommentPanelOperation.id);const unitId = doc.getUnitId();- const text = getSelectionText(doc.getBody()?.dataStream ?? '', textRange.startOffset, textRange.endOffset);+ const dataStream = (doc.getBody()?.dataStream ?? '').slice(textRange.startOffset, textRange.endOffset);+ const text = BuildTextUtils.transform.getPlainText(dataStream);const subUnitId = DEFAULT_DOC_SUBUNIT_ID;const commentId = '';const comment = {diff --git a/packages/docs-ui/src/basics/__tests__/plain-text.spec.ts b/packages/docs-ui/src/basics/__tests__/plain-text.spec.tsdeleted file mode 100644index a846cbde14..0000000000--- a/packages/docs-ui/src/basics/__tests__/plain-text.spec.ts+++ /dev/null@@ -1,30 +0,0 @@-/**- * 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 { describe, expect, it } from 'vitest';-import { getPlainTextFormDocument } from '../plain-text';--describe('Test getPlainTextFormDocument', () => {- it('should return plain text without special tags', () => {- expect(getPlainTextFormDocument({- body: {- dataStream: '\x1E123\x1F\r\n',- },- id: '',- documentStyle: {},- })).toEqual('123');- });-});diff --git a/packages/docs-ui/src/basics/plain-text.ts b/packages/docs-ui/src/basics/plain-text.tsdeleted file mode 100644index ad1ce35111..0000000000--- a/packages/docs-ui/src/basics/plain-text.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * 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 { DataStreamTreeTokenType } from '@univerjs/core';-import type { IDocumentBody, IDocumentData } from '@univerjs/core';--export const getPlainText = (text: string) => {- return text.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')- .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');-};--/**- * get plain text from rich-text- */-export const getPlainTextFormBody = (body: IDocumentBody) => {- let str = body.dataStream;- if (body.dataStream.endsWith('\r\n')) {- str = body.dataStream.slice(0, -2);- }-- return getPlainText(str);-};--/**- * get plain text from rich-text- */-export const getPlainTextFormDocument = (data: IDocumentData) => {- if (!data.body) {- return '';- }- return getPlainTextFormBody(data.body);-};--const tags = [- DataStreamTreeTokenType.PARAGRAPH, // 段落- DataStreamTreeTokenType.SECTION_BREAK, // 章节- DataStreamTreeTokenType.TABLE_START, // 表格开始- DataStreamTreeTokenType.TABLE_ROW_START, // 表格开始- DataStreamTreeTokenType.TABLE_CELL_START, // 表格开始- DataStreamTreeTokenType.TABLE_CELL_END, // 表格开始- DataStreamTreeTokenType.TABLE_ROW_END, // 表格开始- DataStreamTreeTokenType.TABLE_END, // 表格结束- DataStreamTreeTokenType.CUSTOM_RANGE_START, // 自定义范围开始- DataStreamTreeTokenType.CUSTOM_RANGE_END, // 自定义范围结束- DataStreamTreeTokenType.COLUMN_BREAK, // 换列- DataStreamTreeTokenType.PAGE_BREAK, // 换页- DataStreamTreeTokenType.DOCS_END, // 文档结尾- DataStreamTreeTokenType.TAB, // 制表符- DataStreamTreeTokenType.CUSTOM_BLOCK, // 图片 mention 等不参与文档流的场景--];--export function getSelectionText(dataStream: string, start: number, end: number) {- const text = dataStream.slice(start, end);- return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);-}diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex b53245fdec..8cc05e0716 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -23,7 +23,6 @@ export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleexport { addCustomRangeBySelectionFactory, addCustomRangeFactory, deleteCustomRangeFactory } from './basics/custom-range-factory';export * from './basics/docs-view-key';export { hasParagraphInTable } from './basics/paragraph';-export { getPlainText, getPlainTextFormBody, getPlainTextFormDocument, getSelectionText } from './basics/plain-text';export { replaceSelectionFactory } from './basics/replace';export { docDrawingPositionToTransform, transformToDocDrawingPosition } from './basics/transform-position';export { AfterSpaceCommand, EnterCommand, type ITabCommandParams, TabCommand } from './commands/commands/auto-format.command';diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 992ff7edf0..68af054d2e 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import { BuildTextUtils, createIdentifier, CustomRangeType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, getBodySlice, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';+import { BuildTextUtils, createIdentifier, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, getBodySlice, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';-import type { ICustomRange, IDisposable, IDocumentBody, IDocumentData, IParagraph, Nullable } from '@univerjs/core';+import type { IDisposable, IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';import { CutContentCommand, InnerPasteCommand } from '../../commands/commands/clipboard.inner.command';import { getCursorWhenDelete } from '../../commands/commands/delete.command';@@ -135,7 +135,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ// Paste in sheet editing mode without paste style, so we give textRuns empty array;if (this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId() === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {if (text) {- const textDocData = this._generateBody(text);+ const textDocData = BuildTextUtils.transform.fromPlainText(text);return this._paste({ body: textDocData });} else {partDocData.body!.textRuns = [];@@ -416,69 +416,10 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}- private _generateBody(text: string): IDocumentBody {- // Convert all \n to \r, because we use \r to indicate paragraph break.- const dataStream = text.replace(/\n/g, '\r').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');- const paragraphs: IParagraph[] = [];- const customRanges: ICustomRange[] = [];- let cursor = 0;- let newDataStream = '';- let linkCount = 0;-- const loopParagraph = (i: number, insertP = true) => {- const paragraphText = dataStream.slice(cursor, i);- if (Tools.isLegalUrl(paragraphText)) {- const id = generateRandomId();- const urlText = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${paragraphText}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;- const range: ICustomRange = {- startIndex: cursor + linkCount * 2,- endIndex: cursor + linkCount * 2 + urlText.length - 1,- rangeId: id,- rangeType: CustomRangeType.HYPERLINK,- properties: {- url: text,- },- };- customRanges.push(range);- newDataStream += urlText;- cursor = i + 1;- linkCount++;- if (insertP) {- newDataStream += '\r';- paragraphs.push({ startIndex: i + linkCount * 2 });- }- } else {- newDataStream += dataStream.slice(cursor, i + 1);- cursor = i + 1;- if (insertP) {- paragraphs.push({ startIndex: i + linkCount * 2 });- }- }- };-- let end = 0;- for (let i = 0; i < dataStream.length; i++) {- if (dataStream[i] === '\r') {- loopParagraph(i);- end = i;- }- }-- if (end !== dataStream.length - 1) {- loopParagraph(dataStream.length, false);- }-- return {- dataStream: newDataStream,- paragraphs,- customRanges,- };- }-private _genDocDataFromHtmlAndText(html?: string, text?: string): Partial<IDocumentData> {if (!html) {if (text) {- const body = this._generateBody(text);+ const body = BuildTextUtils.transform.fromPlainText(text);return { body };} else {diff --git a/packages/engine-formula/src/engine/utils/cell.ts b/packages/engine-formula/src/engine/utils/cell.tsindex 6773aa639c..8ce28bdfd8 100644--- a/packages/engine-formula/src/engine/utils/cell.ts+++ b/packages/engine-formula/src/engine/utils/cell.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DataStreamTreeTokenType, DEFAULT_EMPTY_DOCUMENT_VALUE } from '@univerjs/core';+import { BuildTextUtils } from '@univerjs/core';import type { ICellData, Nullable } from '@univerjs/core';export function getCellValue(cell: Nullable<ICellData>) {@@ -22,7 +22,6 @@ export function getCellValue(cell: Nullable<ICellData>) {return 0;}- // TODO: @weird94 this method is need to unified to a same handler functionif (cell?.p) {const body = cell?.p.body;@@ -31,12 +30,7 @@ export function getCellValue(cell: Nullable<ICellData>) {}const data = body.dataStream;- const lastString = data.substring(data.length - 2, data.length);- const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ?- data.substring(0, data.length - 2)- .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')- .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '')- : data;+ const newDataStream = BuildTextUtils.transform.getPlainText(data);return newDataStream;}diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.tsindex d7b53f3524..479c5c8bcc 100644--- a/packages/engine-formula/src/functions/base-function.ts+++ b/packages/engine-formula/src/functions/base-function.ts@@ -14,26 +14,26 @@* limitations under the License.*/-import type { IRange, Nullable } from '@univerjs/core';import { Disposable } from '@univerjs/core';+import type { IRange, Nullable } from '@univerjs/core';import { ErrorType } from '../basics/error-type';-import type { IFunctionNames } from '../basics/function';-import { compareToken } from '../basics/token';-import type { BaseReferenceObject, FunctionVariantType, NodeValueType } from '../engine/reference-object/base-reference-object';-import type { ArrayBinarySearchType } from '../engine/utils/compare';-import { ArrayOrderSearchType } from '../engine/utils/compare';-import type { ArrayValueObject } from '../engine/value-object/array-value-object';-import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';-import { NullValueObject, NumberValueObject, type PrimitiveValueType } from '../engine/value-object/primitive-object';-import { convertTonNumber } from '../engine/utils/value-object';-import { createNewArray } from '../engine/utils/array-object';-import { serializeRangeToRefString } from '../engine/utils/reference';import { REFERENCE_REGEX_SINGLE_COLUMN, REFERENCE_REGEX_SINGLE_ROW, REFERENCE_SINGLE_RANGE_REGEX } from '../basics/regex';+import { compareToken } from '../basics/token';import { CellReferenceObject } from '../engine/reference-object/cell-reference-object';-import { RowReferenceObject } from '../engine/reference-object/row-reference-object';import { ColumnReferenceObject } from '../engine/reference-object/column-reference-object';import { RangeReferenceObject } from '../engine/reference-object/range-reference-object';+import { RowReferenceObject } from '../engine/reference-object/row-reference-object';+import { createNewArray } from '../engine/utils/array-object';+import { ArrayOrderSearchType } from '../engine/utils/compare';+import { serializeRangeToRefString } from '../engine/utils/reference';+import { convertTonNumber } from '../engine/utils/value-object';+import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';+import { NullValueObject, NumberValueObject, type PrimitiveValueType } from '../engine/value-object/primitive-object';+import type { IFunctionNames } from '../basics/function';+import type { BaseReferenceObject, FunctionVariantType, NodeValueType } from '../engine/reference-object/base-reference-object';+import type { ArrayBinarySearchType } from '../engine/utils/compare';+import type { ArrayValueObject } from '../engine/value-object/array-value-object';import type { IDefinedNameMapItem } from '../services/defined-names.service';export class BaseFunction extends Disposable {diff --git a/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.tsindex 94023c944d..afd7a5560f 100644--- a/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts@@ -18,10 +18,10 @@ import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../../basics/error-type';import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';-import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';import { NumberValueObject } from '../../../../engine/value-object/primitive-object';import { FUNCTION_NAMES_LOOKUP } from '../../function-names';import { Hlookup } from '../index';+import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';const arrayValueObject1 = ArrayValueObject.create(/*ts*/ `{1,2,3,4,5,6,7,8;diff --git a/packages/engine-formula/src/functions/lookup/lookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/lookup/__tests__/index.spec.tsindex 44bb7cc465..d13d253301 100644--- a/packages/engine-formula/src/functions/lookup/lookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/lookup/__tests__/index.spec.ts@@ -18,10 +18,10 @@ import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../../basics/error-type';import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';-import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';import { FUNCTION_NAMES_LOOKUP } from '../../function-names';import { Lookup } from '../index';+import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';const arrayValueObject1 = ArrayValueObject.create(/*ts*/ `{1, "First";diff --git a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.tsindex 498ea0d286..c06496d12e 100644--- a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts@@ -20,9 +20,9 @@ import { ErrorType } from '../../../../basics/error-type';import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';import { type BaseValueObject, ErrorValueObject } from '../../../../engine/value-object/base-value-object';import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';+import { getObjectValue } from '../../../__tests__/create-function-test-bed';import { FUNCTION_NAMES_LOOKUP } from '../../function-names';import { Vlookup } from '../index';-import { getObjectValue } from '../../../__tests__/create-function-test-bed';const arrayValueObject1 = ArrayValueObject.create(/*ts*/ `{1, "First";diff --git a/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.tsindex 9f615cfeb2..d1f4081a12 100644--- a/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts@@ -16,8 +16,8 @@import { describe, expect, it } from 'vitest';+import { ErrorType } from '../../../../basics/error-type';import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';-import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';import {NullValueObject,NumberValueObject,@@ -25,7 +25,7 @@ import {} from '../../../../engine/value-object/primitive-object';import { FUNCTION_NAMES_LOOKUP } from '../../function-names';import { Xlookup } from '../index';-import { ErrorType } from '../../../../basics/error-type';+import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';const arrayValueObject1 = ArrayValueObject.create(/*ts*/ `{1, "First", 100, 89;diff --git a/packages/engine-formula/src/functions/math/function-map.ts b/packages/engine-formula/src/functions/math/function-map.tsindex 2cead63f69..7dc524b471 100644--- a/packages/engine-formula/src/functions/math/function-map.ts+++ b/packages/engine-formula/src/functions/math/function-map.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import { FUNCTION_NAMES_MATH } from './function-names';import { Abs } from './abs';import { Acos } from './acos';import { Acosh } from './acosh';@@ -46,6 +45,7 @@ import { Factdouble } from './factdouble';import { Floor } from './floor';import { FloorMath } from './floor-math';import { FloorPrecise } from './floor-precise';+import { FUNCTION_NAMES_MATH } from './function-names';import { Gcd } from './gcd';import { Int } from './int';import { Lcm } from './lcm';@@ -73,8 +73,8 @@ import { Rounddown } from './rounddown';import { Roundup } from './roundup';import { Sec } from './sec';import { Sech } from './sech';-import { Seriessum } from './seriessum';import { Sequence } from './sequence';+import { Seriessum } from './seriessum';import { Sign } from './sign';import { Sin } from './sin';import { Sinh } from './sinh';diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.editor.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.editor.controller.tsindex 51be7d17b1..8626b9f06c 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.editor.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.editor.controller.ts@@ -15,6 +15,7 @@*/import {+ BuildTextUtils,Disposable,Inject,LifecycleStages,@@ -22,8 +23,8 @@ import {toDisposable,} from '@univerjs/core';+import { ConditionalFormattingService } from '@univerjs/sheets-conditional-formatting';import { IEditorBridgeService } from '@univerjs/sheets-ui';-import { ConditionalFormattingService, getStringFromDataStream } from '@univerjs/sheets-conditional-formatting';@OnLifecycle(LifecycleStages.Rendered, ConditionalFormattingEditorController)export class ConditionalFormattingEditorController extends Disposable {@@ -52,7 +53,7 @@ export class ConditionalFormattingEditorController extends Disposable {if (result?.style && value?.p) {const keys = Object.keys(result?.style);if (keys.length > 0) {- const v = getStringFromDataStream(value.p);+ const v = BuildTextUtils.transform.getPlainText(value.p.body?.dataStream ?? '');const s = { ...(typeof value.s === 'string' ? context.workbook.getStyles().get(value.s) : value.s) || {} };keys.forEach((key) => {delete s[key as keyof typeof s];diff --git a/packages/sheets-conditional-formatting/src/index.ts b/packages/sheets-conditional-formatting/src/index.tsindex 7c4ee243d4..c328070a8c 100644--- a/packages/sheets-conditional-formatting/src/index.ts+++ b/packages/sheets-conditional-formatting/src/index.ts@@ -14,33 +14,32 @@* limitations under the License.*/-export { UniverSheetsConditionalFormattingPlugin } from './plugin';export * from './base/const';-export * from './models/type';+export { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, type IAddConditionalRuleMutationParams } from './commands/mutations/add-conditional-rule.mutation';+export { DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, type IDeleteConditionalRuleMutationParams } from './commands/mutations/delete-conditional-rule.mutation';+export { ConditionalFormattingFormulaMarkDirty } from './commands/mutations/formula-mark-dirty.mutation';+export { type IMoveConditionalRuleMutationParams, MoveConditionalRuleMutation, MoveConditionalRuleMutationUndoFactory } from './commands/mutations/move-conditional-rule.mutation';+export { type ISetConditionalRuleMutationParams, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from './commands/mutations/set-conditional-rule.mutation';export * from './models/conditional-formatting-rule-model';export * from './models/conditional-formatting-view-model';-export * from './utils/get-string-from-data-stream';-export * from './utils/is-ranges-equal';-export * from './utils/remove-undefined-attr';-export * from './utils/type';-export * from './services/conditional-formatting.service';-export * from './services/calculate-unit/utils';-export * from './services/calculate-unit/type';+export * from './models/icon-map';+export * from './models/type';+export { UniverSheetsConditionalFormattingPlugin } from './plugin';export * from './render/data-bar.render';export * from './render/icon.render';export * from './render/type';-export * from './models/icon-map';+export * from './services/calculate-unit/type';+export * from './services/calculate-unit/utils';+export * from './services/conditional-formatting.service';export * from './services/conditional-formatting-formula.service';-export * from './utils/anchor';-export * from './utils/create-cf-id';// #region - all commands-export { AddConditionalRuleMutationUndoFactory, AddConditionalRuleMutation, type IAddConditionalRuleMutationParams } from './commands/mutations/add-conditional-rule.mutation';-export { DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, type IDeleteConditionalRuleMutationParams } from './commands/mutations/delete-conditional-rule.mutation';-export { ConditionalFormattingFormulaMarkDirty } from './commands/mutations/formula-mark-dirty.mutation';-export { MoveConditionalRuleMutation, MoveConditionalRuleMutationUndoFactory, type IMoveConditionalRuleMutationParams } from './commands/mutations/move-conditional-rule.mutation';-export { SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, type ISetConditionalRuleMutationParams } from './commands/mutations/set-conditional-rule.mutation';+export * from './utils/anchor';+export * from './utils/create-cf-id';+export * from './utils/is-ranges-equal';+export * from './utils/remove-undefined-attr';+export * from './utils/type';// #endregiondiff --git a/packages/sheets-conditional-formatting/src/utils/get-string-from-data-stream.ts b/packages/sheets-conditional-formatting/src/utils/get-string-from-data-stream.tsdeleted file mode 100644index 20edb2aa68..0000000000--- a/packages/sheets-conditional-formatting/src/utils/get-string-from-data-stream.ts+++ /dev/null@@ -1,22 +0,0 @@-/**- * 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 { IDocumentData } from '@univerjs/core';--export const getStringFromDataStream = (data: IDocumentData) => {- const dataStream = data.body?.dataStream.replace(/\r\n$/, '') || '';- return dataStream;-};diff --git a/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts b/packages/sheets-data-validation/src/utils/get-cell-data-origin.tsindex e6b5f41b3b..ad23099a71 100644--- a/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts+++ b/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts@@ -14,28 +14,10 @@* limitations under the License.*/-import { DataStreamTreeTokenType, DEFAULT_EMPTY_DOCUMENT_VALUE, type ICellData, type Nullable } from '@univerjs/core';+import { getOriginCellValue, type ICellData, type Nullable } from '@univerjs/core';export function getCellValueOrigin(cell: Nullable<ICellData>) {- if (cell === null) {- return '';- }-- if (cell?.p) {- const body = cell?.p.body;-- if (body == null) {- return '';- }-- const data = body.dataStream;- const lastString = data.substring(data.length - 2, data.length);- const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;-- return newDataStream.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');- }-- return cell?.v;+ return getOriginCellValue(cell);}export function getStringCellValue(cell: Nullable<ICellData>) {diff --git a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx b/packages/sheets-data-validation/src/views/list-dropdown/index.tsxindex 95b8ced0ab..0cac8bf8b8 100644--- a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx+++ b/packages/sheets-data-validation/src/views/list-dropdown/index.tsx@@ -14,11 +14,10 @@* limitations under the License.*/-import { DataValidationRenderMode, DataValidationType, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';+import { BuildTextUtils, DataValidationRenderMode, DataValidationType, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import { DataValidationModel } from '@univerjs/data-validation';import { RectPopup, Scrollbar } from '@univerjs/design';import { RichTextEditingMutation } from '@univerjs/docs';-import { getPlainTextFormDocument } from '@univerjs/docs-ui';import { DeviceInputEventType } from '@univerjs/engine-render';import { CheckMarkSingle } from '@univerjs/icons';import { SetRangeValuesCommand } from '@univerjs/sheets';@@ -135,7 +134,7 @@ export function ListDropDown(props: IDropdownComponentProps) {if (!unit) {return;}- const text = getPlainTextFormDocument(unit.getSnapshot());+ const text = BuildTextUtils.transform.getPlainText(unit.getSnapshot().body?.dataStream ?? '');setEditingText(text);}});diff --git a/packages/sheets-formula/src/services/function-list/math.ts b/packages/sheets-formula/src/services/function-list/math.tsindex 1c4aec040e..75f9f2749e 100644--- a/packages/sheets-formula/src/services/function-list/math.ts+++ b/packages/sheets-formula/src/services/function-list/math.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { IFunctionInfo } from '@univerjs/engine-formula';import { FUNCTION_NAMES_MATH, FunctionType } from '@univerjs/engine-formula';+import type { IFunctionInfo } from '@univerjs/engine-formula';export const FUNCTION_LIST_MATH: IFunctionInfo[] = [{diff --git a/packages/sheets-hyper-link-ui/src/common/util.ts b/packages/sheets-hyper-link-ui/src/common/util.tsindex bf2dacbaad..23a0743ea4 100644--- a/packages/sheets-hyper-link-ui/src/common/util.ts+++ b/packages/sheets-hyper-link-ui/src/common/util.ts@@ -14,8 +14,7 @@* limitations under the License.*/-import type { ICellData, Nullable } from '@univerjs/core';-import { DEFAULT_EMPTY_DOCUMENT_VALUE, Tools } from '@univerjs/core';+import { Tools } from '@univerjs/core';export function isLegalLink(link: string) {return Tools.isLegalUrl(link);@@ -59,24 +58,3 @@ export function serializeUrl(urlStr: string) {return urlStr;}-export function getCellValueOrigin(cell: Nullable<ICellData>) {- if (cell === null) {- return '';- }-- if (cell?.p) {- const body = cell?.p.body;-- if (body == null) {- return '';- }-- const data = body.dataStream;- const lastString = data.substring(data.length - 2, data.length);- const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;-- return newDataStream;- }-- return cell?.v;-}diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.tsindex 036d10aab9..1324eee2c6 100644--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts@@ -14,19 +14,19 @@* limitations under the License.*/-import type { ISheetLocationBase } from '@univerjs/sheets';-import type { ICanvasPopup } from '@univerjs/sheets-ui';-import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';-import type { DocumentDataModel, ICustomRange, IDisposable, INeedCheckDisposable, ITextRange, Nullable, Workbook } from '@univerjs/core';import { BuildTextUtils, createInternalEditorID, CustomRangeType, Disposable, DOCS_ZEN_EDITOR_UNIT_ID_KEY, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { IEditorService, IRangeSelectorService, IZenZoneService } from '@univerjs/ui';import { BehaviorSubject, Subject } from 'rxjs';+import type { DocumentDataModel, ICustomRange, IDisposable, INeedCheckDisposable, ITextRange, Nullable, Workbook } from '@univerjs/core';import type { IBoundRectNoAngle } from '@univerjs/engine-render';-import { DocCanvasPopManagerService, getPlainText, getPlainTextFormBody, getPlainTextFormDocument } from '@univerjs/docs-ui';-import { IEditorService, IRangeSelectorService, IZenZoneService } from '@univerjs/ui';-import { DocSelectionManagerService } from '@univerjs/docs';-import { CellLinkPopup } from '../views/CellLinkPopup';-import { CellLinkEdit } from '../views/CellLinkEdit';+import type { ISheetLocationBase } from '@univerjs/sheets';+import type { ICanvasPopup } from '@univerjs/sheets-ui';import { HyperLinkEditSourceType } from '../types/enums/edit-source';+import { CellLinkEdit } from '../views/CellLinkEdit';+import { CellLinkPopup } from '../views/CellLinkPopup';export interface IHyperLinkPopup {unitId: string;@@ -200,7 +200,7 @@ export class SheetsHyperLinkPopupService extends Disposable {startOffset: 0,endOffset: body.dataStream.length - 2,collapsed: body.dataStream.length - 2 === 0,- label: getPlainTextFormBody(body),+ label: BuildTextUtils.transform.getPlainText(body.dataStream),};}const links = BuildTextUtils.customRange.getCustomRangesInterestsWithRange(textRange, body.customRanges?.filter((i) => i.rangeType === CustomRangeType.HYPERLINK) ?? []);@@ -214,7 +214,7 @@ export class SheetsHyperLinkPopupService extends Disposable {startOffset: start,endOffset: end,collapsed: start === end,- label: getPlainText(body.dataStream.slice(start, end)),+ label: BuildTextUtils.transform.getPlainText(body.dataStream.slice(start, end)),};}@@ -292,7 +292,7 @@ export class SheetsHyperLinkPopupService extends Disposable {const cell = worksheet?.getCellRaw(link.row, link.col);this._currentEditing$.next({...link,- label: cell?.p ? getPlainTextFormDocument(cell.p) : (cell?.v ?? '').toString(),+ label: cell?.p ? BuildTextUtils.transform.getPlainText(cell.p.body?.dataStream ?? '') : (cell?.v ?? '').toString(),});}}diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsxindex 5ad1fad201..3c0d099f13 100644--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { BuildTextUtils, createInternalEditorID, CustomRangeType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';+import { BuildTextUtils, createInternalEditorID, CustomRangeType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, getOriginCellValue, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';import { Button, FormLayout, Input, Select } from '@univerjs/design';import { DocSelectionManagerService } from '@univerjs/docs';import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeToRefString, serializeRangeWithSheet } from '@univerjs/engine-formula';@@ -28,7 +28,7 @@ import type { ISetSelectionsOperationParams } from '@univerjs/sheets';import { AddHyperLinkCommand, AddRichHyperLinkCommand } from '../../commands/commands/add-hyper-link.command';import { UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '../../commands/commands/update-hyper-link.command';import { CloseHyperLinkPopupOperation } from '../../commands/operations/popup.operations';-import { getCellValueOrigin, isLegalLink, serializeUrl } from '../../common/util';+import { isLegalLink, serializeUrl } from '../../common/util';import { SheetsHyperLinkPopupService } from '../../services/popup.service';import { SheetsHyperLinkResolverService } from '../../services/resolver.service';import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';@@ -85,7 +85,7 @@ export const CellLinkEdit = () => {const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);const cell = worksheet?.getCellRaw(editing.row, editing.col);const range = cell?.p?.body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK && range.properties?.url);- const cellValue = `${getCellValueOrigin(cell) ?? ''}`;+ const cellValue = `${getOriginCellValue(cell) ?? ''}`;if (cell && (cell.p || cellValue)) {setShowLabel(false);}