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(docs-ui): doc custom-range & hyperlink (#3928)

zhangwb18aba7cf591
diff --git a/packages/core/package.json b/packages/core/package.json
index 87690907e0..5295272ea8 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -62,6 +62,7 @@
"dependencies": {
"@univerjs/protocol": "0.1.39-alpha.38",
"@wendellhu/redi": "0.16.1",
+ "fast-diff": "1.3.0",
"kdbush": "^4.0.2",
"lodash-es": "^4.17.21",
"nanoid": "5.0.8",
diff --git a/packages/core/src/docs/data-model/__tests__/replacement.spec.ts b/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
index 6e93c62d2c..2d024876cf 100644
--- a/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import { describe, expect, it } from 'vitest';
+import type { IDocumentBody } from '../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
import { BooleanNumber } from '../../../types/enum/text-style';
import { replaceInDocumentBody } from '../replacement';
-import type { IDocumentBody } from '../../../types/interfaces';
function getTestDocumentBody() {
const documentBody = {
@@ -147,7 +147,7 @@ describe('test case in replaceInDocumentBody utils', () => {
],
} as IDocumentBody;
- expect(replaceInDocumentBody(documentBody, '月色', 'Jocs')).toEqual(expectedBody);
+ expect(replaceInDocumentBody(documentBody, '月色', 'Jocs', true)).toEqual(expectedBody);
});
it('Should replace all `query` to `target` when `target` is empty', () => {
@@ -205,12 +205,12 @@ describe('test case in replaceInDocumentBody utils', () => {
],
} as IDocumentBody;
- expect(replaceInDocumentBody(documentBody, '月色', '')).toEqual(expectedBody);
+ expect(replaceInDocumentBody(documentBody, '月色', '', true)).toEqual(expectedBody);
});
it('Should return the origin body when the query is empty', () => {
const documentBody = getTestDocumentBody();
- expect(replaceInDocumentBody(documentBody, '', 'Jocs')).toEqual(documentBody);
+ expect(replaceInDocumentBody(documentBody, '', 'Jocs', true)).toEqual(documentBody);
});
});
diff --git a/packages/core/src/docs/data-model/replacement.ts b/packages/core/src/docs/data-model/replacement.ts
index b68213bb9c..05fd8c714f 100644
--- a/packages/core/src/docs/data-model/replacement.ts
+++ b/packages/core/src/docs/data-model/replacement.ts
@@ -19,7 +19,8 @@ import { DocumentDataModel } from './document-data-model';
import { JSONX } from './json-x/json-x';
import { TextX } from './text-x/text-x';
-export function replaceInDocumentBody(body: IDocumentBody, query: string, target: string): IDocumentBody {
+// TODO: this function should be replaced by replaceSelection
+export function replaceInDocumentBody(body: IDocumentBody, query: string, target: string, caseSensitive: boolean): IDocumentBody {
if (query === '') {
return body;
}
@@ -36,7 +37,7 @@ export function replaceInDocumentBody(body: IDocumentBody, query: string, target
let index;
// eslint-disable-next-line no-cond-assign
- while ((index = documentDataModel.getBody()!.dataStream.indexOf(query)) >= 0) {
+ while ((index = (caseSensitive ? documentDataModel.getBody()!.dataStream : documentDataModel.getBody()!.dataStream.toLowerCase()).indexOf(query)) >= 0) {
const textX = new TextX();
const jsonX = JSONX.getInstance();
@@ -58,6 +59,15 @@ export function replaceInDocumentBody(body: IDocumentBody, query: string, target
}];
}
+ if (sliceBody?.customRanges?.length) {
+ const customRange = sliceBody.customRanges[0];
+ replaceBody.customRanges = [{
+ ...customRange,
+ startIndex: 0,
+ endIndex: target.length - 1,
+ }];
+ }
+
textX.insert(target.length, replaceBody);
}
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts
index aa033e9ce9..e0d45742c8 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts
@@ -724,7 +724,7 @@ describe('transform()', () => {
dataStream: '',
customRanges: [
{
- startIndex: -1,
+ startIndex: 0,
endIndex: 0,
rangeId: 'rangeId',
rangeType: CustomRangeType.HYPERLINK,
@@ -746,7 +746,7 @@ describe('transform()', () => {
dataStream: '',
customRanges: [
{
- startIndex: -1,
+ startIndex: 0,
endIndex: 0,
rangeId: 'rangeId',
rangeType: CustomRangeType.HYPERLINK,
@@ -768,7 +768,7 @@ describe('transform()', () => {
dataStream: '',
customRanges: [
{
- startIndex: -1,
+ startIndex: 0,
endIndex: 0,
rangeId: 'rangeId',
rangeType: CustomRangeType.HYPERLINK,
@@ -790,7 +790,7 @@ describe('transform()', () => {
dataStream: '',
customRanges: [
{
- startIndex: -1,
+ startIndex: 0,
endIndex: 0,
rangeId: 'rangeId',
rangeType: CustomRangeType.HYPERLINK,
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index e9b014c762..cb7e8cba0e 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -25,9 +25,10 @@ import type {
ISectionBreak,
ITextRun,
} from '../../../../types/interfaces';
+import { shallowEqual } from '../../../../common/equal';
import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../../shared';
import { isSameStyleTextRun } from '../../../../shared/compare';
-import { DataStreamTreeTokenType } from '../../types';
+import { getBodySlice } from '../utils';
export function normalizeTextRuns(textRuns: ITextRun[]) {
const results: ITextRun[] = [];
@@ -314,6 +315,151 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex
}
}
+export function sliceByParagraph(body: IDocumentBody) {
+ const { dataStream, paragraphs = [] } = body;
+ const ranges = [];
+
+ let cursor = 0;
+ for (let i = 0, len = paragraphs.length; i < len; i++) {
+ const paragraph = paragraphs[i];
+ const { startIndex } = paragraph;
+ if (cursor < startIndex) {
+ ranges.push({
+ startOffset: cursor,
+ endOffset: startIndex,
+ });
+ cursor = startIndex;
+ }
+ ranges.push({
+ startOffset: startIndex,
+ endOffset: startIndex + 1,
+ });
+ cursor = startIndex + 1;
+ }
+
+ if (cursor < dataStream.length) {
+ ranges.push({
+ startOffset: cursor,
+ endOffset: dataStream.length,
+ });
+ }
+
+ return ranges.map((range) => getBodySlice(body, range.startOffset, range.endOffset));
+}
+
+const ID_SPLIT_SYMBOL = '$';
+const getRootId = (id: string) => id.split(ID_SPLIT_SYMBOL)[0];
+
+export function mergeContinuousRanges(ranges: ICustomRange[]): ICustomRange[] {
+ if (ranges.length <= 1) return ranges;
+ ranges.sort((a, b) => a.startIndex - b.startIndex);
+
+ const mergedRanges: ICustomRange[] = [];
+ let currentRange = { ...ranges[0] };
+ currentRange.rangeId = getRootId(currentRange.rangeId);
+
+ for (let i = 1; i < ranges.length; i++) {
+ const nextRange = ranges[i];
+ nextRange.rangeId = getRootId(nextRange.rangeId);
+ if (
+ nextRange.rangeId === currentRange.rangeId &&
+ shallowEqual(currentRange.properties, nextRange.properties) &&
+ currentRange.endIndex + 1 >= nextRange.startIndex
+ ) {
+ // Merge continuous ranges with same rangeId
+ currentRange.endIndex = nextRange.endIndex;
+ } else {
+ // Push current range and start a new one
+ mergedRanges.push(currentRange);
+ currentRange = { ...nextRange };
+ }
+ }
+ // Push the last range
+ mergedRanges.push(currentRange);
+
+ const idMap: Record<string, number> = Object.create(null);
+ for (let i = 0, len = mergedRanges.length; i < len; i++) {
+ const range = mergedRanges[i];
+ const id = range.rangeId;
+ if (idMap[id]) {
+ range.rangeId = `${id}${ID_SPLIT_SYMBOL}${idMap[id]}`;
+ idMap[id] = idMap[id] + 1;
+ } else {
+ idMap[id] = 1;
+ }
+ }
+
+ return mergedRanges;
+}
+
+export function splitCustomRangesByIndex(customRanges: ICustomRange[], currentIndex: number) {
+ const matchedCustomRangeIndex = customRanges.findIndex((c) => c.startIndex < currentIndex && c.endIndex >= currentIndex);
+ const matchedCustomRange = customRanges[matchedCustomRangeIndex];
+
+ if (matchedCustomRange) {
+ customRanges.splice(matchedCustomRangeIndex, 1, {
+ rangeId: matchedCustomRange.rangeId,
+ rangeType: matchedCustomRange.rangeType,
+ startIndex: matchedCustomRange.startIndex,
+ endIndex: currentIndex - 1,
+ properties: { ...matchedCustomRange.properties },
+ },
+ {
+ rangeId: matchedCustomRange.rangeId,
+ rangeType: matchedCustomRange.rangeType,
+ startIndex: currentIndex,
+ endIndex: matchedCustomRange.endIndex,
+ properties: { ...matchedCustomRange.properties },
+ });
+ }
+}
+
+export function mergeContinuousDecorations(ranges: ICustomDecoration[]): ICustomDecoration[] {
+ if (ranges.length <= 1) return ranges;
+ ranges.sort((a, b) => a.startIndex - b.startIndex);
+
+ const mergedRanges: ICustomDecoration[] = [];
+ let currentRange = { ...ranges[0] };
+
+ for (let i = 1; i < ranges.length; i++) {
+ const nextRange = ranges[i];
+ if (
+ nextRange.id === currentRange.id &&
+ currentRange.endIndex + 1 >= nextRange.startIndex
+ ) {
+ // Merge continuous ranges with same rangeId
+ currentRange.endIndex = nextRange.endIndex;
+ } else {
+ // Push current range and start a new one
+ mergedRanges.push(currentRange);
+ currentRange = { ...nextRange };
+ }
+ }
+ // Push the last range
+ mergedRanges.push(currentRange);
+ return mergedRanges;
+}
+
+export function splitCustomDecroatesByIndex(customDecorations: ICustomDecoration[], currentIndex: number) {
+ const matcheds = customDecorations.filter((c) => c.startIndex < currentIndex && c.endIndex >= currentIndex);
+
+ matcheds.forEach((matched) => {
+ const index = customDecorations.indexOf(matched);
+ customDecorations.splice(index, 1, {
+ id: matched.id,
+ type: matched.type,
+ startIndex: matched.startIndex,
+ endIndex: currentIndex - 1,
+ },
+ {
+ id: matched.id,
+ type: matched.type,
+ startIndex: currentIndex,
+ endIndex: matched.endIndex,
+ });
+ });
+}
+
export function insertCustomRanges(
body: IDocumentBody,
insertBody: IDocumentBody,
@@ -325,64 +471,32 @@ export function insertCustomRanges(
}
const { customRanges } = body;
- const customRangeMap: Record<string, ICustomRange> = {};
+ splitCustomRangesByIndex(customRanges, currentIndex);
+
for (let i = 0, len = customRanges.length; i < len; i++) {
const customRange = customRanges[i];
- customRangeMap[customRange.rangeId] = customRange;
- const { startIndex, endIndex } = customRange;
+ const { startIndex } = customRange;
+ // move custom range when insert text before it
if (startIndex >= currentIndex) {
customRange.startIndex += textLength;
customRange.endIndex += textLength;
- } else if (endIndex > currentIndex - 1) {
- customRange.endIndex += textLength;
}
}
- const currentRange = customRanges.find((range) => range.startIndex > currentIndex && range.endIndex < currentIndex);
-
- if (currentRange) {
- return;
- }
-
- const insertCustomRanges: ICustomRange[] = [];
+ const insertRanges: ICustomRange[] = [];
if (insertBody.customRanges) {
for (let i = 0, len = insertBody.customRanges.length; i < len; i++) {
const customRange = insertBody.customRanges[i];
- const oldCustomRange = customRangeMap[customRange.rangeId];
-
customRange.startIndex += currentIndex;
customRange.endIndex += currentIndex;
- if (oldCustomRange) {
- if (oldCustomRange.startIndex <= customRange.startIndex &&
- oldCustomRange.endIndex >= customRange.endIndex) {
- continue;
- }
-
- const isClosed =
- body.dataStream[oldCustomRange.startIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_START &&
- body.dataStream[oldCustomRange.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END;
-
- if (isClosed) {
- insertCustomRanges.push(customRange);
- continue;
- }
-
- // old is start
- if (body.dataStream[oldCustomRange.startIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- oldCustomRange.endIndex = customRange.endIndex;
- continue;
- }
- if (body.dataStream[oldCustomRange.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- oldCustomRange.startIndex = customRange.startIndex;
- continue;
- }
- }
- insertCustomRanges.push(customRange);
+ // new custom range
+ insertRanges.push(customRange);
}
- customRanges.push(...insertCustomRanges);
- customRanges.sort(sortRulesFactory('startIndex'));
+ customRanges.push(...insertRanges);
}
+
+ body.customRanges = mergeContinuousRanges(customRanges);
}
interface IIndexRange {
@@ -436,33 +550,34 @@ export function insertCustomDecorations(
if (!body.customDecorations) {
body.customDecorations = [];
}
+
const { customDecorations } = body;
- if (textLength > 0) {
- for (let i = 0, len = customDecorations.length; i < len; i++) {
- const customDecoration = customDecorations[i];
- const { startIndex, endIndex } = customDecoration;
- if (startIndex >= currentIndex) {
- customDecoration.startIndex += textLength;
- customDecoration.endIndex += textLength;
- } else if (endIndex > currentIndex - 1) {
- customDecoration.endIndex += textLength;
- }
+ splitCustomDecroatesByIndex(customDecorations, currentIndex);
+
+ for (let i = 0, len = customDecorations.length; i < len; i++) {
+ const customDecoration = customDecorations[i];
+ const { startIndex } = customDecoration;
+ // move custom range when insert text before it
+ if (startIndex >= currentIndex) {
+ customDecoration.startIndex += textLength;
+ customDecoration.endIndex += textLength;
}
}
+ const insertRanges: ICustomDecoration[] = [];
if (insertBody.customDecorations) {
- const insertCustomDecorations: ICustomDecoration[] = [];
for (let i = 0, len = insertBody.customDecorations.length; i < len; i++) {
const customDecoration = insertBody.customDecorations[i];
- insertCustomDecorations.push(customDecoration);
customDecoration.startIndex += currentIndex;
customDecoration.endIndex += currentIndex;
+ // new custom range
+ insertRanges.push(customDecoration);
}
- customDecorations.push(...insertCustomDecorations);
- body.customDecorations = mergeDecorations(customDecorations);
- body.customDecorations.sort(sortRulesFactory('startIndex'));
+ customDecorations.push(...insertRanges);
}
+
+ body.customDecorations = mergeContinuousDecorations(customDecorations);
}
// eslint-disable-next-line max-lines-per-function
@@ -731,7 +846,6 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
const { customRanges } = body;
const startIndex = currentIndex;
-
const endIndex = currentIndex + textLength - 1;
const removeCustomRanges: ICustomRange[] = [];
@@ -740,15 +854,11 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
for (let i = 0, len = customRanges.length; i < len; i++) {
const customRange = customRanges[i];
const { startIndex: st, endIndex: ed } = customRange;
- // delete custom-range start means delete custom-range
- if (startIndex <= st && endIndex >= st) {
- removeCustomRanges.push({
- ...customRange,
- startIndex: st - currentIndex,
- endIndex: ed - currentIndex,
- });
+ // delete decoration
+ if (st >= startIndex && ed <= endIndex) {
+ removeCustomRanges.push(customRange);
continue;
- } else if (st <= startIndex && ed >= endIndex) {
+ } else if (Math.max(startIndex, st) <= Math.min(endIndex, ed)) {
const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
customRange.startIndex = segments[0];
customRange.endIndex = segments[1];
@@ -758,9 +868,9 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
}
newCustomRanges.push(customRange);
}
- body.customRanges = newCustomRanges;
- }
+ body.customRanges = mergeContinuousRanges(newCustomRanges);
+ }
return removeCustomRanges;
}
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
index 3af6f6cabb..9917ec44fb 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
@@ -15,34 +15,35 @@
*/
import type { Nullable } from '../../../../shared';
-import type {
- ICustomBlock,
- ICustomDecoration,
- ICustomRange,
- ICustomTable,
- IDocumentBody,
- IParagraph,
- ISectionBreak,
- ITextRun,
-} from '../../../../types/interfaces';
import { Tools, UpdateDocsAttributeType } from '../../../../shared';
+import {
+ CustomDecorationType,
+ type ICustomBlock,
+ type ICustomDecoration,
+ type ICustomRange,
+ type ICustomTable,
+ type IDocumentBody,
+ type IParagraph,
+ type ISectionBreak,
+ type ITextRun,
+} from '../../../../types/interfaces';
import { PresetListType } from '../../preset-list-type';
import {
deleteCustomBlocks,
- deleteCustomDecorations,
- deleteCustomRanges,
deleteParagraphs,
deleteSectionBreaks,
deleteTables,
deleteTextRuns,
insertCustomBlocks,
- insertCustomDecorations,
- insertCustomRanges,
insertParagraphs,
insertSectionBreaks,
insertTables,
insertTextRuns,
+ mergeContinuousDecorations,
+ mergeContinuousRanges,
normalizeTextRuns,
+ splitCustomDecroatesByIndex,
+ splitCustomRangesByIndex,
} from './common';
export function updateAttribute(
@@ -438,6 +439,7 @@ function updateTables(
}
// retain
+
function updateCustomRanges(
body: IDocumentBody,
updateBody: IDocumentBody,
@@ -448,21 +450,38 @@ function updateCustomRanges(
if (!body.customRanges) {
body.customRanges = [];
}
- const { customRanges } = body;
+ splitCustomRangesByIndex(body.customRanges, currentIndex);
+ splitCustomRangesByIndex(body.customRanges, currentIndex + textLength);
+ const start = currentIndex;
+ const end = currentIndex + textLength - 1;
const { customRanges: updateDataCustomRanges } = updateBody;
+ const newCustomRanges: ICustomRange[] = [];
+ const relativeCustomRanges = new Map<string, ICustomRange>();
+ body.customRanges.forEach((customRange) => {
+ const { startIndex, endIndex } = customRange;
+ if (startIndex >= start && endIndex <= end) {
+ relativeCustomRanges.set(customRange.rangeId, customRange);
+ } else {
+ newCustomRanges.push(customRange);
+ }
+ });
- if (customRanges == null || updateDataCustomRanges == null) {
- return;
- }
+ const removeCustomRanges: ICustomRange[] = [];
- let removeCustomRanges: ICustomRange[] = [];
- if (coverType === UpdateDocsAttributeType.REPLACE) {
- removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);
+ if (!updateDataCustomRanges) {
+ return [];
}
-
- // retain
- insertCustomRanges(body, updateBody, 0, currentIndex);
+ updateBody.customRanges?.forEach((customRange) => {
+ const { startIndex, endIndex } = customRange;
+ newCustomRanges.push({
+ ...customRange,
+ startIndex: startIndex + currentIndex,
+ endIndex: endIndex + currentIndex,
+ });
+ });
+
+ body.customRanges = mergeContinuousRanges(newCustomRanges);
return removeCustomRanges;
}
@@ -478,11 +497,55 @@ function updateCustomDecorations(
body.customDecorations = [];
}
- let removeCustomDecorations: ICustomDecoration[] = [];
+ splitCustomDecroatesByIndex(body.customDecorations, currentIndex);
+ splitCustomDecroatesByIndex(body.customDecorations, currentIndex + textLength);
+ const removeCustomDecorations: ICustomDecoration[] = [];
+ const { customDecorations } = body;
+ const { customDecorations: updateDataCustomDecorations = [] } = updateBody;
+
if (coverType === UpdateDocsAttributeType.REPLACE) {
- removeCustomDecorations = deleteCustomDecorations(body, textLength, currentIndex, false);
+ for (let index = 0; index < customDecorations.length; index++) {
+ const customDecoration = customDecorations[index];
+ const { startIndex, endIndex } = customDecoration;
+ if (startIndex >= currentIndex && endIndex <= currentIndex + textLength - 1) {
+ removeCustomDecorations.push(customDecoration);
+ }
+ }
+
+ updateDataCustomDecorations?.forEach((customDecoration) => {
+ const { startIndex, endIndex } = customDecoration;
+ customDecorations.push({
+ ...customDecoration,
+ startIndex: startIndex + currentIndex,
+ endIndex: endIndex + currentIndex,
+ });
+ });
+ } else {
+ for (const updateCustomDecoration of updateDataCustomDecorations) {
+ const { id } = updateCustomDecoration;
+ if (updateCustomDecoration.type === CustomDecorationType.DELTED) {
+ const oldCustomDecorations = customDecorations.filter((d) => d.id === id);
+ if (oldCustomDecorations.length) {
+ removeCustomDecorations.push(...oldCustomDecorations);
+ }
+ } else {
+ customDecorations.push({
+ ...updateCustomDecoration,
+ startIndex: updateCustomDecoration.startIndex + currentIndex,
+ endIndex: updateCustomDecoration.endIndex + currentIndex,
+ });
+ }
+ }
+ }
+
+ for (const removeCustomDecoration of removeCustomDecorations) {
+ const { id } = removeCustomDecoration;
+ const index = customDecorations.findIndex((d) => d.id === id);
+ if (index !== -1) {
+ customDecorations.splice(index, 1);
+ }
}
- insertCustomDecorations(body, updateBody, 0, currentIndex);
+ body.customDecorations = mergeContinuousDecorations(customDecorations);
return removeCustomDecorations;
}
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.ts
index 99c84b5839..1a9563c58e 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
@@ -17,8 +17,7 @@
import type { ITextRange } from '../../../../../sheets/typedef';
import { describe, expect, it } from 'vitest';
import { CustomRangeType, type ICustomRange } from '../../../../../types/interfaces';
-import { DataStreamTreeTokenType } from '../../../types';
-import { excludePointsFromRange, getCustomRangesInterestsWithSelection, shouldDeleteCustomRange } from '../custom-range';
+import { excludePointsFromRange, getCustomRangesInterestsWithSelection } from '../custom-range';
describe('excludePointsFromRange function', () => {
it('should handle empty points array', () => {
@@ -112,8 +111,8 @@ describe('getCustomRangesInterestsWithSelection 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 },
+ { startIndex: 0, endIndex: 4, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 11, endIndex: 15, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
];
expect(getCustomRangesInterestsWithSelection(range, customRanges)).toEqual([]);
});
@@ -121,20 +120,20 @@ describe('getCustomRangesInterestsWithSelection function', () => {
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 },
+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
];
expect(getCustomRangesInterestsWithSelection(range, customRanges)).toEqual([
- { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK },
- { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK },
+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
]);
});
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 },
+ { startIndex: 0, endIndex: 4, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 5, endIndex: 10, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
];
expect(getCustomRangesInterestsWithSelection(range, customRanges)).toEqual([]);
});
@@ -142,65 +141,15 @@ describe('getCustomRangesInterestsWithSelection function', () => {
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 },
+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 14, endIndex: 20, rangeId: '3', rangeType: CustomRangeType.HYPERLINK, properties: {} },
];
expect(getCustomRangesInterestsWithSelection(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 },
+ { startIndex: 0, endIndex: 6, rangeId: '1', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 8, endIndex: 12, rangeId: '2', rangeType: CustomRangeType.HYPERLINK, properties: {} },
+ { startIndex: 14, endIndex: 20, rangeId: '3', rangeType: CustomRangeType.HYPERLINK, properties: {} },
]);
});
});
-
-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__/textX.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/textX.ts
new file mode 100644
index 0000000000..e217df521b
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/textX.ts
@@ -0,0 +1,79 @@
+/**
+ * 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 { CustomRangeType, type IDocumentBody } from '../../../../../types/interfaces';
+import { DocumentDataModel } from '../../../document-data-model';
+import { TextX } from '../../text-x';
+import { replaceSelectionTextX } from '../text-x-utils';
+
+describe('test textX function', () => {
+ const text = 'What is univer and how to use it?\r\n';
+ it('should replace the selection', () => {
+ const body: IDocumentBody = {
+ dataStream: 'What is univer and how to use it?\r\n',
+ paragraphs: [
+ {
+ startIndex: text.length - 1,
+ },
+ ],
+ customRanges: [
+ {
+ startIndex: 0,
+ endIndex: 7,
+ rangeId: '1',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: 'https://univer.ai',
+ },
+ },
+ ],
+ };
+
+ const insertBody: IDocumentBody = {
+ dataStream: 'what are',
+ customRanges: [
+ {
+ startIndex: 0,
+ endIndex: 8,
+ rangeId: '1',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: 'https://univer.ai/haha',
+ },
+ },
+ ],
+ };
+
+ const doc = new DocumentDataModel({
+ body,
+ });
+
+ const textX = replaceSelectionTextX({
+ selection: { startOffset: 0, endOffset: 8, collapsed: false },
+ body: insertBody,
+ doc,
+ });
+ expect(textX).toBeTruthy();
+ if (textX) {
+ TextX.apply(body, textX.serialize());
+ expect(body.dataStream).toEqual('what are univer and how to use it?\r\n');
+ expect(body.customRanges?.[0].properties?.url).toEqual('https://univer.ai/haha');
+ expect(body.customRanges?.[0].startIndex).toEqual(0);
+ expect(body.customRanges?.[0].endIndex).toEqual(8);
+ }
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
index 0be5be0d0c..14a891142c 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
@@ -15,13 +15,8 @@
*/
import type { ITextRange } from '../../../../sheets/typedef';
-import type { ICustomRange } from '../../../../types/interfaces';
+import type { CustomRangeType, ICustomRange, IDocumentBody } from '../../../../types/interfaces';
import { generateRandomId, Tools } from '../../../../shared';
-import { DataStreamTreeTokenType } from '../../types';
-
-export function isCustomRangeSplitSymbol(text: string) {
- return text === DataStreamTreeTokenType.CUSTOM_RANGE_END || text === DataStreamTreeTokenType.CUSTOM_RANGE_START;
-}
/**
* Check if two ranges intersect
@@ -39,31 +34,6 @@ export function isIntersecting(line1Start: number, line1End: number, line2Start:
return false;
}
-export function shouldDeleteCustomRange(deleteStart: number, deleteLen: number, customRange: ICustomRange, dataStream: string) {
- const dataStreamSlice = dataStream.slice(customRange.startIndex + 1, customRange.endIndex);
- const start = Math.max(deleteStart - (customRange.startIndex + 1), 0);
- const end = (deleteStart + deleteLen - 1) - (customRange.startIndex + 1);
-
- if (end < 0) {
- return false;
- }
-
- if (start === 0 && end >= dataStreamSlice.length) {
- return true;
- }
-
- const result = dataStreamSlice.slice(0, start) + dataStreamSlice.slice(start + deleteLen);
-
- for (let i = 0, len = result.length; i < len; i++) {
- const letter = result[i];
- if (!isCustomRangeSplitSymbol(letter)) {
- return false;
- }
- }
-
- return true;
-}
-
export function getCustomRangesInterestsWithSelection(range: ITextRange, customRanges: ICustomRange[]) {
const result: ICustomRange[] = [];
for (let i = 0, len = customRanges.length; i < len; i++) {
@@ -112,3 +82,33 @@ export function excludePointsFromRange(range: [number, number], points: number[]
return newRanges;
}
+export function getIntersectingCustomRanges(startIndex: number, endIndex: number, customRanges: ICustomRange[], rangeType?: CustomRangeType) {
+ const relativeCustomRanges = [];
+
+ for (let i = 0, len = customRanges.length; i < len; i++) {
+ const customRange = customRanges[i];
+ // intersect
+ if ((rangeType === undefined || customRange.rangeType === rangeType) && Math.max(customRange.startIndex, startIndex) <= Math.min(customRange.endIndex, endIndex)) {
+ relativeCustomRanges.push({ ...customRange });
+ }
+
+ // optimize
+ if (customRange.startIndex > endIndex) {
+ break;
+ }
+ }
+
+ return relativeCustomRanges;
+}
+
+export function getSelectionForAddCustomRange(range: ITextRange, body: IDocumentBody) {
+ const ranges = getIntersectingCustomRanges(range.startOffset, range.collapsed ? range.startOffset : range.endOffset - 1, body.customRanges ?? []);
+ const startOffset = Math.min(range.startOffset, (ranges[0]?.startIndex ?? Infinity));
+ const endOffset = Math.max(range.endOffset, (ranges[ranges.length - 1]?.endIndex ?? -Infinity) + 1);
+
+ return {
+ startOffset,
+ endOffset,
+ collapsed: startOffset === endOffset,
+ };
+}
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.ts
index 67adbffed4..4cc24b0dc6 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
@@ -14,34 +14,26 @@
* limitations under the License.
*/
-import { copyCustomRange, getCustomRangesInterestsWithSelection, isIntersecting, shouldDeleteCustomRange } from './custom-range';
+import { copyCustomRange, getCustomRangesInterestsWithSelection, isIntersecting } from './custom-range';
import { changeParagraphBulletNestLevel, setParagraphBullet, switchParagraphBullet, toggleChecklistParagraph } from './paragraph';
import { fromPlainText, getPlainText, isEmptyDocument } from './parse';
-import { getDeleteSelection, getInsertSelection, getRetainAndDeleteFromReplace, isSegmentIntersects, makeSelection, normalizeSelection } from './selection';
-import { addCustomRangeTextX, deleteCustomRangeTextX, getRetainAndDeleteAndExcludeLineBreak, replaceSelectionTextX } from './text-x-utils';
+import { isSegmentIntersects, makeSelection, normalizeSelection } from './selection';
+import { addCustomRangeTextX, deleteCustomRangeTextX, deleteSelectionTextX, replaceSelectionTextX } from './text-x-utils';
export class BuildTextUtils {
static customRange = {
add: addCustomRangeTextX,
delete: deleteCustomRangeTextX,
-
copyCustomRange,
getCustomRangesInterestsWithSelection,
- shouldDeleteCustomRange,
-
isIntersecting,
};
static selection = {
replace: replaceSelectionTextX,
-
makeSelection,
normalizeSelection,
- getDeleteSelection,
- getInsertSelection,
-
- getDeleteActions: getRetainAndDeleteFromReplace,
- getDeleteExcludeLastLineBreakActions: getRetainAndDeleteAndExcludeLineBreak,
+ delete: deleteSelectionTextX,
};
static range = {
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.ts
index e33e4d1159..e0ec711ec3 100644
--- 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.ts
@@ -28,8 +28,6 @@ const tags = [
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, // 文档结尾
@@ -57,16 +55,15 @@ export const fromPlainText = (text: string): IDocumentBody => {
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 urlText = `${paragraphText}`;
const range: ICustomRange = {
- startIndex: cursor + linkCount * 2,
- endIndex: cursor + linkCount * 2 + urlText.length - 1,
+ startIndex: cursor,
+ endIndex: cursor + urlText.length - 1,
rangeId: id,
rangeType: CustomRangeType.HYPERLINK,
properties: {
@@ -76,16 +73,15 @@ export const fromPlainText = (text: string): IDocumentBody => {
customRanges.push(range);
newDataStream += urlText;
cursor = i + 1;
- linkCount++;
if (insertP) {
newDataStream += '\r';
- paragraphs.push({ startIndex: i + linkCount * 2 });
+ paragraphs.push({ startIndex: i });
}
} else {
newDataStream += dataStream.slice(cursor, i + 1);
cursor = i + 1;
if (insertP) {
- paragraphs.push({ startIndex: i + linkCount * 2 });
+ paragraphs.push({ startIndex: i });
}
}
};
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/selection.ts b/packages/core/src/docs/data-model/text-x/build-utils/selection.ts
index 0836b03d6c..1218725457 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/selection.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/selection.ts
@@ -14,14 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '../../../../shared';
import type { ITextRange } from '../../../../sheets/typedef';
-import type { IDocumentBody } from '../../../../types/interfaces';
-import type { IDeleteAction, IRetainAction } from '../action-types';
-import { DeleteDirection } from '../../../../types/enum';
-import { DataStreamTreeTokenType } from '../../types';
-import { TextXActionType } from '../action-types';
-import { isCustomRangeSplitSymbol, isIntersecting, shouldDeleteCustomRange } from './custom-range';
export function makeSelection(startOffset: number, endOffset?: number): ITextRange {
if (typeof endOffset === 'undefined') {
@@ -47,263 +40,7 @@ export function normalizeSelection(selection: ITextRange): ITextRange {
};
}
-export function getSelectionWithSymbolMax(selection: ITextRange, body: IDocumentBody) {
- let { startOffset, endOffset } = normalizeSelection(selection);
- while (body.dataStream[startOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- startOffset -= 1;
- }
-
- while (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- startOffset += 1;
- }
-
- while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- endOffset += 1;
- }
-
- while (body.dataStream[endOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- endOffset -= 1;
- }
-
- return {
- startOffset,
- endOffset,
- };
-}
-
-export function getSelectionWithNoSymbolSide(selection: ITextRange, body: IDocumentBody) {
- let { startOffset, endOffset } = normalizeSelection(selection);
- while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {
- startOffset += 1;
- }
-
- while (isCustomRangeSplitSymbol(body.dataStream[endOffset - 1])) {
- endOffset -= 1;
- }
-
- return {
- startOffset,
- endOffset,
- };
-}
-
-export function getDeleteSelection<T extends ITextRange>(selection: T, body: IDocumentBody, direction = DeleteDirection.LEFT): T {
- let { startOffset, endOffset, collapsed } = normalizeSelection(selection);
-
- if (collapsed) {
- if (direction === DeleteDirection.LEFT) {
- while (isCustomRangeSplitSymbol(body.dataStream[startOffset - 1])) {
- endOffset -= 1;
- startOffset -= 1;
- }
- } else {
- while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {
- endOffset += 1;
- startOffset += 1;
- }
- }
- } else {
- const selectionWithSymbolMax = getSelectionWithSymbolMax(selection, body);
- startOffset = selectionWithSymbolMax.startOffset;
- endOffset = selectionWithSymbolMax.endOffset;
- }
-
- collapsed = (startOffset === endOffset);
-
- const customRanges = body.customRanges?.filter((range) => {
- if (!range.wholeEntity) {
- return false;
- }
- if (startOffset <= range.startIndex && endOffset > range.endIndex) {
- return false;
- }
- return isSegmentIntersects(startOffset, collapsed ? endOffset : endOffset - 1, range.startIndex, range.endIndex);
- });
-
- if (customRanges?.length) {
- customRanges.forEach((range) => {
- startOffset = Math.min(range.startIndex, startOffset);
- endOffset = Math.max(range.endIndex + 1, endOffset);
- });
- }
-
- return {
- ...selection,
- startOffset,
- endOffset,
- collapsed: startOffset === endOffset,
- };
-}
-
-export function getInsertSelection<T extends ITextRange>(selection: T, body: IDocumentBody): T {
- let { startOffset, endOffset, collapsed } = normalizeSelection(selection);
-
- if (collapsed) {
- while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- endOffset += 1;
- startOffset += 1;
- }
-
- while (body.dataStream[endOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- endOffset -= 1;
- startOffset -= 1;
- }
-
- return {
- ...selection,
- startOffset,
- endOffset,
- collapsed,
- };
- } else {
- return {
- ...selection,
- ...getSelectionWithSymbolMax(selection, body),
- collapsed: false,
- };
- }
-}
-
-/**
- * Ensure custom-range has a correct order,
- * when range contains range, it won't be present as intersect. <br/>
- * For Example `\s1\s2 text \s1\s2` is not allowed, expect `\s1\s2 text \s2\s1`
- */
-export function getSelectionForAddCustomRange(selection: ITextRange, body: IDocumentBody): Nullable<ITextRange> {
- if (selection.startOffset === selection.endOffset) {
- return null;
- }
-
- const customRanges = body.customRanges;
- if (!customRanges) {
- return normalizeSelection(selection);
- }
-
- let { startOffset, endOffset } = getSelectionWithSymbolMax(selection, body);
- while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {
- if (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- const customRange = customRanges.find((range) => range.startIndex === startOffset);
- if (!customRange) {
- throw new Error('No custom-range matched');
- }
- if (customRange.endIndex === endOffset - 1) {
- return {
- startOffset,
- endOffset,
- collapsed: false,
- };
- } else if (customRange.endIndex < endOffset - 1) {
- break;
- }
- }
-
- startOffset += 1;
- }
-
- while (isCustomRangeSplitSymbol(body.dataStream[endOffset - 1])) {
- if (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- const customRange = customRanges.find((range) => range.endIndex === endOffset - 1);
- if (!customRange) {
- throw new Error('No custom-range matched');
- }
-
- // but actually not possible
- if (customRange.startIndex === startOffset) {
- return {
- startOffset,
- endOffset,
- collapsed: false,
- };
- } else if (customRange.startIndex > startOffset) {
- break;
- }
- }
- endOffset -= 1;
- }
-
- if (endOffset <= startOffset) {
- return null;
- }
-
- return {
- startOffset,
- endOffset,
- collapsed: false,
- };
-}
-
export function isSegmentIntersects(start: number, end: number, start2: number, end2: number) {
return Math.max(start, start2) <= Math.min(end, end2);
}
-export function getRetainAndDeleteFromReplace(
- range: ITextRange,
- segmentId: string = '',
- memoryCursor: number,
- body: IDocumentBody
-) {
- const { startOffset, endOffset } = range;
- const dos: Array<IRetainAction | IDeleteAction> = [];
- const textStart = startOffset - memoryCursor;
- const textEnd = endOffset - memoryCursor;
- const dataStream = body.dataStream;
- const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset - 1));
- const toDeleteRanges = new Set(relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(startOffset, endOffset - startOffset, customRange, dataStream)));
- const retainPoints = new Set<number>();
- relativeCustomRanges?.forEach((range) => {
- if (toDeleteRanges.has(range)) {
- return;
- }
-
- // only retain when the custom-range was intersecting with but not fully contained in the text-range.
- if (range.startIndex - memoryCursor >= textStart &&
- range.startIndex - memoryCursor < textEnd &&
- range.endIndex - memoryCursor >= textEnd) {
- retainPoints.add(range.startIndex);
- }
- if (range.endIndex - memoryCursor >= textStart &&
- range.endIndex - memoryCursor < textEnd &&
- range.startIndex - memoryCursor < textStart) {
- retainPoints.add(range.endIndex);
- }
- });
-
- if (textStart > 0) {
- dos.push({
- t: TextXActionType.RETAIN,
- len: textStart,
- });
- }
-
- const sortedRetains = [...retainPoints].sort((pre, aft) => pre - aft);
- let cursor = textStart;
- sortedRetains.forEach((pos) => {
- const len = pos - cursor;
- if (len > 0) {
- dos.push({
- t: TextXActionType.DELETE,
- len,
- });
- }
- dos.push({
- t: TextXActionType.RETAIN,
- len: 1,
- });
- cursor = pos + 1;
- });
-
- if (cursor < textEnd) {
- dos.push({
- t: TextXActionType.DELETE,
- len: textEnd - cursor,
- });
- cursor = textEnd + 1;
- }
-
- return {
- dos,
- cursor,
- retain: retainPoints.size,
- };
-}
-
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
index abe7eb373b..b441d9a0af 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -18,83 +18,63 @@ import type { IAccessor } from '@wendellhu/redi';
import type { ITextRange, ITextRangeParam } from '../../../../sheets/typedef';
import type { CustomRangeType, IDocumentBody } from '../../../../types/interfaces';
import type { DocumentDataModel } from '../../document-data-model';
-import type { IDeleteAction, IRetainAction } from '../action-types';
+import type { TextXAction } from '../action-types';
+import type { TextXSelection } from '../text-x';
import { type Nullable, UpdateDocsAttributeType } from '../../../../shared';
-import { DataStreamTreeTokenType } from '../../types';
+import { textDiff } from '../../../../shared/text-diff';
import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
-import { excludePointsFromRange, isIntersecting, shouldDeleteCustomRange } from './custom-range';
-import { getDeleteSelection, getSelectionForAddCustomRange } from './selection';
+import { getBodySlice } from '../utils';
+import { excludePointsFromRange, getIntersectingCustomRanges, getSelectionForAddCustomRange } from './custom-range';
export interface IDeleteCustomRangeParam {
rangeId: string;
segmentId?: string;
documentDataModel: DocumentDataModel;
insert?: Nullable<IDocumentBody>;
- textRange?: { index: number };
}
export function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangeParam) {
- const { rangeId, segmentId, documentDataModel, insert, textRange } = params;
-
+ const { rangeId, segmentId, documentDataModel, insert } = params;
const range = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.customRanges?.find((r) => r.rangeId === rangeId);
if (!range) {
return false;
}
const { startIndex, endIndex } = range;
- const textX = new TextX();
+ const textX: TextXSelection = new TextX();
const len = endIndex - startIndex + 1;
- if (startIndex > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: startIndex,
- });
- }
-
textX.push({
- t: TextXActionType.DELETE,
- len: 1,
+ t: TextXActionType.RETAIN,
+ len: startIndex,
});
- if (textRange) {
- if (textRange.index > startIndex) {
- textRange.index--;
- }
- }
-
- if (len - 2 > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: len - 2,
- });
- }
textX.push({
- t: TextXActionType.DELETE,
- len: 1,
+ t: TextXActionType.RETAIN,
+ len,
+ body: {
+ dataStream: '',
+ customRanges: [],
+ },
});
- if (textRange) {
- if (textRange.index > endIndex) {
- textRange.index--;
- }
- }
-
if (insert) {
textX.push({
- body: insert,
t: TextXActionType.INSERT,
+ body: insert,
len: insert.dataStream.length,
});
-
- if (textRange) {
- if (textRange.index > endIndex) {
- textRange.index += insert.dataStream.length;
- }
- }
}
+
+ const end = endIndex + 1 + (insert?.dataStream.length ?? 0);
+ textX.selections = [{
+ startOffset: end,
+ endOffset: end,
+ collapsed: true,
+ }];
+
return textX;
}
@@ -108,9 +88,8 @@ export interface IAddCustomRangeTextXParam {
body: IDocumentBody;
}
-// eslint-disable-next-line max-lines-per-function
export function addCustomRangeTextX(param: IAddCustomRangeTextXParam) {
- const { range, rangeId, rangeType, segmentId, wholeEntity, properties, body } = param;
+ const { range, rangeId, rangeType, wholeEntity, properties, body } = param;
const actualRange = getSelectionForAddCustomRange(range, body);
if (!actualRange) {
return false;
@@ -124,183 +103,97 @@ export function addCustomRangeTextX(param: IAddCustomRangeTextXParam) {
const customRanges = body.customRanges ?? [];
let cursor = 0;
- const textX = new TextX();
+ const textX: TextX & { selections?: ITextRange[] } = new TextX();
- // eslint-disable-next-line max-lines-per-function
const addCustomRange = (startIndex: number, endIndex: number, index: number) => {
- const relativeCustomRanges = [];
- for (let i = 0, len = customRanges.length; i < len; i++) {
- const customRange = customRanges[i];
- // intersect
- if (customRange.rangeType === rangeType && Math.max(customRange.startIndex, startIndex) <= Math.min(customRange.endIndex, endIndex)) {
- relativeCustomRanges.push({ ...customRange });
- }
-
- // optimize
- if (customRange.startIndex > endIndex) {
- break;
- }
- }
- const deletes = relativeCustomRanges.map((i) => [i.startIndex, i.endIndex]).flat().sort((pre, aft) => pre - aft);
-
- const range = deletes.length
- ? {
- startOffset: Math.min(deletes[0], startIndex),
- endOffset: Math.max(deletes[deletes.length - 1] + 1, endIndex + 1),
- }
- : {
- startOffset: startIndex,
- endOffset: endIndex + 1,
- };
-
- if (range.startOffset !== cursor) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: range.startOffset - cursor,
- });
- cursor = range.startOffset;
- }
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,
+ const relativeCustomRanges = getIntersectingCustomRanges(startIndex, endIndex, customRanges, rangeType);
+ const rangeStartIndex = Math.min((relativeCustomRanges[0]?.startIndex ?? Infinity), startIndex);
+ const rangeEndIndex = Math.max(relativeCustomRanges[relativeCustomRanges.length - 1]?.endIndex ?? -Infinity, endIndex);
+
+ const customRange = {
+ rangeId: index ? `${rangeId}-${index}` : rangeId,
+ rangeType,
+ startIndex: 0,
+ endIndex: rangeEndIndex - rangeStartIndex,
+ wholeEntity,
+ properties: {
+ ...properties,
},
- len: 1,
- });
-
- deletes.forEach((index) => {
- if (index !== cursor) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: index - cursor,
- });
- cursor = index;
- }
- textX.push({
- t: TextXActionType.DELETE,
- len: 1,
- });
- cursor++;
+ };
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: rangeStartIndex - cursor,
});
-
- if (cursor !== range.endOffset) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: range.endOffset - cursor,
- });
- cursor = range.endOffset;
- }
-
textX.push({
- t: TextXActionType.INSERT,
+ t: TextXActionType.RETAIN,
+ len: rangeEndIndex - rangeStartIndex + 1,
body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_END,
- customRanges: [
- {
- rangeId: index ? `${rangeId}-${index}` : rangeId,
- rangeType,
- startIndex: -(range.endOffset - range.startOffset - deletes.length + 1),
- endIndex: 0,
- wholeEntity,
- properties: {
- ...properties,
- },
- },
- ],
+ dataStream: '',
+ customRanges: [customRange],
},
- len: 1,
+ coverType: UpdateDocsAttributeType.COVER,
});
+ cursor = rangeEndIndex + 1;
};
const relativeParagraphs = (body.paragraphs ?? []).filter((p) => p.startIndex < endOffset && p.startIndex > startOffset);
const newRanges = excludePointsFromRange([startOffset, endOffset - 1], relativeParagraphs.map((p) => p.startIndex));
newRanges.forEach(([start, end], i) => addCustomRange(start, end, i));
+ textX.selections = [{
+ startOffset: actualRange.endOffset,
+ endOffset: actualRange.endOffset,
+ collapsed: true,
+ }];
return textX;
}
// If the selection contains line breaks,
// paragraph information needs to be preserved when performing the CUT operation
-// eslint-disable-next-line max-lines-per-function
-export function getRetainAndDeleteAndExcludeLineBreak(
- selection: ITextRange,
+
+export function deleteSelectionTextX(
+ selections: ITextRange[],
body: IDocumentBody,
- segmentId: string = '',
memoryCursor: number = 0,
- preserveLineBreak: boolean = true
-): Array<IRetainAction | IDeleteAction> {
- const { startOffset, endOffset } = getDeleteSelection(selection, body);
- const dos: Array<IRetainAction | IDeleteAction> = [];
- const { paragraphs = [], dataStream } = body;
-
- const textStart = startOffset - memoryCursor;
- const textEnd = endOffset - memoryCursor;
+ insertBody: Nullable<IDocumentBody> = null,
+ keepBullet: boolean = true
+): Array<TextXAction> {
+ selections.sort((a, b) => a.startOffset - b.startOffset);
+ const dos: Array<TextXAction> = [];
+ const { paragraphs = [] } = body;
const paragraphInRange = paragraphs?.find(
- (p) => p.startIndex - memoryCursor >= textStart && p.startIndex - memoryCursor < textEnd
+ (p) => p.startIndex >= selections[0].startOffset && p.startIndex < selections[0].endOffset
);
-
- const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset - 1));
- const toDeleteRanges = new Set(relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(startOffset, endOffset - startOffset, customRange, dataStream)));
- const retainPoints = new Set<number>();
- relativeCustomRanges?.forEach((range) => {
- if (toDeleteRanges.has(range)) {
- return;
- }
-
- if (range.startIndex - memoryCursor >= textStart &&
- range.startIndex - memoryCursor <= textEnd &&
- range.endIndex - memoryCursor > textEnd) {
- retainPoints.add(range.startIndex);
- }
- if (range.endIndex - memoryCursor >= textStart &&
- range.endIndex - memoryCursor <= textEnd &&
- range.startIndex < textStart) {
- retainPoints.add(range.endIndex);
- }
- });
-
- if (textStart > 0) {
- dos.push({
- t: TextXActionType.RETAIN,
- len: textStart,
- });
- }
-
- if (preserveLineBreak) {
- if (paragraphInRange && paragraphInRange.startIndex - memoryCursor > textStart) {
- const paragraphIndex = paragraphInRange.startIndex - memoryCursor;
- retainPoints.add(paragraphIndex);
+ let cursor = memoryCursor;
+ selections.forEach((selection) => {
+ const { startOffset, endOffset } = selection;
+ if (startOffset > cursor) {
+ dos.push({
+ t: TextXActionType.RETAIN,
+ len: startOffset - cursor,
+ });
+ cursor = startOffset;
}
- }
-
- const sortedRetains = [...retainPoints].sort((pre, aft) => pre - aft);
- let cursor = textStart;
- sortedRetains.forEach((pos) => {
- const len = pos - cursor;
- if (len > 0) {
+ if (cursor < endOffset) {
dos.push({
t: TextXActionType.DELETE,
- len,
+ len: endOffset - cursor,
});
+ cursor = endOffset;
}
- dos.push({
- t: TextXActionType.RETAIN,
- len: 1,
- });
- cursor = pos + 1;
});
- if (cursor < textEnd) {
+ if (insertBody) {
dos.push({
- t: TextXActionType.DELETE,
- len: textEnd - cursor,
+ t: TextXActionType.INSERT,
+ body: insertBody,
+ len: insertBody.dataStream.length,
});
- cursor = textEnd;
}
- if (!preserveLineBreak) {
- const nextParagraph = paragraphs.find((p) => p.startIndex - memoryCursor >= textEnd);
+ if (paragraphInRange && keepBullet) {
+ const nextParagraph = paragraphs.find((p) => p.startIndex - memoryCursor >= (selections[selections.length - 1].endOffset - 1));
if (nextParagraph) {
if (nextParagraph.startIndex > cursor) {
dos.push({
@@ -351,18 +244,47 @@ export const replaceSelectionTextX = (params: IReplaceSelectionTextXParams) => {
const body = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) return false;
+ const oldBody = selection.collapsed ? null : getBodySlice(body, selection.startOffset, selection.endOffset);
+ const diffs = textDiff(oldBody ? oldBody.dataStream : '', insertBody.dataStream);
+ let cursor = 0;
+ const actions = diffs.map(([type, text]) => {
+ switch (type) {
+ // retain
+ case 0: {
+ const action: TextXAction = {
+ t: TextXActionType.RETAIN,
+ body: getBodySlice(insertBody, cursor, cursor + text.length),
+ len: text.length,
+ };
+ cursor += text.length;
+ return action;
+ }
+ // insert
+ case 1: {
+ const action: TextXAction = {
+ t: TextXActionType.INSERT,
+ body: getBodySlice(insertBody, cursor, cursor + text.length),
+ len: text.length,
+ };
+ cursor += text.length;
+ return action;
+ }
+ // delete
+ default: {
+ const action: TextXAction = {
+ t: TextXActionType.DELETE,
+ len: text.length,
+ };
+ return action;
+ }
+ }
+ });
+
const textX = new TextX();
- const deleteActions = getRetainAndDeleteAndExcludeLineBreak(selection, body, segmentId);
- // delete
- if (deleteActions.length) {
- textX.push(...deleteActions);
- }
- // insert
textX.push({
- t: TextXActionType.INSERT,
- body: insertBody,
- len: insertBody.dataStream.length,
+ t: TextXActionType.RETAIN,
+ len: selection.startOffset,
});
-
+ textX.push(...actions);
return textX;
};
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index 7908239d7f..e9f4afc8aa 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ITextRange } from '../../../sheets/typedef';
import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
@@ -418,6 +419,10 @@ export class TextX {
}
}
+export type TextXSelection = TextX & {
+ selections?: ITextRange[];
+};
+
// FIXME: @Jocs, Use to avoid storybook error. and move the static name property to here.
Object.defineProperty(TextX, 'name', {
value: 'text-x',
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index 60c72232ba..594c079562 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -18,7 +18,6 @@ import type { ICustomBlock, ICustomDecoration, IDocumentBody, IParagraph, ISecti
import type { IRetainAction } from './action-types';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
-import { DataStreamTreeTokenType } from '../types';
import { coverTextRuns } from './apply-utils/update-apply';
export enum SliceBodyType {
@@ -176,7 +175,7 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {
}
});
- const newData = `${DataStreamTreeTokenType.CUSTOM_RANGE_START.repeat(leftOffset)}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END.repeat(rightOffset)}`;
+ const newData = `${dataStream}`;
if (textRuns) {
if (textRuns[0]) {
@@ -225,39 +224,16 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {
export function getCustomRangeSlice(body: IDocumentBody, startOffset: number, endOffset: number) {
const { customRanges = [] } = body;
- let leftOffset = 0;
- let rightOffset = 0;
+ const leftOffset = 0;
+ const rightOffset = 0;
const relativeCustomRanges = customRanges
.filter((customRange) => Math.max(customRange.startIndex, startOffset) <= Math.min(customRange.endIndex, endOffset - 1))
.map((range) => ({
...range,
- startIndex: range.startIndex,
- endIndex: range.endIndex,
+ startIndex: Math.max(range.startIndex, startOffset),
+ endIndex: Math.min(range.endIndex, endOffset - 1),
}));
- if (relativeCustomRanges.length) {
- relativeCustomRanges.forEach((customRange) => {
- if (customRange.startIndex < startOffset) {
- leftOffset += 1;
- }
- if (customRange.endIndex > (endOffset - 1)) {
- rightOffset += 1;
- }
- });
-
- for (let i = 0; i < leftOffset; i++) {
- const range = relativeCustomRanges[i];
- range.startIndex = startOffset - leftOffset + i;
- }
- if (rightOffset) {
- const sorted = [...relativeCustomRanges].sort((pre, aft) => aft.endIndex - pre.endIndex);
- for (let i = 0; i < rightOffset; i++) {
- const range = sorted[i];
- range.endIndex = endOffset + rightOffset - i - 1;
- }
- }
- }
-
return {
customRanges: relativeCustomRanges.map((range) => ({
...range,
@@ -281,7 +257,7 @@ export function getCustomDecorationSlice(body: IDocumentBody, startOffset: numbe
customDecorationSlice.push({
...copy,
startIndex: Math.max(copy.startIndex - startOffset, 0),
- endIndex: Math.min(copy.endIndex, endOffset) - startOffset,
+ endIndex: Math.min(copy.endIndex, endOffset - 1) - startOffset,
});
}
});
diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.ts
index c2b32c5b05..8ba7b6a04a 100644
--- a/packages/core/src/docs/data-model/types.ts
+++ b/packages/core/src/docs/data-model/types.ts
@@ -38,7 +38,13 @@ export enum DataStreamTreeTokenType {
TABLE_ROW_END = '\x0E', // 表格行结束
TABLE_END = '\x0F', // 表格结束
// custom range.
+ /**
+ * @deprecated
+ */
CUSTOM_RANGE_START = '\x1F', // 自定义范围开始
+ /**
+ * @deprecated
+ */
CUSTOM_RANGE_END = '\x1E', // 自定义范围结束
COLUMN_BREAK = '\v', // 换列
@@ -54,5 +60,5 @@ export enum DataStreamTreeTokenType {
/** Wrap your stream in a pair of custom range tokens. */
export function makeCustomRangeStream(stream: string): string {
- return `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${stream}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ return `${stream}`;
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 79f6ace190..586d3411a5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -19,7 +19,7 @@ import { installShims } from './common/shims';
installShims();
export { debounce, get, merge, mergeWith, set } from 'lodash-es';
-
+export { textDiff } from './shared/text-diff';
export { dedupe, groupBy, makeArray, remove, rotate } from './common/array';
export { isBooleanString } from './common/boolean';
export {
diff --git a/packages/core/src/shared/text-diff.ts b/packages/core/src/shared/text-diff.ts
new file mode 100644
index 0000000000..a2ed23684b
--- /dev/null
+++ b/packages/core/src/shared/text-diff.ts
@@ -0,0 +1,17 @@
+/**
+ * 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 { default as textDiff } from 'fast-diff';
diff --git a/packages/core/src/types/const/const.ts b/packages/core/src/types/const/const.ts
index 4f43d95529..de9f5fb8f1 100644
--- a/packages/core/src/types/const/const.ts
+++ b/packages/core/src/types/const/const.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY } from '../../common/const';
import {
BooleanNumber,
HorizontalAlign,
@@ -164,3 +165,4 @@ export const DEFAULT_SLIDE = {
},
};
+export const SHEET_EDITOR_UNITS = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 665d769863..77aa4d53ad 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -369,6 +369,8 @@ export enum CustomRangeType {
CUSTOM,
MENTION,
UNI_FORMULA,
+
+ DELTED = 9999,
}
/**
@@ -383,6 +385,8 @@ export interface ICustomBlock {
export enum CustomDecorationType {
COMMENT,
+
+ DELTED = 9999,
}
export interface ICustomDecoration {
diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
index 9991bd4763..303a26ec11 100644
--- a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
@@ -77,7 +77,7 @@ export const InsertDocDrawingCommand: ICommand = {
});
}
} else {
- const { dos } = BuildTextUtils.selection.getDeleteActions(activeTextRange, segmentId, 0, body);
+ const dos = BuildTextUtils.selection.delete([activeTextRange], body, 0, null, false);
textX.push(...dos);
const removedCustomBlockIds = getCustomBlockIdsInSelections(body, [activeTextRange]);
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
index 2badef8015..55473f1fbe 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel, ICommand } from '@univerjs/core';
-import { CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, getBodySlice, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { CommandType, CustomRangeType, getBodySlice, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, replaceSelectionFactory } from '@univerjs/docs';
export interface IUpdateDocHyperLinkCommandParams {
@@ -33,7 +33,7 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
if (!params) {
return false;
}
- const { unitId, payload, segmentId } = params;
+ const { unitId, payload, segmentId, linkId } = params;
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
@@ -43,7 +43,6 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
return false;
}
- const newId = generateRandomId();
const oldBody = getBodySlice(doc.getSelfOrHeaderFooterModel(segmentId).getBody()!, currentSelection.startOffset!, currentSelection.endOffset!);
const textRun = oldBody.textRuns?.[0];
if (textRun) {
@@ -53,9 +52,9 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
const replaceSelection = replaceSelectionFactory(accessor, {
unitId,
body: {
- dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${params.label}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ dataStream: `${params.label}`,
customRanges: [{
- rangeId: newId,
+ rangeId: linkId,
rangeType: CustomRangeType.HYPERLINK,
startIndex: 0,
endIndex: params.label.length + 1,
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
index 317962903e..0cfaf1c714 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
@@ -61,6 +61,8 @@ export interface IShowDocHyperLinkEditPopupOperationParams {
linkId: string;
segmentId?: string;
segmentPage?: number;
+ startIndex: number;
+ endIndex: number;
};
}
@@ -89,6 +91,8 @@ export interface IShowDocHyperLinkInfoPopupOperationParams {
segmentId?: string;
unitId: string;
segmentPage?: number;
+ startIndex: number;
+ endIndex: number;
}
export const ToggleDocHyperLinkInfoPopupOperation: ICommand<IShowDocHyperLinkInfoPopupOperationParams> = {
diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
index c0e02abdd2..a76b8ae194 100644
--- a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
@@ -48,7 +48,7 @@ export class DocHyperLinkSelectionController extends Disposable {
const index = customRanges?.findIndex((value) => (value.startIndex) < startOffset && value.endIndex > endOffset - 1) ?? -1;
if (index > -1) {
const customRange = customRanges![index];
- this._docHyperLinkService.showInfoPopup({ unitId, linkId: customRange.rangeId, segmentId, segmentPage });
+ this._docHyperLinkService.showInfoPopup({ unitId, linkId: customRange.rangeId, segmentId, segmentPage, startIndex: customRange.startIndex, endIndex: customRange.endIndex });
return;
}
} else {
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
index 109acb2637..eb60bebe28 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
+import type { DocumentDataModel } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { CustomRangeType, Disposable, ICommandService, Inject } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocEventManagerService } from '@univerjs/docs-ui';
-import type { DocumentDataModel } from '@univerjs/core';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { ClickDocHyperLinkOperation, ToggleDocHyperLinkInfoPopupOperation } from '../../commands/operations/popup.operation';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
@@ -69,6 +69,8 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
segmentId: link.segmentId,
segmentPage: link.segmentPageIndex,
rangeId: link.range.rangeId,
+ startIndex: link.range.startIndex,
+ endIndex: link.range.endIndex,
}
);
} else {
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
index e1a0d9f351..92b654c29b 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
@@ -41,11 +41,18 @@ export class DocHyperLinkRenderController extends Disposable implements IRenderM
if (!data) {
return next(data);
}
- const { unitId } = pos;
+ const { unitId, index } = pos;
const activeLink = this._hyperLinkService.showing;
- const { linkId, unitId: linkUnitId } = activeLink || {};
- const isActive = linkUnitId === unitId && data.rangeId === linkId;
+ if (!activeLink) {
+ return next({
+ ...data,
+ active: false,
+ });
+ }
+ const { linkId, unitId: linkUnitId, startIndex, endIndex } = activeLink;
+ const isActive = linkUnitId === unitId && data.rangeId === linkId && index >= startIndex && index <= endIndex;
+
return next({
...data,
active: isActive,
@@ -57,7 +64,7 @@ export class DocHyperLinkRenderController extends Disposable implements IRenderM
private _initReRender() {
this.disposeWithMe(this._hyperLinkService.showingLink$
.pipe(
- distinctUntilChanged((prev, aft) => prev?.linkId === aft?.linkId && prev?.unitId === aft?.unitId),
+ distinctUntilChanged((prev, aft) => prev?.linkId === aft?.linkId && prev?.unitId === aft?.unitId && prev?.startIndex === aft?.startIndex),
pairwise()
)
.subscribe(([preLink, link]) => {
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 16b925b31a..a214a2a559 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -14,24 +14,21 @@
* limitations under the License.
*/
+import type { DocumentDataModel, IDisposable, ITextRangeParam, Nullable } from '@univerjs/core';
import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { BehaviorSubject } from 'rxjs';
-import type { DocumentDataModel, IDisposable, ITextRangeParam, Nullable } from '@univerjs/core';
import { DocHyperLinkEdit } from '../views/hyper-link-edit';
import { DocLinkPopup } from '../views/hyper-link-popup';
-/**
- * A link will have a placeholder, and when it is a link at the beginning, the placeholder does not have a width or height, causing an evaluation error
- */
-const SKIT_PLACEHOLDER = 0;
-
export interface ILinkInfo {
unitId: string;
linkId: string;
segmentId?: string;
segmentPage?: number;
+ startIndex: number;
+ endIndex: number;
}
export class DocHyperLinkPopupService extends Disposable {
@@ -71,23 +68,19 @@ export class DocHyperLinkPopupService extends Disposable {
this._editingLink$.next(linkInfo);
let activeRange: Nullable<ITextRangeParam> = this._textSelectionManagerService.getActiveTextRange();
if (linkInfo) {
- const { unitId, linkId, segmentId, segmentPage } = linkInfo;
- const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const range = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges?.find((i) => i.rangeId === linkId);
- if (range) {
- activeRange = {
- collapsed: false,
- startOffset: range.startIndex + SKIT_PLACEHOLDER,
- endOffset: range.endIndex + 1,
- segmentId,
- segmentPage,
- };
-
- this._textSelectionManagerService.replaceTextRanges([{
- startOffset: range.startIndex,
- endOffset: range.endIndex + 1,
- }]);
- }
+ const { segmentId, segmentPage, startIndex, endIndex } = linkInfo;
+ activeRange = {
+ collapsed: false,
+ startOffset: startIndex,
+ endOffset: endIndex + 1,
+ segmentId,
+ segmentPage,
+ };
+
+ this._textSelectionManagerService.replaceDocRanges([{
+ startOffset: startIndex,
+ endOffset: endIndex + 1,
+ }]);
}
if (activeRange) {
@@ -111,12 +104,14 @@ export class DocHyperLinkPopupService extends Disposable {
}
showInfoPopup(info: ILinkInfo): Nullable<IDisposable> {
- const { linkId, unitId, segmentId, segmentPage } = info;
+ const { linkId, unitId, segmentId, segmentPage, startIndex, endIndex } = info;
if (
this.showing?.linkId === linkId &&
this.showing?.unitId === unitId &&
this.showing?.segmentId === segmentId &&
- this.showing?.segmentPage === segmentPage
+ this.showing?.segmentPage === segmentPage &&
+ this.showing?.startIndex === startIndex &&
+ this.showing?.endIndex === endIndex
) {
return;
}
@@ -128,19 +123,15 @@ export class DocHyperLinkPopupService extends Disposable {
if (!doc) {
return;
}
- const range = doc.getSelfOrHeaderFooterModel(info.segmentId).getBody()?.customRanges?.find((i) => i.rangeId === linkId);
- this._showingLink$.next({ unitId, linkId, segmentId, segmentPage });
- if (!range) {
- return;
- }
+ this._showingLink$.next({ unitId, linkId, segmentId, segmentPage, startIndex, endIndex });
this._infoPopup = this._docCanvasPopupManagerService.attachPopupToRange(
{
collapsed: false,
- startOffset: range.startIndex + SKIT_PLACEHOLDER,
- endOffset: range.endIndex + 1,
- segmentId: info.segmentId,
- segmentPage: info.segmentPage,
+ startOffset: startIndex,
+ endOffset: endIndex + 1,
+ segmentId,
+ segmentPage,
},
{
componentKey: DocLinkPopup.componentKey,
@@ -150,7 +141,7 @@ export class DocHyperLinkPopupService extends Disposable {
this.hideInfoPopup();
},
},
- info.unitId
+ unitId
);
return this._infoPopup;
}
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.tsx
index 989280fb79..7e5b8a4ce4 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
@@ -63,16 +63,16 @@ export const DocHyperLinkEdit = () => {
if (editing) {
const body = doc?.getSelfOrHeaderFooterModel(editing.segmentId)?.getBody();
- const matchedRange = body?.customRanges?.find((i) => editing?.linkId === i.rangeId);
+ const matchedRange = body?.customRanges?.find((i) => editing?.linkId === i.rangeId && i.startIndex === editing.startIndex && i.endIndex === editing.endIndex);
if (doc && matchedRange) {
setLink(matchedRange.properties?.url ?? '');
- setLabel(BuildTextUtils.transform.getPlainText(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex).dataStream));
+ setLabel(BuildTextUtils.transform.getPlainText(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex + 1).dataStream));
}
return;
}
const body = doc?.getSelfOrHeaderFooterModel(activeRange.segmentId)?.getBody();
- const selection = body ? BuildTextUtils.selection.getInsertSelection(activeRange, body) : null;
+ const selection = body ? activeRange : null;
const matchedRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, body?.customRanges ?? [])?.[0];
if (doc && matchedRange) {
setLink(matchedRange?.properties?.url ?? '');
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx
index 56733d501d..db64a3b541 100644
--- a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx
@@ -16,14 +16,14 @@
import type { DocumentDataModel } from '@univerjs/core';
import { CustomRangeType, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
-import React from 'react';
-import { CopySingle, LinkSingle, UnlinkSingle, WriteSingle } from '@univerjs/icons';
-import cs from 'clsx';
import { MessageType, Tooltip } from '@univerjs/design';
+import { CopySingle, LinkSingle, UnlinkSingle, WriteSingle } from '@univerjs/icons';
import { IMessageService, useObservable } from '@univerjs/ui';
-import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+import cs from 'clsx';
+import React from 'react';
import { DeleteDocHyperLinkCommand } from '../../commands/commands/delete-link.command';
import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
import styles from './index.module.less';
export const DocLinkPopup = () => {
@@ -37,10 +37,10 @@ export const DocLinkPopup = () => {
return null;
}
- const { unitId, linkId, segmentId } = currentPopup;
+ const { unitId, linkId, segmentId, startIndex, endIndex } = currentPopup;
const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const body = doc?.getSelfOrHeaderFooterModel(segmentId).getBody();
- const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK);
+ const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK && range.startIndex === startIndex && range.endIndex === endIndex);
if (!link) {
return null;
diff --git a/packages/docs-mention-ui/src/commands/commands/doc-mention.command.ts b/packages/docs-mention-ui/src/commands/commands/doc-mention.command.ts
index ad43ebe39c..b197c86ff8 100644
--- a/packages/docs-mention-ui/src/commands/commands/doc-mention.command.ts
+++ b/packages/docs-mention-ui/src/commands/commands/doc-mention.command.ts
@@ -16,7 +16,7 @@
import type { ICommand, IDocumentBody } from '@univerjs/core';
import type { IDocMention } from '../../types/interfaces/i-mention';
-import { CommandType, CustomRangeType, DataStreamTreeTokenType, ICommandService } from '@univerjs/core';
+import { CommandType, CustomRangeType, ICommandService } from '@univerjs/core';
import { deleteCustomRangeFactory, DocSelectionManagerService, replaceSelectionFactory } from '@univerjs/docs';
export interface IAddDocMentionCommandParams {
@@ -40,7 +40,7 @@ export const AddDocMentionCommand: ICommand<IAddDocMentionCommandParams> = {
if (!activeRange) {
return false;
}
- const dataStream = `${DataStreamTreeTokenType.CUSTOM_RANGE_START} @${mention.label} ${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ const dataStream = ` @${mention.label} `;
const body: IDocumentBody = {
dataStream,
customRanges: [{
diff --git a/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts b/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts
index f335ac9c49..844d8fcf63 100644
--- a/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts
+++ b/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, sequenceExecute } from '@univerjs/core';
import { deleteCustomDecorationFactory } from '@univerjs/docs-ui';
-import type { ICommand } from '@univerjs/core';
export interface IDeleteDocCommentComment {
unitId: string;
diff --git a/packages/docs-thread-comment-ui/src/controllers/menu.ts b/packages/docs-thread-comment-ui/src/controllers/menu.ts
index 8bdcb02fa9..dbbf7897eb 100644
--- a/packages/docs-thread-comment-ui/src/controllers/menu.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/menu.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import { UniverInstanceType } from '@univerjs/core';
+import type { IAccessor } from '@univerjs/core';
+import type { IMenuButtonItem } from '@univerjs/ui';
+import { SHEET_EDITOR_UNITS, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { debounceTime, Observable } from 'rxjs';
-import type { IAccessor } from '@univerjs/core';
-import type { IMenuButtonItem } from '@univerjs/ui';
import { StartAddCommentOperation, ToggleCommentPanelOperation } from '../commands/operations/show-comment-panel.operation';
export const shouldDisableAddComment = (accessor: IAccessor) => {
@@ -49,7 +49,7 @@ export function AddDocCommentMenuItemFactory(accessor: IAccessor): IMenuButtonIt
icon: 'CommentSingle',
title: 'threadCommentUI.panel.addComment',
tooltip: 'threadCommentUI.panel.addComment',
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC, undefined, SHEET_EDITOR_UNITS),
disabled$: new Observable(function (subscribe) {
const textSelectionService = accessor.get(DocSelectionManagerService);
const observer = textSelectionService.textSelection$.pipe(debounceTime(16)).subscribe(() => {
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
index 4de3fcae59..7f7066a71e 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
@@ -137,9 +137,10 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
this._threadCommentModel.addComment(unitId, subUnitId, { id, threadId: id, ref: '', dT: '', personId: '', text: { dataStream: '' }, unitId, subUnitId });
}
});
- deleteIds.forEach((id) => {
- this._threadCommentModel.deleteThread(unitId, subUnitId, id);
- });
+
+ // deleteIds.forEach((id) => {
+ // this._threadCommentModel.deleteThread(unitId, subUnitId, id);
+ // });
this._threadCommentModel.syncThreadComments(unitId, subUnitId, [...addIds]);
}
diff --git a/packages/docs-ui/src/basics/custom-decoration-factory.ts b/packages/docs-ui/src/basics/custom-decoration-factory.ts
index 49573c8375..39c4e9a879 100644
--- a/packages/docs-ui/src/basics/custom-decoration-factory.ts
+++ b/packages/docs-ui/src/basics/custom-decoration-factory.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { CustomDecorationType, DocumentDataModel, IAccessor, IMutationInfo } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, IMutationInfo } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getBodySlice, IUniverInstanceService, JSONX, TextX, TextXActionType, Tools, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';
+import { CustomDecorationType, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
interface IAddCustomDecorationParam {
@@ -130,23 +130,11 @@ export function deleteCustomDecorationFactory(accessor: IAccessor, params: IDele
return false;
}
- const decorations = documentDataModel.getBody()?.customDecorations?.filter((d) => d.id === id);
- if (!decorations?.length) {
+ const decoration = documentDataModel.getBody()?.customDecorations?.find((d) => d.id === id);
+ if (!decoration) {
return false;
}
- const oldBodySlices = decorations.map((i) => {
- const bodySlice = getBodySlice(body, i.startIndex, i.endIndex + 1);
- // bodySlice.customDecorations = bodySlice.customDecorations?.filter((decoration) => decoration.id !== id);
- return bodySlice;
- });
-
- const bodySlices = oldBodySlices.map((bodySlice) => {
- const copy = Tools.deepClone(bodySlice);
- copy.customDecorations = copy.customDecorations?.filter((decoration) => decoration.id !== id);
- return copy;
- });
-
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
@@ -158,26 +146,28 @@ export function deleteCustomDecorationFactory(accessor: IAccessor, params: IDele
const textX = new TextX();
const jsonX = JSONX.getInstance();
+ const { startIndex, endIndex } = decoration;
+ const len = endIndex - startIndex + 1;
- let cursor = 0;
- decorations.forEach((decoration, i) => {
- const bodySlice = bodySlices[i];
- const oldBody = oldBodySlices[i];
- if (decoration.startIndex !== cursor) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: decoration.startIndex - cursor,
- });
- }
- cursor = (decoration.startIndex);
- textX.push({
- t: TextXActionType.RETAIN,
- len: decoration.endIndex - decoration.startIndex + 1,
- body: bodySlice,
- oldBody,
- coverType: UpdateDocsAttributeType.REPLACE,
- });
- cursor = cursor + (decoration.endIndex - decoration.startIndex + 1);
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: startIndex,
+ });
+
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len,
+ body: {
+ dataStream: '',
+ customDecorations: [
+ {
+ startIndex: 0,
+ endIndex: len - 1,
+ id,
+ type: CustomDecorationType.DELTED,
+ },
+ ],
+ },
});
doMutation.params.actions = jsonX.editOp(textX.serialize());
diff --git a/packages/docs-ui/src/basics/paragraph.ts b/packages/docs-ui/src/basics/paragraph.ts
index 2c3ae741e7..1d924057c1 100644
--- a/packages/docs-ui/src/basics/paragraph.ts
+++ b/packages/docs-ui/src/basics/paragraph.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICustomTable, IParagraph, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
+import type { ICustomDecoration, ICustomRange, ICustomTable, IParagraph, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
export function hasParagraphInTable(paragraph: IParagraph, tables: ICustomTable[]) {
return tables.some((table) => paragraph.startIndex > table.startIndex && paragraph.startIndex < table.endIndex);
@@ -56,3 +56,15 @@ export function getTextRunAtPosition(
return retTextRun;
}
+
+export function getCustomRangeAtPosition(customRanges: ICustomRange[], position: number, extendRange?: boolean) {
+ if (extendRange) {
+ return customRanges.find((customRange) => position >= customRange.startIndex && position <= customRange.endIndex + 1);
+ }
+
+ return customRanges.find((customRange) => position > customRange.startIndex && position <= customRange.endIndex);
+}
+
+export function getCustomDecorationAtPosition(customDecorations: ICustomDecoration[], position: number) {
+ return customDecorations.filter((customDecoration) => position > customDecoration.startIndex && position <= customDecoration.endIndex);
+}
diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.ts
index ea35f382f9..8108fcf600 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel, ICommand, IDocumentBody, IParagraph } from '@univerjs/core';
-import { BuildTextUtils, CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, PresetListType, Tools, UniverInstanceType } from '@univerjs/core';
+import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, PresetListType, Tools, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { getTextRunAtPosition } from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
@@ -91,7 +91,7 @@ export const BreakLineCommand: ICommand = {
const unitId = docDataModel.getUnitId();
- const { startOffset, endOffset } = BuildTextUtils.selection.getInsertSelection(activeTextRange, body);
+ const { startOffset, endOffset } = activeTextRange;
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index 9e33dc3a87..a09a162322 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -33,11 +33,13 @@ import {
IUniverInstanceService,
JSONX,
MemoryCursor,
+ SHEET_EDITOR_UNITS,
TextX,
TextXActionType,
Tools,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { getCustomDecorationAtPosition, getCustomRangeAtPosition } from '../../basics/paragraph';
import { getCommandSkeleton, getRichTextEditPath } from '../util';
import { getDeleteRowContentActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams } from './table/table';
@@ -78,6 +80,7 @@ export interface IInnerPasteCommandParams {
textRanges: ITextRangeWithStyle[];
}
+const UNITS = SHEET_EDITOR_UNITS;
// Actually, the command is to handle paste event.
export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
id: 'doc.command.inner-paste',
@@ -89,10 +92,10 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
const commandService = accessor.get(ICommandService);
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const originSelections = docSelectionManagerService.getTextRanges();
+ const selections = docSelectionManagerService.getTextRanges();
const rectRanges = docSelectionManagerService.getRectRanges();
const { body, tableSource, drawings } = doc;
- if (!Array.isArray(originSelections) || originSelections.length === 0 || body == null) {
+ if (!Array.isArray(selections) || selections.length === 0 || body == null) {
return false;
}
@@ -101,7 +104,6 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
if (docDataModel == null || originBody == null) {
return false;
}
- const selections = originSelections.map((range) => BuildTextUtils.selection.getInsertSelection(range, originBody));
const unitId = docDataModel.getUnitId();
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
@@ -141,7 +143,8 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
return false;
}
- for (const selection of selections) {
+ for (let i = 0; i < selections.length; i++) {
+ const selection = selections[i];
const { startOffset, endOffset, collapsed } = selection;
const len = startOffset - memoryCursor.cursor;
@@ -185,22 +188,37 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
}
}
+ const customRange = getCustomRangeAtPosition(originBody.customRanges ?? [], endOffset, UNITS.includes(unitId));
+ const customDecorations = getCustomDecorationAtPosition(originBody.customDecorations ?? [], endOffset);
+ if (customRange) {
+ cloneBody.customRanges = [{
+ ...customRange,
+ startIndex: 0,
+ endIndex: body.dataStream.length,
+ }];
+ }
+ if (customDecorations.length) {
+ cloneBody.customDecorations = customDecorations.map((customDecoration) => ({
+ ...customDecoration,
+ startIndex: 0,
+ endIndex: body.dataStream.length,
+ }));
+ }
if (collapsed) {
textX.push({
t: TextXActionType.RETAIN,
len,
});
+ textX.push({
+ t: TextXActionType.INSERT,
+ body: cloneBody,
+ len: body.dataStream.length,
+ });
} else {
- const { dos } = BuildTextUtils.selection.getDeleteActions(selection, segmentId, memoryCursor.cursor, originBody);
+ const dos = BuildTextUtils.selection.delete([selection], body, memoryCursor.cursor, cloneBody, selections.length === 1);
textX.push(...dos);
}
- textX.push({
- t: TextXActionType.INSERT,
- body: cloneBody,
- len: body.dataStream.length,
- });
-
memoryCursor.reset();
memoryCursor.moveCursor(endOffset);
}
@@ -240,7 +258,8 @@ function getCutActionsFromTextRanges(
const memoryCursor = new MemoryCursor();
memoryCursor.reset();
- for (const selection of selections) {
+ for (let i = 0; i < selections.length; i++) {
+ const selection = selections[i];
const { startOffset, endOffset, collapsed } = selection;
if (startOffset == null || endOffset == null) {
@@ -255,7 +274,7 @@ function getCutActionsFromTextRanges(
len,
});
} else {
- textX.push(...BuildTextUtils.selection.getDeleteExcludeLastLineBreakActions(selection, originBody, segmentId, memoryCursor.cursor, false));
+ textX.push(...BuildTextUtils.selection.delete([selection], originBody, memoryCursor.cursor, null, selections.length === 1));
}
memoryCursor.reset();
diff --git a/packages/docs-ui/src/commands/commands/core-editing.command.ts b/packages/docs-ui/src/commands/commands/core-editing.command.ts
index 92788c4c65..eef7ed2d03 100644
--- a/packages/docs-ui/src/commands/commands/core-editing.command.ts
+++ b/packages/docs-ui/src/commands/commands/core-editing.command.ts
@@ -36,7 +36,6 @@ export interface IInsertCommandParams {
range: ITextRange;
segmentId?: string;
cursorOffset?: number;
- extendLastRange?: boolean;
}
export const EditorInsertTextCommandId = 'doc.command.insert-text';
@@ -51,7 +50,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
handler: async (accessor, params: IInsertCommandParams) => {
const commandService = accessor.get(ICommandService);
- const { range, segmentId, body, unitId, cursorOffset, extendLastRange } = params;
+ const { range, segmentId, body, unitId, cursorOffset } = params;
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -67,10 +66,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
if (originBody == null) {
return false;
}
- const actualRange = extendLastRange
- ? BuildTextUtils.selection.getDeleteSelection(range, originBody)
- : BuildTextUtils.selection.getInsertSelection(range, originBody);
- const { startOffset, collapsed } = actualRange;
+ const { startOffset, collapsed } = range;
const cursorMove = cursorOffset ?? body.dataStream.length;
const textRanges = [
{
@@ -101,23 +97,22 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
len: startOffset,
});
}
- } else {
- const { dos, retain } = BuildTextUtils.selection.getDeleteActions(actualRange, segmentId, 0, originBody);
+ textX.push({
+ t: TextXActionType.INSERT,
+ body,
+ len: body.dataStream.length,
+ });
+ } else {
+ const dos = BuildTextUtils.selection.delete([range], originBody, 0, body);
textX.push(...dos);
-
- doMutation.params.textRanges = [{
- startOffset: startOffset + cursorMove + retain,
- endOffset: startOffset + cursorMove + retain,
- collapsed,
- }];
}
- textX.push({
- t: TextXActionType.INSERT,
- body,
- len: body.dataStream.length,
- });
+ doMutation.params.textRanges = [{
+ startOffset: startOffset + cursorMove,
+ endOffset: startOffset + cursorMove,
+ collapsed,
+ }];
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
@@ -157,28 +152,16 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
}
const { startOffset } = range;
- const dataStream = body.dataStream;
const start = direction === DeleteDirection.LEFT ? startOffset - len : startOffset;
- const end = start + len - 1;
- const relativeCustomRanges = body.customRanges?.filter((customRange) => BuildTextUtils.customRange.isIntersecting(customRange.startIndex, customRange.endIndex, start, end));
- const toDeleteRanges = relativeCustomRanges?.filter((customRange) => BuildTextUtils.customRange.shouldDeleteCustomRange(start, len, customRange, dataStream));
- const deleteIndexes: number[] = [];
- for (let i = 0; i < len; i++) {
- deleteIndexes.push(start + i);
- }
- toDeleteRanges?.forEach((range) => {
- deleteIndexes.push(range.startIndex, range.endIndex);
- });
- deleteIndexes.sort((pre, aft) => pre - aft);
- const deleteStart = deleteIndexes[0];
+
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
unitId,
actions: [],
textRanges: [{
- startOffset: deleteStart,
- endOffset: deleteStart,
+ startOffset: start,
+ endOffset: start,
collapsed: true,
}],
debounce: true,
@@ -188,21 +171,16 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
const textX = new TextX();
const jsonX = JSONX.getInstance();
- let cursor = 0;
- for (let i = 0; i < deleteIndexes.length; i++) {
- const deleteIndex = deleteIndexes[i];
- if (deleteIndex - cursor > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: deleteIndex - cursor,
- });
- }
- textX.push({
- t: TextXActionType.DELETE,
- len: 1,
- });
- cursor = deleteIndex + 1;
- }
+ const cursor = 0;
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: start - cursor,
+ });
+
+ textX.push({
+ t: TextXActionType.DELETE,
+ len,
+ });
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index f6382b9a87..cae5540889 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -18,7 +18,6 @@ import type { DocumentDataModel, IAccessor, ICommand, ICustomBlock, IDocumentBod
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import {
- BuildTextUtils,
CommandType,
DataStreamTreeTokenType,
generateRandomId,
@@ -42,8 +41,6 @@ import { getCommandSkeleton, getRichTextEditPath } from '../util';
import { CutContentCommand } from './clipboard.inner.command';
import { DeleteCommand, UpdateCommand } from './core-editing.command';
-const getDeleteSelection = BuildTextUtils.selection.getDeleteSelection;
-
export interface IDeleteCustomBlockParams {
direction: DeleteDirection;
range: ITextRangeWithStyle;
@@ -164,7 +161,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
return false;
}
- const actualRange = getDeleteSelection(activeRange, originBody);
+ const actualRange = activeRange;
const unitId = docDataModel.getUnitId();
const { startOffset, collapsed } = actualRange;
@@ -362,7 +359,7 @@ export const DeleteLeftCommand: ICommand = {
return false;
}
- const actualRange = getDeleteSelection(activeRange, body);
+ const actualRange = activeRange;
const { startOffset, collapsed } = actualRange;
const curGlyph = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage);
@@ -572,7 +569,7 @@ export const DeleteRightCommand: ICommand = {
return false;
}
- const actualRange = getDeleteSelection(activeRange, body, DeleteDirection.RIGHT);
+ const actualRange = activeRange;
const { startOffset, endOffset, collapsed } = actualRange;
// No need to delete when the cursor is at the last position of the last paragraph.
if (startOffset === body.dataStream.length - 2 && collapsed) {
diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.ts
index bb22a9bac9..da1b60e0bc 100644
--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts
+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts
@@ -16,10 +16,10 @@
import type { DocumentDataModel, ICommand, ICommandInfo } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import { BuildTextUtils, CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, ICommandService, IUniverInstanceService, JSONX, SHEET_EDITOR_UNITS, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService, type ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getTextRunAtPosition } from '../../basics/paragraph';
+import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';
import { DocIMEInputManagerService } from '../../services/doc-ime-input-manager.service';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { getRichTextEditPath } from '../util';
@@ -32,6 +32,8 @@ export interface IIMEInputCommandParams {
isCompositionEnd: boolean;
}
+const UNITS = SHEET_EDITOR_UNITS;
+
export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
id: 'doc.command.ime-input',
@@ -64,7 +66,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
return false;
}
- const insertRange = BuildTextUtils.selection.getInsertSelection(previousActiveRange, body);
+ const insertRange = previousActiveRange;
Object.assign(previousActiveRange, insertRange);
const { startOffset, endOffset } = previousActiveRange;
@@ -90,6 +92,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
const defaultTextStyle = docMenuStyleService.getDefaultStyle();
const styleCache = docMenuStyleService.getStyleCache();
+ const curCustomRange = getCustomRangeAtPosition(body.customRanges ?? [], startOffset + oldTextLen, UNITS.includes(unitId));
const curTextRun = getTextRunAtPosition(
body.textRuns ?? [],
isCompositionStart ? endOffset : startOffset + oldTextLen,
@@ -97,17 +100,16 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
styleCache
);
+ const customDecorations = getCustomDecorationAtPosition(body.customDecorations ?? [], startOffset + oldTextLen);
const textX = new TextX();
const jsonX = JSONX.getInstance();
if (!previousActiveRange.collapsed && isCompositionStart) {
- const { dos, retain } = BuildTextUtils.selection.getDeleteActions(previousActiveRange, segmentId, 0, body);
-
+ const dos = BuildTextUtils.selection.delete([previousActiveRange], body, 0, null, false);
textX.push(...dos);
-
doMutation.params!.textRanges = [{
- startOffset: startOffset + len + retain,
- endOffset: startOffset + len + retain,
+ startOffset: startOffset + len,
+ endOffset: startOffset + len,
collapsed: true,
}];
} else {
@@ -135,6 +137,18 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
ed: newText.length,
}]
: [],
+ customRanges: curCustomRange
+ ? [{
+ ...curCustomRange,
+ startIndex: 0,
+ endIndex: newText.length,
+ }]
+ : [],
+ customDecorations: customDecorations.map((customDecoration) => ({
+ ...customDecoration,
+ startIndex: 0,
+ endIndex: newText.length,
+ })),
},
len: newText.length,
});
diff --git a/packages/docs-ui/src/commands/commands/replace-content.command.ts b/packages/docs-ui/src/commands/commands/replace-content.command.ts
index 61832307a7..ecbe96c5a8 100644
--- a/packages/docs-ui/src/commands/commands/replace-content.command.ts
+++ b/packages/docs-ui/src/commands/commands/replace-content.command.ts
@@ -334,13 +334,7 @@ export const ReplaceSelectionCommand: ICommand<IReplaceSelectionCommandParams> =
const textX = new TextX();
const jsonX = JSONX.getInstance();
// delete
- textX.push(...BuildTextUtils.selection.getDeleteExcludeLastLineBreakActions(selection, body, '', 0, false));
- // insert
- textX.push({
- t: TextXActionType.INSERT,
- body: insertBody,
- len: insertBody.dataStream.length,
- });
+ textX.push(...BuildTextUtils.selection.delete([selection], body, 0, insertBody));
doMutation.params.actions = jsonX.editOp(textX.serialize());
return true;
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
index 654b5d5eb6..b6ccd7b26f 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
@@ -17,7 +17,7 @@
import type { ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { BuildTextUtils, CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getCommandSkeleton, getRichTextEditPath } from '../../util';
import { generateParagraphs } from '../break-line.command';
@@ -61,7 +61,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
if (skeleton == null) {
return false;
}
- const { startOffset } = BuildTextUtils.selection.getInsertSelection(activeRange, body);
+ const { startOffset } = activeRange;
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index 1989016b22..72be712078 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -264,8 +264,6 @@ export class DocMoveCursorController extends Disposable {
}
}
const skipTokens: string[] = [
- DataStreamTreeTokenType.CUSTOM_RANGE_START,
- DataStreamTreeTokenType.CUSTOM_RANGE_END,
DataStreamTreeTokenType.TABLE_START,
DataStreamTreeTokenType.TABLE_END,
DataStreamTreeTokenType.TABLE_ROW_START,
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
index a4c07b8d01..2113daf30e 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
@@ -17,9 +17,9 @@
import type { DocumentDataModel, Nullable } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import type { Subscription } from 'rxjs';
-import { Disposable, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, Inject } from '@univerjs/core';
+import { Disposable, ICommandService, Inject, SHEET_EDITOR_UNITS } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
-import { getTextRunAtPosition } from '../../basics/paragraph';
+import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';
import { AfterSpaceCommand } from '../../commands/commands/auto-format.command';
import { InsertCommand } from '../../commands/commands/core-editing.command';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
@@ -69,14 +69,16 @@ export class DocInputController extends Disposable implements IRenderModule {
}
const { segmentId } = activeRange;
- const UNITS = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
+
const docDataModel = this._context.unit;
const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
// Insert content's style should follow the text style of the current position.
const defaultTextStyle = this._docMenuStyleService.getDefaultStyle();
const cacheStyle = this._docMenuStyleService.getStyleCache();
+ const curCustomRange = getCustomRangeAtPosition(originBody?.customRanges ?? [], activeRange.endOffset, SHEET_EDITOR_UNITS.includes(unitId));
const curTextRun = getTextRunAtPosition(originBody?.textRuns ?? [], activeRange.endOffset, defaultTextStyle, cacheStyle);
+ const curCustomDecorations = getCustomDecorationAtPosition(originBody?.customDecorations ?? [], activeRange.endOffset);
await this._commandService.executeCommand(InsertCommand.id, {
unitId,
@@ -91,10 +93,21 @@ export class DocInputController extends Disposable implements IRenderModule {
},
]
: [],
+ customRanges: curCustomRange
+ ? [{
+ ...curCustomRange,
+ startIndex: 0,
+ endIndex: content.length,
+ }]
+ : [],
+ customDecorations: curCustomDecorations.map((customDecoration) => ({
+ ...customDecoration,
+ startIndex: 0,
+ endIndex: content.length,
+ })),
},
range: activeRange,
segmentId,
- extendLastRange: UNITS.includes(unitId),
});
// Space
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
index 0b288dc897..4cbe544803 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
@@ -91,7 +91,10 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
return;
}
- this._docSelectionManagerService.__replaceTextRangesWithNoRefresh(params);
+ this._docSelectionManagerService.__replaceTextRangesWithNoRefresh(params, {
+ unitId: this._context.unitId,
+ subUnitId: this._context.unitId,
+ });
})
);
}
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 3eaa677c6f..f01967ee6d 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -131,7 +131,6 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
async legacyPaste(html?: string, text?: string): Promise<boolean> {
const partDocData = this._genDocDataFromHtmlAndText(html, text);
-
// 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) {
@@ -279,8 +278,6 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
(documentBodyList.length > 1
? documentBodyList.map((body) => body.dataStream).join('\n')
: documentBodyList[0].dataStream)
- .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')
- .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '')
.replaceAll(DataStreamTreeTokenType.TABLE_START, '')
.replaceAll(DataStreamTreeTokenType.TABLE_END, '')
.replaceAll(DataStreamTreeTokenType.TABLE_ROW_START, '')
@@ -385,7 +382,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
continue;
}
- const deleteRange = BuildTextUtils.selection.getDeleteSelection({ startOffset, endOffset, collapsed }, body);
+ const deleteRange = { startOffset, endOffset, collapsed };
const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
if (docBody == null) {
@@ -394,7 +391,6 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
results.push(docBody);
}
-
return {
bodyList: results,
needCache,
diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
index 43dd3dbc29..75776d2c32 100644
--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import { CustomRangeType, DataStreamTreeTokenType, generateRandomId, skipParseTagNames, Tools } from '@univerjs/core';
import type { IDocumentBody, IDocumentData, ITable, ITextStyle, Nullable } from '@univerjs/core';
+import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';
+import { CustomRangeType, DataStreamTreeTokenType, generateRandomId, skipParseTagNames, Tools } from '@univerjs/core';
import { genTableSource, getEmptyTableCell, getEmptyTableRow, getTableColumn } from '../../../commands/commands/table/table';
import { extractNodeStyle } from './parse-node-style';
import parseToDom from './parse-to-dom';
-import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';
function matchFilter(node: HTMLElement, filter: IStyleRule['filter']) {
const tagName = node.tagName.toLowerCase();
@@ -285,13 +285,7 @@ export class HtmlToUDMService {
private _processBeforeLink(node: HTMLElement, doc: Partial<IDocumentData>) {
const body = doc.body!;
- const element = node as HTMLElement;
- const start = body.dataStream.length;
- if (element.tagName.toUpperCase() === 'A') {
- body.dataStream += DataStreamTreeTokenType.CUSTOM_RANGE_START;
- }
-
- return start;
+ return body.dataStream.length;
}
private _processAfterLink(node: HTMLElement, doc: Partial<IDocumentData>, start: number) {
@@ -299,7 +293,6 @@ export class HtmlToUDMService {
const element = node as HTMLElement;
if (element.tagName.toUpperCase() === 'A') {
- body.dataStream += DataStreamTreeTokenType.CUSTOM_RANGE_END;
body.customRanges = body.customRanges ?? [];
body.customRanges.push({
startIndex: start,
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
index 5c0eb9327e..42b86b71f0 100644
--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
@@ -15,8 +15,8 @@
*/
import type { IDocumentBody, IParagraph, ITextRun } from '@univerjs/core';
-import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, Tools } from '@univerjs/core';
import type { DataStreamTreeNode } from '@univerjs/engine-render';
+import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, Tools } from '@univerjs/core';
import { parseDataStreamToTree } from '@univerjs/engine-render';
export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {
@@ -126,7 +126,7 @@ export function getBodySliceHtml(body: IDocumentBody, startIndex: number, endInd
const { startIndex, endIndex, rangeType, rangeId } = range;
const preHtml = getBodyInlineSlice(body, cursorIndex, startIndex);
html += preHtml;
- const sliceHtml = getBodyInlineSlice(body, startIndex + 1, endIndex);
+ const sliceHtml = getBodyInlineSlice(body, startIndex, endIndex + 1);
switch (rangeType) {
case CustomRangeType.HYPERLINK: {
html += `<a data-rangeid="${rangeId}" href="${range.properties?.url ?? ''}">${sliceHtml}</a>`;
diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.ts
index ae615912fd..0c6e6ad48e 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -40,7 +40,7 @@ interface IBulletBound {
}
const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, skeleton: DocumentSkeleton, pageIndex: number): IBoundRectNoAngle[] | undefined => {
- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, pageIndex);
+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, pageIndex);
const skeletonData = skeleton.getSkeletonData();
let end = range.endOffset;
if (range.segmentId) {
@@ -49,7 +49,7 @@ const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, ske
end = Math.min(root.ed, end);
}
}
- const endPosition = skeleton.findNodePositionByCharIndex(end, false, range.segmentId, pageIndex);
+ const endPosition = skeleton.findNodePositionByCharIndex(end, true, range.segmentId, pageIndex);
if (!endPosition || !startPosition) {
return;
}
@@ -104,7 +104,7 @@ interface IBulletActive {
export class DocEventManagerService extends Disposable implements IRenderModule {
private readonly _hoverCustomRanges$ = new BehaviorSubject<ICustomRangeActive[]>([]);
- readonly hoverCustomRanges$ = this._hoverCustomRanges$.pipe(distinctUntilChanged((pre, aft) => pre.length === aft.length && pre.every((item, i) => aft[i].range.rangeId === item.range.rangeId && aft[i].segmentId === item.segmentId && aft[i].segmentPageIndex === item.segmentPageIndex)));
+ readonly hoverCustomRanges$ = this._hoverCustomRanges$.pipe(distinctUntilChanged((pre, aft) => pre.length === aft.length && pre.every((item, i) => aft[i].range.rangeId === item.range.rangeId && aft[i].segmentId === item.segmentId && aft[i].segmentPageIndex === item.segmentPageIndex && aft[i].range.startIndex === item.range.startIndex)));
private readonly _clickCustomRanges$ = new Subject<ICustomRangeActive>();
readonly clickCustomRanges$ = this._clickCustomRanges$.asObservable();
@@ -225,7 +225,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
customRanges.forEach((range) => {
const textRange: ITextRangeParam = {
startOffset: range.startIndex,
- endOffset: range.endIndex,
+ endOffset: range.endIndex + 1,
collapsed: false,
segmentId,
};
diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.ts
index 38819645f0..35ada0b12a 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -14,14 +14,15 @@
* limitations under the License.
*/
+import type { IDisposable, INeedCheckDisposable, ITextRangeParam } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
+import type { IPopup } from '@univerjs/ui';
import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService } from '@univerjs/core';
-import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService, pxToNum } from '@univerjs/engine-render';
import { ICanvasPopupService } from '@univerjs/ui';
import { BehaviorSubject, map } from 'rxjs';
-import type { IDisposable, INeedCheckDisposable, ITextRangeParam } from '@univerjs/core';
-import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
-import type { IPopup } from '@univerjs/ui';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
import { NodePositionConvertToCursor } from './selection/convert-text-range';
@@ -92,8 +93,8 @@ export interface IDocCanvasPopup extends Pick<IPopup, 'direction' | 'excludeOuts
export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {
const { scene, mainComponent, engine } = currentRender;
const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, range.segmentPage);
- const endPosition = skeleton.findNodePositionByCharIndex(range.endOffset, false, range.segmentId, range.segmentPage);
+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, range.segmentPage);
+ const endPosition = skeleton.findNodePositionByCharIndex(range.endOffset, true, range.segmentId, range.segmentPage);
const document = mainComponent as Documents;
if (!endPosition || !startPosition) {
@@ -168,8 +169,11 @@ export class DocCanvasPopManagerService extends Disposable {
const disposable = new DisposableCollection();
disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
- if (commandInfo.id === SetDocZoomRatioOperation.id) {
- position$.next(calc());
+ if (commandInfo.id === SetDocZoomRatioOperation.id || commandInfo.id === RichTextEditingMutation.id) {
+ const newPosition = calc();
+ if (newPosition) {
+ position$.next(newPosition);
+ }
}
}));
@@ -193,10 +197,13 @@ export class DocCanvasPopManagerService extends Disposable {
const disposable = new DisposableCollection();
disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
- if (commandInfo.id === SetDocZoomRatioOperation.id) {
- const position = calcDocRangePositions(range, currentRender);
- if (position) {
- positions$.next(position);
+ if (commandInfo.id === SetDocZoomRatioOperation.id || commandInfo.id === RichTextEditingMutation.id) {
+ const params = commandInfo.params as IRichTextEditingMutationParams;
+ if (params.unitId === currentRender.unitId) {
+ const position = calcDocRangePositions(range, currentRender);
+ if (position) {
+ positions$.next(position);
+ }
}
}
}));
diff --git a/packages/docs/src/services/doc-selection-manager.service.ts b/packages/docs/src/services/doc-selection-manager.service.ts
index 075017c830..e837a05d81 100644
--- a/packages/docs/src/services/doc-selection-manager.service.ts
+++ b/packages/docs/src/services/doc-selection-manager.service.ts
@@ -222,14 +222,14 @@ export class DocSelectionManagerService extends RxDisposable {
}
// Only use in doc-selection-render.controller.ts
- __replaceTextRangesWithNoRefresh(textSelectionInfo: IDocSelectionInnerParam) {
+ __replaceTextRangesWithNoRefresh(textSelectionInfo: IDocSelectionInnerParam, search: IDocSelectionManagerSearchParam) {
if (this._currentSelection == null) {
return;
}
const params = {
- ...this._currentSelection,
...textSelectionInfo,
+ ...search,
};
// Store the textSelectionInfo.
diff --git a/packages/docs/src/utils/custom-range-factory.ts b/packages/docs/src/utils/custom-range-factory.ts
index f3d8103391..8215901115 100644
--- a/packages/docs/src/utils/custom-range-factory.ts
+++ b/packages/docs/src/utils/custom-range-factory.ts
@@ -111,6 +111,7 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAd
properties,
body,
});
+
if (!textX) {
return false;
}
@@ -120,7 +121,7 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAd
params: {
unitId,
actions: [],
- textRanges: undefined,
+ textRanges: textX.selections,
},
textX,
};
@@ -139,15 +140,12 @@ export interface IDeleteCustomRangeFactoryParams {
export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeFactoryParams) {
const { unitId, segmentId, insert } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const docSelectionManagerService = accessor.get(DocSelectionManagerService);
- const selection = docSelectionManagerService.getTextRanges({ unitId, subUnitId: unitId })?.[0];
const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);
if (!documentDataModel) {
return false;
}
- const textRange = selection?.collapsed ? { index: selection.startOffset } : undefined;
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
@@ -164,7 +162,6 @@ export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCus
rangeId: params.rangeId,
insert,
segmentId,
- textRange,
});
if (!textX) {
@@ -173,6 +170,6 @@ export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCus
const path = getRichTextEditPath(documentDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
- doMutation.params.textRanges = textRange ? [{ startOffset: textRange.index, endOffset: textRange.index, collapsed: true }] : undefined;
+ doMutation.params.textRanges = textX.selections;
return doMutation;
}
diff --git a/packages/docs/src/utils/replace-selection-factory.ts b/packages/docs/src/utils/replace-selection-factory.ts
index 069fadbc86..395345761c 100644
--- a/packages/docs/src/utils/replace-selection-factory.ts
+++ b/packages/docs/src/utils/replace-selection-factory.ts
@@ -70,6 +70,7 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSel
body: insertBody,
doc: docDataModel,
});
+
if (!textX) {
return false;
}
diff --git a/packages/engine-formula/src/functions/compatibility/hypgeomdist/index.ts b/packages/engine-formula/src/functions/compatibility/hypgeomdist/index.ts
index 66e1cfc684..87dd68aa5f 100644
--- a/packages/engine-formula/src/functions/compatibility/hypgeomdist/index.ts
+++ b/packages/engine-formula/src/functions/compatibility/hypgeomdist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { hypergeometricPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Hypgeomdist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/compatibility/lognormdist/index.ts b/packages/engine-formula/src/functions/compatibility/lognormdist/index.ts
index f86d57bd77..139b21976d 100644
--- a/packages/engine-formula/src/functions/compatibility/lognormdist/index.ts
+++ b/packages/engine-formula/src/functions/compatibility/lognormdist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { lognormalCDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Lognormdist extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/beta-dist/index.ts b/packages/engine-formula/src/functions/statistical/beta-dist/index.ts
index c29aba0f02..80faed346e 100644
--- a/packages/engine-formula/src/functions/statistical/beta-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/beta-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { betaCDF, betaPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class BetaDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/beta-inv/index.ts b/packages/engine-formula/src/functions/statistical/beta-inv/index.ts
index 5f055aa828..f2f568c2a4 100644
--- a/packages/engine-formula/src/functions/statistical/beta-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/beta-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { betaINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class BetaInv extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/binom-dist-range/index.ts b/packages/engine-formula/src/functions/statistical/binom-dist-range/index.ts
index 9ceec1e95c..50051829c6 100644
--- a/packages/engine-formula/src/functions/statistical/binom-dist-range/index.ts
+++ b/packages/engine-formula/src/functions/statistical/binom-dist-range/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { binomialPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class BinomDistRange extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/binom-dist/index.ts b/packages/engine-formula/src/functions/statistical/binom-dist/index.ts
index 36a8eba1b6..352a6ff6fe 100644
--- a/packages/engine-formula/src/functions/statistical/binom-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/binom-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { binomialCDF, binomialPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class BinomDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/binom-inv/index.ts b/packages/engine-formula/src/functions/statistical/binom-inv/index.ts
index 0ad61bdeb6..32de153d1b 100644
--- a/packages/engine-formula/src/functions/statistical/binom-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/binom-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { binomialCDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class BinomInv extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/chisq-dist-rt/index.ts b/packages/engine-formula/src/functions/statistical/chisq-dist-rt/index.ts
index bf70007989..5af943aba6 100644
--- a/packages/engine-formula/src/functions/statistical/chisq-dist-rt/index.ts
+++ b/packages/engine-formula/src/functions/statistical/chisq-dist-rt/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { chisquareCDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ChisqDistRt extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/chisq-dist/index.ts b/packages/engine-formula/src/functions/statistical/chisq-dist/index.ts
index 4f48fdf0f1..a2438620dc 100644
--- a/packages/engine-formula/src/functions/statistical/chisq-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/chisq-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { chisquareCDF, chisquarePDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ChisqDist extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/chisq-inv/index.ts b/packages/engine-formula/src/functions/statistical/chisq-inv/index.ts
index 4a01b390c6..ed762a817b 100644
--- a/packages/engine-formula/src/functions/statistical/chisq-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/chisq-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { chisquareINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ChisqInv extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/confidence-norm/index.ts b/packages/engine-formula/src/functions/statistical/confidence-norm/index.ts
index d6f62fb91f..4ea42c3c40 100644
--- a/packages/engine-formula/src/functions/statistical/confidence-norm/index.ts
+++ b/packages/engine-formula/src/functions/statistical/confidence-norm/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { normalINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ConfidenceNorm extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/confidence-t/index.ts b/packages/engine-formula/src/functions/statistical/confidence-t/index.ts
index 2f02099ab8..b9be93ee9a 100644
--- a/packages/engine-formula/src/functions/statistical/confidence-t/index.ts
+++ b/packages/engine-formula/src/functions/statistical/confidence-t/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { studentTINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ConfidenceT extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/expon-dist/index.ts b/packages/engine-formula/src/functions/statistical/expon-dist/index.ts
index 30d097d91b..9aad435b27 100644
--- a/packages/engine-formula/src/functions/statistical/expon-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/expon-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { exponentialCDF, exponentialPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class ExponDist extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/f-dist-rt/index.ts b/packages/engine-formula/src/functions/statistical/f-dist-rt/index.ts
index ca741474ba..d950c25f39 100644
--- a/packages/engine-formula/src/functions/statistical/f-dist-rt/index.ts
+++ b/packages/engine-formula/src/functions/statistical/f-dist-rt/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { centralFCDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class FDistRt extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/f-dist/index.ts b/packages/engine-formula/src/functions/statistical/f-dist/index.ts
index 4fb02bf412..697cb77c03 100644
--- a/packages/engine-formula/src/functions/statistical/f-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/f-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { centralFCDF, centralFPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class FDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/f-inv-rt/index.ts b/packages/engine-formula/src/functions/statistical/f-inv-rt/index.ts
index 2cc0772c97..7b23dfb2c2 100644
--- a/packages/engine-formula/src/functions/statistical/f-inv-rt/index.ts
+++ b/packages/engine-formula/src/functions/statistical/f-inv-rt/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { centralFINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class FInvRt extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/f-inv/index.ts b/packages/engine-formula/src/functions/statistical/f-inv/index.ts
index 1880848352..4be5659317 100644
--- a/packages/engine-formula/src/functions/statistical/f-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/f-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { centralFINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class FInv extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/frequency/index.ts b/packages/engine-formula/src/functions/statistical/frequency/index.ts
index 9351c6b07f..15b0eccb49 100644
--- a/packages/engine-formula/src/functions/statistical/frequency/index.ts
+++ b/packages/engine-formula/src/functions/statistical/frequency/index.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { isRealNum } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
import { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
export class Frequency extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/gamma-dist/index.ts b/packages/engine-formula/src/functions/statistical/gamma-dist/index.ts
index 8fd2b07f26..0c856d6ac2 100644
--- a/packages/engine-formula/src/functions/statistical/gamma-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/gamma-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { gammaCDF, gammaPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class GammaDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/gauss/index.ts b/packages/engine-formula/src/functions/statistical/gauss/index.ts
index 26a64b568d..dcee2bae6e 100644
--- a/packages/engine-formula/src/functions/statistical/gauss/index.ts
+++ b/packages/engine-formula/src/functions/statistical/gauss/index.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { normalCDF } from '../../../basics/statistical';
import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-variant-error';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
export class Gauss extends BaseFunction {
override minParams = 1;
diff --git a/packages/engine-formula/src/functions/statistical/intercept/index.ts b/packages/engine-formula/src/functions/statistical/intercept/index.ts
index bafe35e611..7afa616dc0 100644
--- a/packages/engine-formula/src/functions/statistical/intercept/index.ts
+++ b/packages/engine-formula/src/functions/statistical/intercept/index.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { forecastLinear, getTwoArrayNumberValues } from '../../../basics/statistical';
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Intercept extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/lognorm-dist/index.ts b/packages/engine-formula/src/functions/statistical/lognorm-dist/index.ts
index b90ed74eca..aedc6938bc 100644
--- a/packages/engine-formula/src/functions/statistical/lognorm-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/lognorm-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { lognormalCDF, lognormalPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class LognormDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/norm-dist/index.ts b/packages/engine-formula/src/functions/statistical/norm-dist/index.ts
index ac1bf29ec8..6bfd746cf7 100644
--- a/packages/engine-formula/src/functions/statistical/norm-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/norm-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { normalCDF, normalPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class NormDist extends BaseFunction {
override minParams = 4;
diff --git a/packages/engine-formula/src/functions/statistical/norm-inv/index.ts b/packages/engine-formula/src/functions/statistical/norm-inv/index.ts
index 4a0d954a0e..1e0b64fee1 100644
--- a/packages/engine-formula/src/functions/statistical/norm-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/norm-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { normalINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class NormInv extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/norm-s-dist/index.ts b/packages/engine-formula/src/functions/statistical/norm-s-dist/index.ts
index bc019e9850..42eca43ab9 100644
--- a/packages/engine-formula/src/functions/statistical/norm-s-dist/index.ts
+++ b/packages/engine-formula/src/functions/statistical/norm-s-dist/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { normalCDF, normalPDF } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class NormSDist extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/pearson/index.ts b/packages/engine-formula/src/functions/statistical/pearson/index.ts
index 04e989d522..8804d06ebc 100644
--- a/packages/engine-formula/src/functions/statistical/pearson/index.ts
+++ b/packages/engine-formula/src/functions/statistical/pearson/index.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { getTwoArrayNumberValues } from '../../../basics/statistical';
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Pearson extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/prob/index.ts b/packages/engine-formula/src/functions/statistical/prob/index.ts
index 8d26993a65..5c9e9c81f0 100644
--- a/packages/engine-formula/src/functions/statistical/prob/index.ts
+++ b/packages/engine-formula/src/functions/statistical/prob/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { getTwoArrayNumberValues } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Prob extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/quartile-exc/index.ts b/packages/engine-formula/src/functions/statistical/quartile-exc/index.ts
index d98388dc62..3839d9e00f 100644
--- a/packages/engine-formula/src/functions/statistical/quartile-exc/index.ts
+++ b/packages/engine-formula/src/functions/statistical/quartile-exc/index.ts
@@ -14,14 +14,14 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { isRealNum } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-variant-error';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
export class QuartileExc extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/quartile-inc/index.ts b/packages/engine-formula/src/functions/statistical/quartile-inc/index.ts
index 043c215251..0a0f3f5292 100644
--- a/packages/engine-formula/src/functions/statistical/quartile-inc/index.ts
+++ b/packages/engine-formula/src/functions/statistical/quartile-inc/index.ts
@@ -14,14 +14,14 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { isRealNum } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-variant-error';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
export class QuartileInc extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/slope/index.ts b/packages/engine-formula/src/functions/statistical/slope/index.ts
index 4eddf26b80..7b8819aaa2 100644
--- a/packages/engine-formula/src/functions/statistical/slope/index.ts
+++ b/packages/engine-formula/src/functions/statistical/slope/index.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { getTwoArrayNumberValues } from '../../../basics/statistical';
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Slope extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/standardize/index.ts b/packages/engine-formula/src/functions/statistical/standardize/index.ts
index ee75c09c50..eb9ccd0649 100644
--- a/packages/engine-formula/src/functions/statistical/standardize/index.ts
+++ b/packages/engine-formula/src/functions/statistical/standardize/index.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-variant-error';
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Standardize extends BaseFunction {
override minParams = 3;
diff --git a/packages/engine-formula/src/functions/statistical/t-inv-2t/index.ts b/packages/engine-formula/src/functions/statistical/t-inv-2t/index.ts
index b6f5a41c71..7ea8a79dcf 100644
--- a/packages/engine-formula/src/functions/statistical/t-inv-2t/index.ts
+++ b/packages/engine-formula/src/functions/statistical/t-inv-2t/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { studentTINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class TInv2t extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/t-inv/index.ts b/packages/engine-formula/src/functions/statistical/t-inv/index.ts
index 2005115ece..4659fc7e57 100644
--- a/packages/engine-formula/src/functions/statistical/t-inv/index.ts
+++ b/packages/engine-formula/src/functions/statistical/t-inv/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../basics/error-type';
import { studentTINV } from '../../../basics/statistical';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
@@ -21,7 +22,6 @@ import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class TInv extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/statistical/trimmean/index.ts b/packages/engine-formula/src/functions/statistical/trimmean/index.ts
index d1239988b5..f69727c65f 100644
--- a/packages/engine-formula/src/functions/statistical/trimmean/index.ts
+++ b/packages/engine-formula/src/functions/statistical/trimmean/index.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { isRealNum } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
import { checkVariantsErrorIsStringToNumber } from '../../../engine/utils/check-variant-error';
@@ -21,8 +23,6 @@ import { floor } from '../../../engine/utils/math-kit';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
export class Trimmean extends BaseFunction {
override minParams = 2;
diff --git a/packages/engine-formula/src/functions/text/char/index.ts b/packages/engine-formula/src/functions/text/char/index.ts
index ef10e774d4..38ff9961e2 100644
--- a/packages/engine-formula/src/functions/text/char/index.ts
+++ b/packages/engine-formula/src/functions/text/char/index.ts
@@ -32,8 +32,6 @@ const filterCodeArray = Object.values(DataStreamTreeTokenType).filter((value) =>
DataStreamTreeTokenType.TABLE_CELL_END,
DataStreamTreeTokenType.TABLE_ROW_END,
DataStreamTreeTokenType.TABLE_END,
- DataStreamTreeTokenType.CUSTOM_RANGE_START,
- DataStreamTreeTokenType.CUSTOM_RANGE_END,
DataStreamTreeTokenType.CUSTOM_BLOCK,
].includes(value as DataStreamTreeTokenType);
});
diff --git a/packages/engine-formula/src/functions/text/unichar/index.ts b/packages/engine-formula/src/functions/text/unichar/index.ts
index 95d5f679b5..b2b9f0425b 100644
--- a/packages/engine-formula/src/functions/text/unichar/index.ts
+++ b/packages/engine-formula/src/functions/text/unichar/index.ts
@@ -32,8 +32,6 @@ const filterCodeArray = Object.values(DataStreamTreeTokenType).filter((value) =>
DataStreamTreeTokenType.TABLE_CELL_END,
DataStreamTreeTokenType.TABLE_ROW_END,
DataStreamTreeTokenType.TABLE_END,
- DataStreamTreeTokenType.CUSTOM_RANGE_START,
- DataStreamTreeTokenType.CUSTOM_RANGE_END,
DataStreamTreeTokenType.CUSTOM_BLOCK,
].includes(value as DataStreamTreeTokenType);
});
diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
index d4eb802f8c..c210ea0c76 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -885,7 +885,7 @@ export class SheetFindModel extends FindModel {
const isRichText = !!currentContent.p?.body;
if (isRichText) {
const clonedRichText = Tools.deepClone(currentContent.p!);
- replaceInDocumentBody(clonedRichText.body!, findString, replaceString);
+ replaceInDocumentBody(clonedRichText.body!, findString, replaceString, this._query!.caseSensitive);
return { p: clonedRichText };
}
diff --git a/packages/sheets-formula/src/services/function-list/statistical.ts b/packages/sheets-formula/src/services/function-list/statistical.ts
index 0a83fb8955..afe9148c0c 100644
--- a/packages/sheets-formula/src/services/function-list/statistical.ts
+++ b/packages/sheets-formula/src/services/function-list/statistical.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { FUNCTION_NAMES_STATISTICAL, FunctionType } from '@univerjs/engine-formula';
import type { IFunctionInfo } from '@univerjs/engine-formula';
+import { FUNCTION_NAMES_STATISTICAL, FunctionType } from '@univerjs/engine-formula';
export const FUNCTION_LIST_STATISTICAL: IFunctionInfo[] = [
{
diff --git a/packages/sheets-hyper-link-ui/src/controllers/menu.ts b/packages/sheets-hyper-link-ui/src/controllers/menu.ts
index 516f8733be..ae263907e6 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/menu.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/menu.ts
@@ -17,13 +17,13 @@
import type { IAccessor, Nullable, Workbook } from '@univerjs/core';
import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';
import type { IMenuItem, IShortcutItem } from '@univerjs/ui';
-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, IContextService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { getSheetCommandTarget, RangeProtectionPermissionEditPoint, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetInsertHyperlinkPermission, WorksheetSetCellValuePermission } from '@univerjs/sheets';
import { getCurrentRangeDisable$, IEditorBridgeService, whenSheetEditorFocused } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, KeyCode, MenuGroup, MenuItemType, MenuPosition, MetaKeys } from '@univerjs/ui';
-import { distinctUntilChanged, filter, map, of, switchMap } from 'rxjs';
+import { combineLatest, distinctUntilChanged, filter, map, of, switchMap } from 'rxjs';
import { InsertHyperLinkOperation, InsertHyperLinkToolbarOperation } from '../commands/operations/popup.operations';
import { getShouldDisableCellLink, shouldDisableAddLink } from '../utils';
@@ -87,12 +87,17 @@ const getLinkDisable$ = (accessor: IAccessor) => {
const isEditing$ = (editorBridgeService ? editorBridgeService.visible$ : of<Nullable<IEditorBridgeServiceVisibleParam>>(null))
.pipe(map((visible) => visible?.visible ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY : undefined));
+ const focusingFxBarEditor$ = accessor.get(IContextService).subscribeContextValue$(FOCUSING_FX_BAR_EDITOR);
- return isEditing$.pipe(
+ return combineLatest([isEditing$, focusingFxBarEditor$]).pipe(
switchMap(
- (editing) => editing ?
- getEditingLinkDisable$(accessor, editing)
- : of(false)
+ ([editing, focusingFxBarEditor]) => {
+ return editing ?
+ focusingFxBarEditor
+ ? of(true)
+ : getEditingLinkDisable$(accessor, editing)
+ : of(false);
+ }
)
);
})
diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.ts
index d782786677..bb39481eb6 100644
--- a/packages/sheets-hyper-link-ui/src/plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/plugin.ts
@@ -25,10 +25,7 @@ import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.sch
import { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';
import { SheetsHyperLinkPermissionController } from './controllers/hyper-link-permission.controller';
import { SheetsHyperLinkPopupController } from './controllers/popup.controller';
-import { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';
import { SheetsHyperLinkRenderController, SheetsHyperLinkRenderManagerController } from './controllers/render-controllers/render.controller';
-import { SheetsHyperLinkRichTextRefRangeController } from './controllers/rich-text-ref-range.controller';
-import { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';
import { SheetsHyperLinkUIController } from './controllers/ui.controller';
import { SheetHyperLinkUrlController } from './controllers/url.controller';
import { SheetsHyperLinkPopupService } from './services/popup.service';
@@ -62,22 +59,19 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
[SheetsHyperLinkPopupService],
[SheetsHyperLinkSidePanelService],
- [SheetsHyperLinkRemoveSheetController],
[SheetsHyperLinkRenderManagerController],
- [SheetHyperLinkSetRangeController],
+
[SheetsHyperLinkPopupController],
[SheetsHyperLinkUIController],
[SheetsHyperLinkAutoFillController],
[SheetsHyperLinkCopyPasteController],
[SheetsHyperLinkPermissionController],
[SheetHyperLinkUrlController],
- [SheetsHyperLinkRichTextRefRangeController],
+
];
dependencies.forEach((dep) => this._injector.add(dep));
this._injector.get(SheetsHyperLinkRenderManagerController);
- this._injector.get(SheetsHyperLinkRichTextRefRangeController);
- this._injector.get(SheetHyperLinkSetRangeController);
}
override onReady(): void {
@@ -86,7 +80,6 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
this._injector.get(SheetsHyperLinkAutoFillController);
this._injector.get(SheetsHyperLinkCopyPasteController);
- this._injector.get(SheetsHyperLinkRemoveSheetController);
this._injector.get(SheetsHyperLinkUIController);
}
diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
index 104dfe689d..a0b60074c3 100644
--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
@@ -266,7 +266,7 @@ export class SheetsHyperLinkPopupService extends Disposable {
this._editPopup,
DOCS_ZEN_EDITOR_UNIT_ID_KEY
);
- const label = document.getBody()?.dataStream.slice(range.startOffset, range.endOffset - 1);
+ const label = document.getBody()?.dataStream.slice(range.startOffset, range.endOffset);
this._currentEditing$.next({
...link,
label,
@@ -317,7 +317,7 @@ export class SheetsHyperLinkPopupService extends Disposable {
if (link.type === HyperLinkEditSourceType.ZEN_EDITOR) {
const document: Nullable<DocumentDataModel> = this._univerInstanceService.getUnit(DOCS_ZEN_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);
customRange = document?.getBody()?.customRanges?.find((range) => range.rangeId === link.customRangeId);
- label = customRange ? document?.getBody()?.dataStream.slice(customRange.startIndex + 1, customRange.endIndex) : '';
+ label = customRange ? document?.getBody()?.dataStream.slice(customRange.startIndex, customRange.endIndex + 1) : '';
if (!customRange || !label) {
return;
}
diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
index 65d3f9d520..e9ea3fe3ce 100644
--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
@@ -129,7 +129,7 @@ export class SheetsHyperLinkResolverService {
this.navigateToSheetById(unitId, gid);
}
- async navigateToRange(unitId: string, subUnitId: string, range: IRange) {
+ async navigateToRange(unitId: string, subUnitId: string, range: IRange, forceTop?: boolean) {
const worksheet = await this.navigateToSheetById(unitId, subUnitId);
if (worksheet) {
const realRange = getContainRange(range, worksheet);
@@ -146,6 +146,7 @@ export class SheetsHyperLinkResolverService {
);
await this._commandService.executeCommand(ScrollToRangeOperation.id, {
range: realRange,
+ forceTop,
});
}
}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
index ab6d49b833..eb67717ebb 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -16,7 +16,7 @@
import type { DocumentDataModel, Nullable, Workbook } from '@univerjs/core';
import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
-import { BuildTextUtils, ColorKit, CustomRangeType, DisposableCollection, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, ThemeService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
+import { BuildTextUtils, ColorKit, CustomRangeType, DataStreamTreeTokenType, DisposableCollection, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, ThemeService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
import { Button, FormLayout, Input, Select } from '@univerjs/design';
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocBackScrollRenderController, DocSelectionRenderService } from '@univerjs/docs-ui';
@@ -27,7 +27,7 @@ import { RangeSelector } from '@univerjs/sheets-formula-ui';
import { AddHyperLinkCommand, AddRichHyperLinkCommand, SheetHyperLinkType, SheetsHyperLinkParserService, UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '@univerjs/sheets-hyper-link';
import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
import { IZenZoneService, KeyCode, useEvent, useObservable } from '@univerjs/ui';
-import React, { useEffect, useMemo, useRef, useState } from 'react';
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CloseHyperLinkPopupOperation } from '../../commands/operations/popup.operations';
import { isLegalLink, serializeUrl } from '../../common/util';
import { SheetsHyperLinkPopupService } from '../../services/popup.service';
@@ -39,7 +39,7 @@ import styles from './index.module.less';
export const CellLinkEdit = () => {
const [id, setId] = useState('');
const [hide, setHide] = useState(false);
- const [display, setDisplay] = useState('');
+ const [display, _setDisplay] = useState('');
const [showLabel, setShowLabel] = useState(true);
const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
const [payload, setPayload] = useState('');
@@ -81,10 +81,20 @@ export const CellLinkEdit = () => {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
const subUnitId = workbook?.getActiveSheet().getSheetId() || '';
+ // to polyfill the display value on old version data
+ // case split tag is no longer needed
+ const setDisplay = useCallback((value: string) => {
+ _setDisplay(value.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, ''));
+ }, [_setDisplay]);
useEffect(() => {
if (editing?.row !== undefined && editing.col !== undefined) {
- const { label, customRange, row, col } = editing;
+ const { customRange, row, col } = editing;
+ let { label } = editing;
+ if (typeof label === 'number') {
+ label = `${label}`;
+ }
+
let link;
if (customRange) {
link = {
@@ -101,7 +111,7 @@ export const CellLinkEdit = () => {
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 = cell?.v;
- if (cell && (!BuildTextUtils.transform.isEmptyDocument(cell.p?.body?.dataStream) || cellValue)) {
+ if (cell && (!BuildTextUtils.transform.isEmptyDocument(cell.p?.body?.dataStream) || Tools.isDefine(cellValue))) {
setShowLabel(false);
}
link = {
@@ -115,7 +125,7 @@ export const CellLinkEdit = () => {
const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
const currentSelection = textSelectionService.getActiveTextRange();
const body = doc?.getBody();
- const selection = currentSelection && body ? BuildTextUtils.selection.getInsertSelection(currentSelection, body) : null;
+ const selection = currentSelection && body ? currentSelection : null;
const customRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, body?.customRanges ?? [])?.[0];
setShowLabel(false);
@@ -257,6 +267,16 @@ export const CellLinkEdit = () => {
};
}, [contextService, zenZoneService]);
+ useEffect(() => {
+ if (isFocusRangeSelector) {
+ editorBridgeService.enableForceKeepVisible();
+
+ return () => {
+ editorBridgeService.disableForceKeepVisible();
+ };
+ }
+ }, [isFocusRangeSelector, editorBridgeService]);
+
const linkTypeOptions: Array<{
label: string;
value: SheetHyperLinkType | string;
@@ -478,7 +498,7 @@ export const CellLinkEdit = () => {
}
setHide(true);
} else {
- await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col });
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
if (editing.type === HyperLinkEditSourceType.ZEN_EDITOR) {
await commandService.executeCommand(SetSelectionsOperation.id, {
unitId: editing.unitId,
@@ -555,7 +575,7 @@ export const CellLinkEdit = () => {
<Button
onClick={() => {
if (editing) {
- resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col });
+ resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
}
commandService.executeCommand(CloseHyperLinkPopupOperation.id);
}}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx
index cd7b7d7f4c..9e88419cfb 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx
@@ -79,6 +79,10 @@ export const CellLinkPopup = () => {
return;
}
+ if (isError) {
+ return;
+ }
+
resolverService.navigate(linkObj);
}}
>
diff --git a/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
index 1754282634..bffb50378d 100644
--- a/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
+++ b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
@@ -16,7 +16,7 @@
import type { ICellData, ICommand, IDocumentData, IMutationInfo } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { BuildTextUtils, CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools } from '@univerjs/core';
+import { BuildTextUtils, CellValueType, CommandType, CustomRangeType, generateRandomId, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools } from '@univerjs/core';
import { addCustomRangeBySelectionFactory } from '@univerjs/docs';
import { getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
import { AddHyperLinkMutation, HyperLinkModel, type ICellHyperLink, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
@@ -65,10 +65,10 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
collapsed: true,
},
body: {
- dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ dataStream: `${display}`,
customRanges: [{
startIndex: 0,
- endIndex: display.length + 1,
+ endIndex: display.length - 1,
rangeType: CustomRangeType.HYPERLINK,
rangeId: id,
properties: {
diff --git a/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
index ef05d7878f..71d9b28520 100644
--- a/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
+++ b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel, ICellData, ICommand, IMutationInfo } from '@univerjs/core';
-import { CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, getBodySlice, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools, UniverInstanceType } from '@univerjs/core';
+import { CellValueType, CommandType, CustomRangeType, generateRandomId, getBodySlice, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools, UniverInstanceType } from '@univerjs/core';
import { replaceSelectionFactory } from '@univerjs/docs';
import { getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
import { AddHyperLinkMutation, HyperLinkModel, type ICellLinkContent, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
@@ -69,12 +69,12 @@ export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {
const replaceSelection = replaceSelectionFactory(accessor, {
unitId,
body: {
- dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ dataStream: `${display}`,
customRanges: [{
rangeId: newId,
rangeType: CustomRangeType.HYPERLINK,
startIndex: 0,
- endIndex: display.length + 1,
+ endIndex: display.length - 1,
properties: {
url: payload,
},
@@ -191,12 +191,12 @@ export const UpdateRichHyperLinkCommand: ICommand<IUpdateRichHyperLinkCommandPar
const replaceSelection = replaceSelectionFactory(accessor, {
unitId,
body: {
- dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ dataStream: `${display}`,
customRanges: [{
rangeId: newId,
rangeType: CustomRangeType.HYPERLINK,
startIndex: 0,
- endIndex: display.length + 1,
+ endIndex: display.length - 1,
properties: {
url: payload.payload,
},
diff --git a/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts b/packages/sheets-hyper-link/src/controllers/remove-sheet.controller.ts
similarity index 93%
rename from packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts
rename to packages/sheets-hyper-link/src/controllers/remove-sheet.controller.ts
index 3874106507..2d2cc765cb 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts
+++ b/packages/sheets-hyper-link/src/controllers/remove-sheet.controller.ts
@@ -18,7 +18,9 @@ import type { Workbook } from '@univerjs/core';
import type { IRemoveSheetCommandParams } from '@univerjs/sheets';
import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';
-import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { AddHyperLinkMutation } from '../commands/mutations/add-hyper-link.mutation';
+import { RemoveHyperLinkMutation } from '../commands/mutations/remove-hyper-link.mutation';
+import { HyperLinkModel } from '../models/hyper-link.model';
export class SheetsHyperLinkRemoveSheetController extends Disposable {
constructor(
diff --git a/packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts b/packages/sheets-hyper-link/src/controllers/rich-text-ref-range.controller.ts
similarity index 99%
rename from packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts
rename to packages/sheets-hyper-link/src/controllers/rich-text-ref-range.controller.ts
index 87dfc58fc5..3ea2303032 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts
+++ b/packages/sheets-hyper-link/src/controllers/rich-text-ref-range.controller.ts
@@ -19,7 +19,7 @@ import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { CustomRangeType, Disposable, DisposableCollection, ICommandService, Inject, isValidRange, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';
import { RefRangeService, SetRangeValuesMutation } from '@univerjs/sheets';
-import { ERROR_RANGE } from '@univerjs/sheets-hyper-link';
+import { ERROR_RANGE } from '../types/const';
export class SheetsHyperLinkRichTextRefRangeController extends Disposable {
private _refRangeMap: Map<string, Map<string, ObjectMatrix<IDisposable>>> = new Map();
diff --git a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts b/packages/sheets-hyper-link/src/controllers/set-range.controller.ts
similarity index 90%
rename from packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
rename to packages/sheets-hyper-link/src/controllers/set-range.controller.ts
index a341b59b31..d95738fce3 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
+++ b/packages/sheets-hyper-link/src/controllers/set-range.controller.ts
@@ -16,20 +16,18 @@
import type { IMutationInfo, Workbook } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { BuildTextUtils, CustomRangeType, DataStreamTreeTokenType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, Inject, IUniverInstanceService, ObjectMatrix, Range, TextX, Tools, UniverInstanceType } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { BuildTextUtils, CustomRangeType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, Inject, IUniverInstanceService, ObjectMatrix, Range, TextX, Tools, UniverInstanceType } from '@univerjs/core';
import { AFTER_CELL_EDIT, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, getSheetCommandTarget, SetRangeValuesCommand, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
-import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
-import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { AddHyperLinkMutation } from '../commands/mutations/add-hyper-link.mutation';
+import { RemoveHyperLinkMutation } from '../commands/mutations/remove-hyper-link.mutation';
+import { HyperLinkModel } from '../models/hyper-link.model';
export class SheetHyperLinkSetRangeController extends Disposable {
constructor(
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
@@ -171,10 +169,10 @@ export class SheetHyperLinkSetRangeController extends Disposable {
collapsed: false,
},
body: {
- dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${cell.v}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ dataStream: `${cell.v}`,
customRanges: [{
startIndex: 0,
- endIndex: cell.v.length + 1,
+ endIndex: cell.v.length - 1,
rangeId: generateRandomId(),
rangeType: CustomRangeType.HYPERLINK,
properties: {
diff --git a/packages/sheets-hyper-link/src/facade/f-range.ts b/packages/sheets-hyper-link/src/facade/f-range.ts
index 8d90831dfb..bec1616357 100644
--- a/packages/sheets-hyper-link/src/facade/f-range.ts
+++ b/packages/sheets-hyper-link/src/facade/f-range.ts
@@ -17,7 +17,7 @@
import type { IAddHyperLinkCommandParams } from '../commands/commands/add-hyper-link.command';
import type { ICancelHyperLinkCommandParams } from '../commands/commands/remove-hyper-link.command';
import type { IUpdateHyperLinkCommandParams } from '../commands/commands/update-hyper-link.command';
-import { CustomRangeType, generateRandomId } from '@univerjs/core';
+import { CustomRangeType, DataStreamTreeTokenType, generateRandomId } from '@univerjs/core';
import { FRange } from '@univerjs/sheets/facade';
import { AddHyperLinkCommand } from '../commands/commands/add-hyper-link.command';
import { CancelHyperLinkCommand } from '../commands/commands/remove-hyper-link.command';
@@ -39,6 +39,7 @@ interface IFRangeHyperlinkMixin {
getHyperLinks(): ICellHyperLink[];
/**
* Update hyperlink in the cell in the range.
+ * [!important] This method is async.
* @param id id of the hyperlink
* @param url url
* @param label optional, label of the url
@@ -47,6 +48,7 @@ interface IFRangeHyperlinkMixin {
updateHyperLink(id: string, url: string, label?: string): Promise<boolean>;
/**
* Cancel hyperlink in the cell in the range.
+ * [!important] This method is async.
* @param id id of the hyperlink
* @returns success or not
*/
@@ -56,6 +58,13 @@ interface IFRangeHyperlinkMixin {
class FRangeHyperlinkMixin extends FRange implements IFRangeHyperlinkMixin {
// #region hyperlink
+ /**
+ * Set hyperlink in the cell in the range.
+ * [!important] This method is async.
+ * @param url url
+ * @param label optional, label of the url
+ * @returns success or not
+ */
setHyperLink(url: string, label?: string): Promise<boolean> {
const params: IAddHyperLinkCommandParams = {
unitId: this.getUnitId(),
@@ -72,6 +81,10 @@ class FRangeHyperlinkMixin extends FRange implements IFRangeHyperlinkMixin {
return this._commandService.executeCommand(AddHyperLinkCommand.id, params);
}
+ /**
+ * Get all hyperlinks in the cell in the range.
+ * @returns hyperlinks
+ */
override getHyperLinks(): ICellHyperLink[] {
const cellValue = this._worksheet.getCellRaw(this._range.startRow, this._range.startColumn);
if (!cellValue?.p) {
@@ -81,14 +94,22 @@ class FRangeHyperlinkMixin extends FRange implements IFRangeHyperlinkMixin {
return cellValue.p.body?.customRanges
?.filter((range) => range.rangeType === CustomRangeType.HYPERLINK)
.map((range) => ({
- id: range.rangeId,
+ id: `${range.rangeId}_${range.startIndex}_${range.endIndex}`,
startIndex: range.startIndex,
endIndex: range.endIndex,
url: range.properties?.url ?? '',
- label: cellValue.p?.body?.dataStream.slice(range.startIndex + 1, range.endIndex) ?? '',
+ label: cellValue.p?.body?.dataStream.slice(range.startIndex, range.endIndex + 1).replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '') ?? '',
})) ?? [];
}
+ /**
+ * Update hyperlink in the cell in the range.
+ * [!important] This method is async.
+ * @param id id of the hyperlink
+ * @param url url
+ * @param label optional, label of the url
+ * @returns success or not
+ */
override updateHyperLink(id: string, url: string, label?: string): Promise<boolean> {
const params: IUpdateHyperLinkCommandParams = {
unitId: this.getUnitId(),
diff --git a/packages/sheets-hyper-link/src/plugin.ts b/packages/sheets-hyper-link/src/plugin.ts
index 42fdccbe2a..c9c9a81993 100644
--- a/packages/sheets-hyper-link/src/plugin.ts
+++ b/packages/sheets-hyper-link/src/plugin.ts
@@ -19,6 +19,9 @@ import { DependentOn, IConfigService, Inject, Injector, Plugin, registerDependen
import { UniverSheetsPlugin } from '@univerjs/sheets';
import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
import { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';
+import { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';
+import { SheetsHyperLinkRichTextRefRangeController } from './controllers/rich-text-ref-range.controller';
+import { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';
import { SheetsHyperLinkController } from './controllers/sheet-hyper-link.controller';
import { SheetsHyperLinkResourceController } from './controllers/sheet-hyper-link-resource.controller';
import { HyperLinkModel } from './models/hyper-link.model';
@@ -44,17 +47,24 @@ export class UniverSheetsHyperLinkPlugin extends Plugin {
override onStarting(): void {
registerDependencies(this._injector, [
+ [HyperLinkModel],
[SheetsHyperLinkParserService],
[SheetsHyperLinkResourceController],
[SheetsHyperLinkController],
[SheetsHyperLinkRefRangeController],
- [HyperLinkModel],
+ [SheetHyperLinkSetRangeController],
+ [SheetsHyperLinkRemoveSheetController],
+ [SheetsHyperLinkRichTextRefRangeController],
+
]);
touchDependencies(this._injector, [
[SheetsHyperLinkRefRangeController],
[SheetsHyperLinkResourceController],
[SheetsHyperLinkController],
+ [SheetHyperLinkSetRangeController],
+ [SheetsHyperLinkRemoveSheetController],
+ [SheetsHyperLinkRichTextRefRangeController],
]);
}
}
diff --git a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts b/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
index d7564b72db..23ac3048d1 100644
--- a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
@@ -14,15 +14,15 @@
* limitations under the License.
*/
+import type { ICommand, IRange, Nullable } from '@univerjs/core';
+import type { IScrollState } from '../../services/scroll-manager.service';
+
import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-
import { getSheetCommandTarget } from '@univerjs/sheets';
-import type { ICommand, IRange, Nullable } from '@univerjs/core';
import { SheetsScrollRenderController } from '../../controllers/render-controllers/scroll.render-controller';
import { SheetScrollManagerService } from '../../services/scroll-manager.service';
import { SetScrollOperation } from '../operations/scroll.operation';
-import type { IScrollState } from '../../services/scroll-manager.service';
export interface ISetScrollRelativeCommandParams {
offsetX?: number;
@@ -130,6 +130,8 @@ export const ScrollCommand: ICommand<IScrollCommandParams> = {
export interface IScrollToCellCommandParams {
range: IRange;
+ forceTop?: boolean;
+ forceLeft?: boolean;
}
/**
@@ -144,7 +146,7 @@ export const ScrollToCellCommand: ICommand<IScrollToCellCommandParams> = {
const scrollController = renderManagerService
.getRenderById(instanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId())!
.with(SheetsScrollRenderController);
- return scrollController.scrollToRange(params!.range);
+ return scrollController.scrollToRange(params!.range, params!.forceTop, params!.forceLeft);
},
};
diff --git a/packages/sheets-ui/src/commands/operations/scroll-to-range.operation.ts b/packages/sheets-ui/src/commands/operations/scroll-to-range.operation.ts
index a45c1ec4d5..ca06719f60 100644
--- a/packages/sheets-ui/src/commands/operations/scroll-to-range.operation.ts
+++ b/packages/sheets-ui/src/commands/operations/scroll-to-range.operation.ts
@@ -32,6 +32,6 @@ export const ScrollToRangeOperation: ICommand<IScrollToCellCommandParams> = {
.getRenderById(instanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId())!
.with(SheetsScrollRenderController);
- return scrollController.scrollToRange(params.range);
+ return scrollController.scrollToRange(params.range, params.forceTop, params.forceLeft);
},
};
diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.ts
index f21e672cee..34a45bfab0 100644
--- a/packages/sheets-ui/src/common/utils.ts
+++ b/packages/sheets-ui/src/common/utils.ts
@@ -256,6 +256,14 @@ export function getHoverCellPosition(currentRender: IRender, workbook: Workbook,
}
let { actualCol, actualRow } = cellIndex;
+ const originLocation = {
+ unitId,
+ subUnitId: sheetId,
+ workbook,
+ worksheet,
+ row: actualRow,
+ col: actualCol,
+ };
skeleton.overflowCache.forValue((r, c, range) => {
if (range.startRow <= actualRow && range.endRow >= actualRow && range.startColumn <= actualCol && range.endColumn >= actualCol) {
@@ -265,15 +273,6 @@ export function getHoverCellPosition(currentRender: IRender, workbook: Workbook,
});
const actualCell = skeleton.getCellByIndex(actualRow, actualCol);
- const originLocation = {
- unitId,
- subUnitId: sheetId,
- workbook,
- worksheet,
- row: actualCell.actualRow,
- col: actualCell.actualColumn,
- };
-
const location: ISheetLocation = getCellRealRange(workbook, worksheet, skeleton, actualRow, actualCol);
let anchorCell: IRange;
if (actualCell.mergeInfo) {
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index bdb92b79ba..93c5acaef4 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -14,7 +14,17 @@
* limitations under the License.
*/
-import { cellToRange, CustomRangeType, DataStreamTreeTokenType, DEFAULT_STYLES, generateRandomId, IUniverInstanceService, numfmt, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
+import type { IAccessor, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, Nullable } from '@univerjs/core';
+import type {
+ IAddWorksheetMergeMutationParams,
+ IMoveRangeMutationParams,
+ IRemoveWorksheetMergeMutationParams,
+ ISetRangeValuesMutationParams,
+ ISetSelectionsOperationParams,
+} from '@univerjs/sheets';
+import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetDiscreteRangeLocation } from '../../services/clipboard/type';
+import { cellToRange, CustomRangeType, DEFAULT_STYLES, generateRandomId, IUniverInstanceService, numfmt, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
+
import { DEFAULT_PADDING_DATA } from '@univerjs/engine-render';
import {
AddMergeUndoMutationFactory,
@@ -29,18 +39,8 @@ import {
SetSelectionsOperation,
SheetInterceptorService,
} from '@univerjs/sheets';
-import type { IAccessor, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, Nullable } from '@univerjs/core';
-
-import type {
- IAddWorksheetMergeMutationParams,
- IMoveRangeMutationParams,
- IRemoveWorksheetMergeMutationParams,
- ISetRangeValuesMutationParams,
- ISetSelectionsOperationParams,
-} from '@univerjs/sheets';
import { COPY_TYPE } from '../../services/clipboard/type';
import { discreteRangeToRange, type IDiscreteRange, virtualizeDiscreteRanges } from '../utils/range-tools';
-import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetDiscreteRangeLocation } from '../../services/clipboard/type';
// if special paste need append mutations instead of replace the default, it can use this function to generate default mutations.
export function getDefaultOnPasteCellMutations(
@@ -605,7 +605,7 @@ export function getClearAndSetMergeMutations(
export function generateBody(text: string): IDocumentBody {
if (!text.includes('\r') && Tools.isLegalUrl(text)) {
const id = generateRandomId();
- const urlText = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ const urlText = `${text}`;
const range: ICustomRange = {
startIndex: 0,
endIndex: urlText.length - 1,
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index f30b1c8ab1..f7e894905f 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -554,6 +554,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
worksheet = workbook.getActiveSheet();
// If cross-sheet operation, switch current sheet first, then const cellData
+ // This should moved to after cell editor
const cellData: Nullable<ICellData> = getCellDataByInput(
worksheet.getCellRaw(row, column) || {},
documentDataModel,
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
index a809a9020d..ba17e09582 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
@@ -15,6 +15,11 @@
*/
import type { IFreeze, IRange, IWorksheetData, Nullable, Workbook } from '@univerjs/core';
+import type { IMouseEvent, IPoint, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam } from '@univerjs/engine-render';
+import type { IExpandSelectionCommandParams } from '../../../commands/commands/set-selection.command';
+import type { IScrollState, IScrollStateSearchParam, IViewportScrollState } from '../../../services/scroll-manager.service';
+import type { ISheetSkeletonManagerParam } from '../../../services/sheet-skeleton-manager.service';
+
import {
Direction,
Disposable,
@@ -24,16 +29,11 @@ import {
RANGE_TYPE,
toDisposable,
} from '@univerjs/core';
-import type { IMouseEvent, IPoint, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam } from '@univerjs/engine-render';
import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
import { ScrollToCellOperation, SheetsSelectionsService } from '@univerjs/sheets';
-
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
-import type { IExpandSelectionCommandParams } from '../../../commands/commands/set-selection.command';
import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';
-import type { IScrollState, IScrollStateSearchParam, IViewportScrollState } from '../../../services/scroll-manager.service';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
-import type { ISheetSkeletonManagerParam } from '../../../services/sheet-skeleton-manager.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { getSheetObject } from '../../utils/component-tools';
diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
index 5737550df2..52935d4989 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
@@ -61,7 +61,7 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
this._initSkeletonListener();
}
- scrollToRange(range: IRange): boolean {
+ scrollToRange(range: IRange, forceTop?: boolean, forceLeft?: boolean): boolean {
let { endRow, endColumn, startColumn, startRow } = range;
const bounding = this._getViewportBounding();
if (range.rangeType === RANGE_TYPE.ROW) {
@@ -72,12 +72,12 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
endRow = 0;
}
- if (bounding) {
+ if (bounding && !forceTop && !forceLeft) {
const row = bounding.startRow > endRow ? startRow : endRow;
const col = bounding.startColumn > endColumn ? startColumn : endColumn;
return this._scrollToCell(row, col);
} else {
- return this._scrollToCell(startRow, startColumn);
+ return this._scrollToCell(startRow, startColumn, forceTop, forceLeft);
}
}
@@ -479,7 +479,7 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
}
// eslint-disable-next-line max-lines-per-function, complexity
- private _scrollToCell(row: number, column: number): boolean {
+ private _scrollToCell(row: number, column: number, forceTop?: boolean, forceLeft?: boolean): boolean {
const { rowHeightAccumulation, columnWidthAccumulation } = this._sheetSkeletonManagerService.getCurrent()?.skeleton ?? {};
if (rowHeightAccumulation == null || columnWidthAccumulation == null) return false;
@@ -561,8 +561,8 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
startSheetViewColumn = startSheetViewColumn ? Math.min(startSheetViewColumn, column) : startSheetViewColumn;
return this._commandService.syncExecuteCommand(ScrollCommand.id, {
- sheetViewStartRow: startSheetViewRow,
- sheetViewStartColumn: startSheetViewColumn,
+ sheetViewStartRow: forceTop ? Math.max(0, row - freezeYSplit) : startSheetViewRow,
+ sheetViewStartColumn: forceLeft ? Math.max(0, column - freezeXSplit) : startSheetViewColumn,
offsetX: startSheetViewColumn === undefined ? offsetX : 0,
offsetY: startSheetViewRow === undefined ? offsetY : 0,
});
diff --git a/packages/sheets-ui/src/controllers/utils/component-tools.ts b/packages/sheets-ui/src/controllers/utils/component-tools.ts
index a064278f0f..46c5275836 100644
--- a/packages/sheets-ui/src/controllers/utils/component-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/component-tools.ts
@@ -15,7 +15,6 @@
*/
import type { IUniverInstanceService, Nullable } from '@univerjs/core';
-import { UniverInstanceType, Workbook } from '@univerjs/core';
import type {
Engine,
IRenderContext,
@@ -28,6 +27,7 @@ import type {
SpreadsheetSkeleton,
Viewport,
} from '@univerjs/engine-render';
+import { UniverInstanceType, Workbook } from '@univerjs/core';
import { SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { SHEET_VIEW_KEY } from '../../common/keys';
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
index 8a0f499972..90236c6dc5 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
@@ -14,14 +14,10 @@
* limitations under the License.
*/
-import { CustomRangeType, DataStreamTreeTokenType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
-import { handleStringToStyle, textTrim } from '@univerjs/ui';
import type { ICustomRange, IDocumentBody, IDocumentData, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
-
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
-import { extractNodeStyle } from './parse-node-style';
-import parseToDom, { generateParagraphs } from './utils';
import type { ISheetSkeletonManagerParam } from '../../sheet-skeleton-manager.service';
+
import type {
ICellDataWithSpanInfo,
IClipboardPropertyItem,
@@ -29,6 +25,10 @@ import type {
IUniverSheetCopyDataModel,
} from '../type';
import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';
+import { CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
+import { handleStringToStyle, textTrim } from '@univerjs/ui';
+import { extractNodeStyle } from './parse-node-style';
+import parseToDom, { generateParagraphs } from './utils';
export interface IStyleRule {
filter: string | string[] | ((node: HTMLElement) => boolean);
@@ -514,7 +514,6 @@ export class HtmlToUSMService {
return documentModel?.getSnapshot();
}
- // eslint-disable-next-line max-lines-per-function
private process(
parent: Nullable<ChildNode>,
nodes: NodeListOf<ChildNode>,
@@ -543,24 +542,6 @@ export class HtmlToUSMService {
textRuns: [],
};
- // if ((parent as Element).tagName.toUpperCase() === 'A') {
- // const id = Tools.generateRandomId();
- // text = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
- // doc.customRanges = [
- // ...(doc.customRanges ?? []),
- // {
- // startIndex: doc.dataStream.length,
- // endIndex: doc.dataStream.length + text.length - 1,
- // rangeId: id,
- // rangeType: CustomRangeType.HYPERLINK,
- // },
- // ];
- // doc.payloads = {
- // ...doc.payloads,
- // [id]: (parent as HTMLAnchorElement).href,
- // };
- // }
-
doc.dataStream += text;
newDoc.dataStream += text;
if (style && Object.getOwnPropertyNames(style).length) {
@@ -609,13 +590,7 @@ export class HtmlToUSMService {
private _processBeforeLink(node: HTMLElement, doc: Partial<IDocumentData>) {
const body = doc.body!;
- const element = node as HTMLElement;
- const start = body.dataStream.length;
- if (element.tagName.toUpperCase() === 'A') {
- body.dataStream += DataStreamTreeTokenType.CUSTOM_RANGE_START;
- }
-
- return start;
+ return body.dataStream.length;
}
private _processAfterLink(node: HTMLElement, doc: Partial<IDocumentData>, start: number) {
@@ -623,7 +598,6 @@ export class HtmlToUSMService {
const element = node as HTMLElement;
if (element.tagName.toUpperCase() === 'A') {
- body.dataStream += DataStreamTreeTokenType.CUSTOM_RANGE_END;
body.customRanges = body.customRanges ?? [];
body.customRanges.push({
startIndex: start,
diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts
index 93fee7313e..f10b364943 100644
--- a/packages/sheets-ui/src/services/hover-manager.service.ts
+++ b/packages/sheets-ui/src/services/hover-manager.service.ts
@@ -76,6 +76,8 @@ export class HoverManagerService extends Disposable {
&& pre?.location?.col === aft?.location?.col
&& pre?.customRange?.rangeId === aft?.customRange?.rangeId
&& pre?.bullet?.startIndex === aft?.bullet?.startIndex
+ && pre?.customRange?.startIndex === aft?.customRange?.startIndex
+ && pre?.customRange?.endIndex === aft?.customRange?.endIndex
)
),
map((cell) => cell && {
diff --git a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
index a1e4aded74..06a20a8160 100644
--- a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
+++ b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
@@ -25,7 +25,7 @@ import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
const calcDocRangePositions = (range: ITextRangeParam, skeleton: DocumentSkeleton): IBoundRectNoAngle[] | undefined => {
const pageIndex = -1;
- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, pageIndex);
+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, pageIndex);
const skeletonData = skeleton.getSkeletonData();
let end = range.endOffset;
if (range.segmentId) {
@@ -34,7 +34,7 @@ const calcDocRangePositions = (range: ITextRangeParam, skeleton: DocumentSkeleto
end = Math.min(root.ed, end);
}
}
- const endPosition = skeleton.findNodePositionByCharIndex(end, false, range.segmentId, pageIndex);
+ const endPosition = skeleton.findNodePositionByCharIndex(end, true, range.segmentId, pageIndex);
if (!endPosition || !startPosition) {
return;
}
@@ -237,7 +237,7 @@ export const getCustomRangePosition = (injector: Injector, unitId: string, subUn
right: rect.right + actualCell.mergeInfo.startX + paddingLeft + leftOffset,
})),
customRange,
- label: docSkeleton.getViewModel().getBody()!.dataStream.slice(customRange.startIndex + 1, customRange.endIndex),
+ label: docSkeleton.getViewModel().getBody()!.dataStream.slice(customRange.startIndex, customRange.endIndex + 1),
};
};
@@ -288,6 +288,6 @@ export const getEditingCustomRangePosition = (injector: Injector, unitId: string
right: rect.right + canvasClientRect.left,
})),
customRange,
- label: docSkeleton.getViewModel().getBody()!.dataStream.slice(customRange.startIndex + 1, customRange.endIndex),
+ label: docSkeleton.getViewModel().getBody()!.dataStream.slice(customRange.startIndex, customRange.endIndex + 1),
};
};
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
index 16a3ebdf8a..4a9184f788 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { CustomRangeType, type IDocumentBody } from '@univerjs/core';
import type { IThreadCommentMention } from '@univerjs/thread-comment';
+import { CustomRangeType, type IDocumentBody } from '@univerjs/core';
export type TextNode = {
type: 'text';
@@ -128,6 +128,7 @@ export const transformTextNodes2Document = (nodes: TextNode[]): IDocumentBody =>
rangeType: CustomRangeType.MENTION,
startIndex: start,
endIndex: end,
+ properties: {},
});
break;
}
diff --git a/packages/ui/src/common/menu-hidden-observable.ts b/packages/ui/src/common/menu-hidden-observable.ts
index 4b7469ab37..90a9064a53 100644
--- a/packages/ui/src/common/menu-hidden-observable.ts
+++ b/packages/ui/src/common/menu-hidden-observable.ts
@@ -22,7 +22,7 @@ export function getMenuHiddenObservable(
accessor: IAccessor,
targetUniverType: UniverInstanceType,
matchUnitId?: string,
- needHideUnitId?: string
+ needHideUnitId?: string | string[]
): Observable<boolean> {
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -34,7 +34,7 @@ export function getMenuHiddenObservable(
if (matchUnitId && matchUnitId !== unitId) {
return subscriber.next(true);
}
- if (needHideUnitId && needHideUnitId === unitId) {
+ if (needHideUnitId && (Array.isArray(needHideUnitId) ? needHideUnitId.includes(unitId) : needHideUnitId === unitId)) {
return subscriber.next(true);
}
const univerType = univerInstanceService.getUnitType(unitId);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 97577842f0..af82be31c6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1005,6 +1005,9 @@ importers:
'@wendellhu/redi':
specifier: 0.16.1
version: 0.16.1
+ fast-diff:
+ specifier: 1.3.0
+ version: 1.3.0
kdbush:
specifier: ^4.0.2
version: 4.0.2