Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(sheets-hyper-link-ui): sheet link support rich-text mode (#3322)

zhangwd19d224a4260
diff --git a/examples/esbuild.config.mjs b/examples/esbuild.config.mjs
index d3a7773fb8..0075558503 100644
--- a/examples/esbuild.config.mjs
+++ b/examples/esbuild.config.mjs
@@ -115,6 +115,7 @@ const ctx = await esbuild[args.watch ? 'context' : 'build']({
'process.env.BUILD_TIME': `"${new Date().toISOString()}"`,
'process.env.IS_E2E': isE2E ? 'true' : 'false',
},
+
});
if (args.watch) {
diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo.ts b/examples/src/data/sheets/demo/default-workbook-data-demo.ts
index dd7dc36510..d6697b6aee 100644
--- a/examples/src/data/sheets/demo/default-workbook-data-demo.ts
+++ b/examples/src/data/sheets/demo/default-workbook-data-demo.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { IDataValidationRule, IDocumentData, IWorkbookData } from '@univerjs/core';
import { BooleanNumber, DataValidationErrorStyle, DataValidationOperator, DataValidationType, LocaleType } from '@univerjs/core';
-
import { DATA_VALIDATION_PLUGIN_NAME } from '@univerjs/sheets-data-validation';
+
+import type { IDataValidationRule, IDocumentData, IWorkbookData } from '@univerjs/core';
import type { ICellHyperLink } from '@univerjs/sheets-hyper-link';
import { PAGE5_RICHTEXT_1 } from '../../slides/rich-text/page5-richtext1';
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 7f5ee6a8af..8a4e649c42 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -82,8 +82,11 @@ univer.registerPlugin(UniverFormulaEnginePlugin, { notExecuteFormula: true });
univer.registerPlugin(UniverSheetsFormulaPlugin, { notExecuteFormula: true });
// filter plugin
univer.registerPlugin(UniverSheetsFilterPlugin);
-// hyperlink
-univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);
+// mock lazy load
+setTimeout(() => {
+ // hyperlink
+ univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);
+}, 500);
// mock lazy load data validation
setTimeout(() => {
diff --git a/packages-experimental/action-recorder/package.json b/packages-experimental/action-recorder/package.json
index 57ad52e74d..4da0174f13 100644
--- a/packages-experimental/action-recorder/package.json
+++ b/packages-experimental/action-recorder/package.json
@@ -69,7 +69,7 @@
"@univerjs/sheets-ui": "workspace:*",
"@univerjs/ui": "workspace:*",
"clsx": ">=2.0.0",
- "react": ">=16.9.0",
+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0",
"rxjs": ">=7.0.0"
},
"dependencies": {
diff --git a/packages-experimental/uni-formula-ui/src/commands/commands/doc.command.ts b/packages-experimental/uni-formula-ui/src/commands/commands/doc.command.ts
index 2475a82f37..f9da06673b 100644
--- a/packages-experimental/uni-formula-ui/src/commands/commands/doc.command.ts
+++ b/packages-experimental/uni-formula-ui/src/commands/commands/doc.command.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, generateRandomId, ICommandService, LocaleService, makeCustomRangeStream, sequenceExecute } from '@univerjs/core';
-import { makeSelection, replaceSelectionFactory } from '@univerjs/docs-ui';
+import { BuildTextUtils, CommandType, CustomRangeType, generateRandomId, ICommandService, LocaleService, makeCustomRangeStream, sequenceExecute } from '@univerjs/core';
+import { replaceSelectionFactory } from '@univerjs/docs-ui';
import { AddDocUniFormulaMutation, RemoveDocUniFormulaMutation, UpdateDocUniFormulaMutation } from '@univerjs/uni-formula';
import type { ICommand, IDocumentBody, IMutationInfo } from '@univerjs/core';
import type { IAddDocUniFormulaMutationParams, IRemoveDocUniFormulaMutationParams, IUpdateDocUniFormulaMutationParams } from '@univerjs/uni-formula';
@@ -53,7 +53,7 @@ export const AddDocUniFormulaCommand: ICommand<IAddDocUniFormulaCommandParams> =
const insertCustomRangeMutation = replaceSelectionFactory(accessor, {
unitId,
body,
- selection: makeSelection(startIndex, startIndex + 1),
+ selection: BuildTextUtils.selection.makeSelection(startIndex, startIndex + 1),
});
if (insertCustomRangeMutation) {
diff --git a/packages-experimental/uni-formula-ui/src/commands/commands/slide.command.ts b/packages-experimental/uni-formula-ui/src/commands/commands/slide.command.ts
index b775223ea1..cf62b28244 100644
--- a/packages-experimental/uni-formula-ui/src/commands/commands/slide.command.ts
+++ b/packages-experimental/uni-formula-ui/src/commands/commands/slide.command.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, generateRandomId, ICommandService, LocaleService, makeCustomRangeStream } from '@univerjs/core';
-import { makeSelection, replaceSelectionFactory } from '@univerjs/docs-ui';
+import { BuildTextUtils, CommandType, CustomRangeType, generateRandomId, ICommandService, LocaleService, makeCustomRangeStream } from '@univerjs/core';
+import { replaceSelectionFactory } from '@univerjs/docs-ui';
import { SLIDE_EDITOR_ID } from '@univerjs/slides-ui';
import type { ICommand, IDocumentBody } from '@univerjs/core';
import { SlideUIFormulaCacheService } from '../../services/slide-ui-formula-cache.service';
@@ -57,7 +57,7 @@ export const AddSlideUniFormulaCommand: ICommand<IAddSlideUniFormulaCommandParam
const insertCustomRangeMutation = replaceSelectionFactory(accessor, {
unitId: SLIDE_EDITOR_ID,
body,
- selection: makeSelection(startIndex, startIndex + 1),
+ selection: BuildTextUtils.selection.makeSelection(startIndex, startIndex + 1),
});
// NOTE: For slides, the process to update a element's content is pretty different from docs.
diff --git a/packages-experimental/uni-formula-ui/src/services/formula-popup.service.ts b/packages-experimental/uni-formula-ui/src/services/formula-popup.service.ts
index 8679271f8a..d24cfa5722 100644
--- a/packages-experimental/uni-formula-ui/src/services/formula-popup.service.ts
+++ b/packages-experimental/uni-formula-ui/src/services/formula-popup.service.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { Disposable, FORMULA_EDITOR_ACTIVATED, ICommandService, IContextService, ILogService, Inject } from '@univerjs/core';
-import { DocCanvasPopManagerService, makeSelection } from '@univerjs/docs-ui';
+import { BuildTextUtils, Disposable, FORMULA_EDITOR_ACTIVATED, ICommandService, IContextService, ILogService, Inject } from '@univerjs/core';
+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { FORMULA_PROMPT_ACTIVATED } from '@univerjs/sheets-formula';
import { IShortcutService, KeyCode } from '@univerjs/ui';
import { IUniFormulaService } from '@univerjs/uni-formula';
@@ -104,7 +104,7 @@ export class UniFormulaPopupService extends Disposable {
: '=';
const disposable = this._docCanvasPopupManagerService.attachPopupToRange(
- makeSelection(startIndex),
+ BuildTextUtils.selection.makeSelection(startIndex),
{
componentKey: DOC_FORMULA_POPUP_KEY,
onClickOutside: () => this.closePopup(), // user may update ref range selections
diff --git a/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts b/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
index 714b94fe61..9fe66557ba 100644
--- a/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
+++ b/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
@@ -15,6 +15,7 @@
*/
import {
+ BuildTextUtils,
CommandType,
CustomRangeType,
ICommandService,
@@ -28,7 +29,7 @@ import {
toDisposable,
UniverInstanceType,
} from '@univerjs/core';
-import { makeSelection, replaceSelectionFactory } from '@univerjs/docs-ui';
+import { replaceSelectionFactory } from '@univerjs/docs-ui';
import { RichText } from '@univerjs/engine-render';
import { DataSyncPrimaryController } from '@univerjs/rpc';
import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';
@@ -104,9 +105,9 @@ export const UpdateSlideUniFormulaCacheCommand: ICommand<IUpdateSlideUniFormulaC
const redoMutation = replaceSelectionFactory(accessor, {
unitId,
- originBody,
body,
- selection: makeSelection(range.startIndex, range.endIndex),
+ selection: BuildTextUtils.selection.makeSelection(range.startIndex, range.endIndex),
+ doc: documentModel,
});
if (!redoMutation) return false;
@@ -170,7 +171,7 @@ export const UpdateDocUniFormulaCacheCommand: ICommand<IUpdateDocUniFormulaCache
const redoMutation = replaceSelectionFactory(accessor, {
unitId,
body,
- selection: makeSelection(range.startIndex, range.endIndex),
+ selection: BuildTextUtils.selection.makeSelection(range.startIndex, range.endIndex),
});
if (redoMutation) {
diff --git a/packages-experimental/uni-sheets-ui/package.json b/packages-experimental/uni-sheets-ui/package.json
index d01a539e8d..53e6e9b738 100644
--- a/packages-experimental/uni-sheets-ui/package.json
+++ b/packages-experimental/uni-sheets-ui/package.json
@@ -60,6 +60,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
+ "@univerjs/docs-ui": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-drawing-ui": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.ts
index 4c7c266344..1da8083fe0 100644
--- a/packages/core/src/docs/data-model/index.ts
+++ b/packages/core/src/docs/data-model/index.ts
@@ -17,3 +17,4 @@
export * from './document-data-model';
export * from './preset-list-type';
export * from './types';
+export * from './text-x/build-utils';
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
new file mode 100644
index 0000000000..2a108d98a7
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts
@@ -0,0 +1,62 @@
+/**
+ * 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 { excludePointsFromRange } from '../custom-range'; // 替换为你的文件路径
+
+describe('excludePointsFromRange function', () => {
+ it('should handle empty points array', () => {
+ const range: [number, number] = [0, 10];
+ const points: number[] = [];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 10]]);
+ });
+
+ it('should handle points at the beginning and end', () => {
+ const range: [number, number] = [0, 10];
+ const points = [0, 10];
+ expect(excludePointsFromRange(range, points)).toEqual([[1, 9]]);
+ });
+
+ it('should handle overlapping points', () => {
+ const range: [number, number] = [0, 10];
+ const points = [2, 3, 3, 5];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [4, 4], [6, 10]]);
+ });
+
+ it('should handle points outside the range', () => {
+ const range: [number, number] = [0, 10];
+ const points = [-1, 12];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 10]]);
+ });
+
+ it('should handle a single point in the middle', () => {
+ const range: [number, number] = [0, 10];
+ const points = [5];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 4], [6, 10]]);
+ });
+
+ it('should handle multiple ranges', () => {
+ const range: [number, number] = [0, 20];
+ const points = [2, 5, 10, 15];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [3, 4], [6, 9], [11, 14], [16, 20]]);
+ });
+
+ it('should handle points in ascending order', () => {
+ const range: [number, number] = [0, 10];
+ const points = [2, 4, 6, 8];
+ expect(excludePointsFromRange(range, points)).toEqual([[0, 1], [3, 3], [5, 5], [7, 7], [9, 10]]);
+ });
+});
diff --git a/packages/docs-ui/src/basics/custom-range.ts b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
similarity index 83%
rename from packages/docs-ui/src/basics/custom-range.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
index a0bfbc44bd..acff24281b 100644
--- a/packages/docs-ui/src/basics/custom-range.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
@@ -78,3 +78,27 @@ export function copyCustomRange(range: ICustomRange) {
rangeId: generateRandomId(),
};
}
+
+export function excludePointsFromRange(range: [number, number], points: number[]): [number, number][] {
+ const newRanges = [];
+ let start = range[0];
+
+ for (const point of points) {
+ if (point < range[0] || point > range[1]) {
+ continue;
+ }
+
+ if (start < point) {
+ newRanges.push([start, point - 1] as [number, number]);
+ }
+
+ start = point + 1;
+ }
+
+ if (start <= range[1]) {
+ newRanges.push([start, range[1]] as [number, number]);
+ }
+
+ return newRanges;
+}
+
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
new file mode 100644
index 0000000000..e0953a9ce1
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/index.ts
@@ -0,0 +1,51 @@
+/**
+ * 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 { copyCustomRange, getCustomRangesInterestsWithRange, isIntersecting, shouldDeleteCustomRange } from './custom-range';
+import { getDeleteSelection, getInsertSelection, getRetainAndDeleteFromReplace, getSelectionWithNoSymbolSide, getSelectionWithSymbolMax, isSegmentIntersects, makeSelection, normalizeSelection } from './selection';
+import { addCustomRangeTextX, deleteCustomRangeTextX, getRetainAndDeleteAndExcludeLineBreak, replaceSelectionTextX } from './text-x-utils';
+
+export class BuildTextUtils {
+ static customRange = {
+ add: addCustomRangeTextX,
+ delete: deleteCustomRangeTextX,
+
+ copyCustomRange,
+ getCustomRangesInterestsWithRange,
+ shouldDeleteCustomRange,
+
+ isIntersecting,
+ };
+
+ static selection = {
+ replace: replaceSelectionTextX,
+
+ makeSelection,
+ normalizeSelection,
+ getSelectionWithSymbolMax,
+ getSelectionWithNoSymbolSide,
+ getDeleteSelection,
+ getInsertSelection,
+ getDeleteActions: getRetainAndDeleteFromReplace,
+ getDeleteExculdeLastLineBreakActions: getRetainAndDeleteAndExcludeLineBreak,
+ };
+
+ static range = {
+ isIntersects: isSegmentIntersects,
+ };
+}
+
+export type { IAddCustomRangeTextXParam, IDeleteCustomRangeParam, IReplaceSelectionTextXParams } from './text-x-utils';
diff --git a/packages/docs-ui/src/basics/selection.ts b/packages/core/src/docs/data-model/text-x/build-utils/selection.ts
similarity index 69%
rename from packages/docs-ui/src/basics/selection.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/selection.ts
index dc168c4571..e2e8dd9315 100644
--- a/packages/docs-ui/src/basics/selection.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/selection.ts
@@ -14,11 +14,14 @@
* limitations under the License.
*/
-import { DataStreamTreeTokenType } from '@univerjs/core';
-import { isSegmentIntersects } from '@univerjs/docs';
-import type { IDocumentBody, ITextRange, Nullable } from '@univerjs/core';
-import { DeleteDirection } from '../../../docs-ui/src/types/delete-direction';
-import { isCustomRangeSplitSymbol } from './custom-range';
+import { DeleteDirection } from '../../../../types/enum';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { isCustomRangeSplitSymbol, isIntersecting, shouldDeleteCustomRange } from './custom-range';
+import type { Nullable } from '../../../../shared';
+import type { ITextRange } from '../../../../sheets/typedef';
+import type { IDocumentBody } from '../../../../types/interfaces';
+import type { IDeleteAction, IRetainAction } from '../action-types';
export function makeSelection(startOffset: number, endOffset?: number): ITextRange {
if (typeof endOffset === 'undefined') {
@@ -220,26 +223,84 @@ export function getSelectionForAddCustomRange(selection: ITextRange, body: IDocu
collapsed: false,
};
}
-const tags = [
- DataStreamTreeTokenType.PARAGRAPH, // 段落
- DataStreamTreeTokenType.SECTION_BREAK, // 章节
- DataStreamTreeTokenType.TABLE_START, // 表格开始
- DataStreamTreeTokenType.TABLE_ROW_START, // 表格开始
- DataStreamTreeTokenType.TABLE_CELL_START, // 表格开始
- DataStreamTreeTokenType.TABLE_CELL_END, // 表格开始
- DataStreamTreeTokenType.TABLE_ROW_END, // 表格开始
- DataStreamTreeTokenType.TABLE_END, // 表格结束
- DataStreamTreeTokenType.CUSTOM_RANGE_START, // 自定义范围开始
- DataStreamTreeTokenType.CUSTOM_RANGE_END, // 自定义范围结束
- DataStreamTreeTokenType.COLUMN_BREAK, // 换列
- DataStreamTreeTokenType.PAGE_BREAK, // 换页
- DataStreamTreeTokenType.DOCS_END, // 文档结尾
- DataStreamTreeTokenType.TAB, // 制表符
- DataStreamTreeTokenType.CUSTOM_BLOCK, // 图片 mention 等不参与文档流的场景
-
-];
-export function getSelectionText(dataStream: string, start: number, end: number) {
- const text = dataStream.slice(start, end);
- return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);
+
+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));
+ 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,
+ segmentId,
+ });
+ }
+
+ 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,
+ line: 0,
+ segmentId,
+ });
+ }
+ dos.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ segmentId,
+ });
+ cursor = pos + 1;
+ });
+
+ if (cursor < textEnd) {
+ dos.push({
+ t: TextXActionType.DELETE,
+ len: textEnd - cursor,
+ line: 0,
+ segmentId,
+ });
+ 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
new file mode 100644
index 0000000000..dbbfa2f40b
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -0,0 +1,345 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@wendellhu/redi';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { TextX } from '../text-x';
+import { excludePointsFromRange, isIntersecting, shouldDeleteCustomRange } from './custom-range';
+import { getDeleteSelection, getSelectionForAddCustomRange } from './selection';
+import type { Nullable } from '../../../../shared';
+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';
+
+export interface IDeleteCustomRangeParam {
+ rangeId: string;
+ segmentId?: string;
+ documentDataModel: DocumentDataModel;
+ insert?: Nullable<IDocumentBody>;
+}
+
+export function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangeParam) {
+ 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 len = endIndex - startIndex + 1;
+
+ if (startIndex > 0) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: startIndex,
+ segmentId,
+ });
+ }
+
+ textX.push({
+ t: TextXActionType.DELETE,
+ len: 1,
+ segmentId,
+ line: 0,
+ });
+
+ if (len - 2 > 0) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: len - 2,
+ segmentId,
+ });
+ }
+
+ textX.push({
+ t: TextXActionType.DELETE,
+ len: 1,
+ segmentId,
+ line: 0,
+ });
+
+ if (insert) {
+ textX.push({
+ body: insert,
+ t: TextXActionType.INSERT,
+ len: insert.dataStream.length,
+ segmentId,
+ line: 1,
+ });
+ }
+ return textX;
+}
+
+export interface IAddCustomRangeTextXParam {
+ range: ITextRange;
+ segmentId?: string;
+ rangeId: string;
+ rangeType: CustomRangeType;
+ properties?: Record<string, any>;
+ wholeEntity?: boolean;
+ 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 actualRange = getSelectionForAddCustomRange(range, body);
+ if (!actualRange) {
+ return false;
+ }
+
+ if (!body) {
+ return false;
+ }
+
+ const { startOffset, endOffset } = actualRange;
+
+ const customRanges = body.customRanges ?? [];
+ let cursor = 0;
+ const textX = 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,
+ segmentId,
+ });
+ cursor = range.startOffset;
+ }
+ textX.push({
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,
+ },
+ len: 1,
+ line: 0,
+ segmentId,
+ });
+
+ deletes.forEach((index) => {
+ if (index !== cursor) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: index - cursor,
+ segmentId,
+ });
+ cursor = index;
+ }
+ textX.push({
+ t: TextXActionType.DELETE,
+ len: 1,
+ line: 0,
+ segmentId,
+ });
+ cursor++;
+ });
+
+ if (cursor !== range.endOffset) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: range.endOffset - cursor,
+ segmentId,
+ });
+ cursor = range.endOffset;
+ }
+
+ textX.push({
+ t: TextXActionType.INSERT,
+ 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,
+ },
+ },
+ ],
+ },
+ len: 1,
+ line: 0,
+ segmentId,
+ });
+ };
+ 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));
+
+ 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,
+ 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;
+
+ const paragraphInRange = paragraphs?.find(
+ (p) => p.startIndex - memoryCursor >= textStart && p.startIndex - memoryCursor < textEnd
+ );
+
+ const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset));
+ 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,
+ segmentId,
+ });
+ }
+
+ if (preserveLineBreak) {
+ if (paragraphInRange && paragraphInRange.startIndex - memoryCursor > textStart) {
+ const paragraphIndex = paragraphInRange.startIndex - memoryCursor;
+ retainPoints.add(paragraphIndex);
+ }
+ }
+
+ 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,
+ line: 0,
+ segmentId,
+ });
+ }
+ dos.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ segmentId,
+ });
+ cursor = pos + 1;
+ });
+
+ if (cursor < textEnd) {
+ dos.push({
+ t: TextXActionType.DELETE,
+ len: textEnd - cursor,
+ line: 0,
+ segmentId,
+ });
+ }
+ return dos;
+}
+
+export interface IReplaceSelectionTextXParams {
+ /**
+ * range to be replaced.
+ */
+ selection: ITextRangeParam;
+
+ /** Body to be inserted at the given position. */
+ body: IDocumentBody; // Do not contain `\r\n` at the end.
+ /**
+ * origin document data model.
+ */
+ doc: DocumentDataModel;
+}
+
+export const replaceSelectionTextX = (params: IReplaceSelectionTextXParams) => {
+ const { selection, body: insertBody, doc } = params;
+ const segmentId = selection.segmentId;
+ const body = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!body) return false;
+
+ 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,
+ line: 0,
+ segmentId,
+ });
+
+ return textX;
+};
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 6132f82730..7e897ab2d2 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -16,6 +16,7 @@
import type { ICellData, ICellDataForSheetInterceptor, IRange, IRangeWithCoord, ISelectionCell, ISelectionCellWithMergeInfo } from '../sheets/typedef';
import { RANGE_TYPE } from '../sheets/typedef';
+import type { Worksheet } from '../sheets/worksheet';
import {
BaselineOffset,
BorderStyleTypes,
@@ -487,7 +488,7 @@ export function getDocsUpdateBody(model: IDocumentData, segmentId?: string) {
return body;
}
-export function isValidRange(range: IRange): boolean {
+export function isValidRange(range: IRange, worksheet?: Worksheet): boolean {
const { startRow, endRow, startColumn, endColumn, rangeType } = range;
if (
startRow < 0
@@ -518,6 +519,14 @@ export function isValidRange(range: IRange): boolean {
return false;
}
+ if (worksheet) {
+ const rowCount = worksheet.getRowCount();
+ const colCount = worksheet.getColumnCount();
+ if (endRow >= rowCount || endColumn >= colCount) {
+ return false;
+ }
+ }
+
return true;
}
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index d62816f6b7..1387bdbccb 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -243,6 +243,15 @@ export interface ICellDataForSheetInterceptor extends ICellData {
* can cell be covered when sibling is overflow
*/
coverable?: boolean;
+ linkUrl?: string;
+ linkId?: string;
+ fontRenderExtension?: {
+ leftOffset?: number;
+ rightOffset?: number;
+ topOffset?: number;
+ downOffset?: number;
+ isSkip?: boolean;
+ };
}
export function isICellData(value: any): value is ICellData {
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 4f9d695759..87589036a6 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { DataStreamTreeTokenType } from '../docs';
import { ObjectMatrix, Rectangle, Tools } from '../shared';
import { createRowColIter } from '../shared/row-col-iter';
import { type BooleanNumber, CellValueType } from '../types/enum';
@@ -731,7 +732,7 @@ export function extractPureTextFromCell(cell: Nullable<ICellData>): string {
const richTextValue = cell.p?.body?.dataStream;
if (richTextValue) {
- return richTextValue;
+ return richTextValue.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
}
const rawValue = cell.v;
diff --git a/packages/core/src/types/const/const.ts b/packages/core/src/types/const/const.ts
index 26c7e3d7cd..4f43d95529 100644
--- a/packages/core/src/types/const/const.ts
+++ b/packages/core/src/types/const/const.ts
@@ -164,7 +164,3 @@ export const DEFAULT_SLIDE = {
},
};
-/**
- * Univer internal key on cellData.custom to save some internal values
- */
-export const UNIVER_INTERNAL = '__univer_internal__';
diff --git a/packages/docs-ui/src/types/index.d.ts b/packages/core/src/types/enum/delete-direction.ts
similarity index 90%
rename from packages/docs-ui/src/types/index.d.ts
rename to packages/core/src/types/enum/delete-direction.ts
index 7facc6a68b..3b4d4170d9 100644
--- a/packages/docs-ui/src/types/index.d.ts
+++ b/packages/core/src/types/enum/delete-direction.ts
@@ -14,5 +14,7 @@
* limitations under the License.
*/
-export * from '../index';
-declare module '@univerjs/docs-ui' {}
+export enum DeleteDirection {
+ LEFT,
+ RIGHT,
+}
diff --git a/packages/core/src/types/enum/index.ts b/packages/core/src/types/enum/index.ts
index 2278b84624..da8c8db963 100644
--- a/packages/core/src/types/enum/index.ts
+++ b/packages/core/src/types/enum/index.ts
@@ -31,3 +31,4 @@ export * from './sheet-types';
export * from './text-style';
export * from './theme-color-type';
export * from './prst-geom-type';
+export * from './delete-direction';
diff --git a/packages/docs/src/basics/selection.ts b/packages/core/src/types/interfaces/i-need-check-disposable.ts
similarity index 79%
rename from packages/docs/src/basics/selection.ts
rename to packages/core/src/types/interfaces/i-need-check-disposable.ts
index 6c6ca377f6..cf86a31007 100644
--- a/packages/docs/src/basics/selection.ts
+++ b/packages/core/src/types/interfaces/i-need-check-disposable.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
-export function isSegmentIntersects(start: number, end: number, start2: number, end2: number) {
- return Math.max(start, start2) <= Math.min(end, end2);
+import type { IDisposable } from '@wendellhu/redi';
+
+export interface INeedCheckDisposable extends IDisposable {
+ canDispose: () => boolean;
}
diff --git a/packages/core/src/types/interfaces/index.ts b/packages/core/src/types/interfaces/index.ts
index 8114d15c09..f04179e1e4 100644
--- a/packages/core/src/types/interfaces/index.ts
+++ b/packages/core/src/types/interfaces/index.ts
@@ -21,3 +21,4 @@ export * from './i-placeholder';
export * from './i-shape-properties';
export * from './i-slide-data';
export * from './i-style-data';
+export * from './i-need-check-disposable';
diff --git a/packages/data-validation/src/commands/commands/data-validation.command.ts b/packages/data-validation/src/commands/commands/data-validation.command.ts
index 4befd96cf7..ba39fb1a48 100644
--- a/packages/data-validation/src/commands/commands/data-validation.command.ts
+++ b/packages/data-validation/src/commands/commands/data-validation.command.ts
@@ -16,12 +16,12 @@
import { CommandType, ICommandService, ILogService, IUndoRedoService } from '@univerjs/core';
import type { ICommand, IDataValidationRule, IDataValidationRuleBase, IDataValidationRuleOptions, IMutationInfo, Injector, IRange, ISheetDataValidationRule } from '@univerjs/core';
-import type { IAddDataValidationMutationParams, IRemoveDataValidationMutationParams, IUpdateDataValidationMutationParams } from '../mutations/data-validation.mutation';
-import { AddDataValidationMutation, RemoveDataValidationMutation, UpdateDataValidationMutation } from '../mutations/data-validation.mutation';
-import { DataValidatorRegistryService } from '../../services/data-validator-registry.service';
-import { DataValidationModel } from '../../models/data-validation-model';
import { getRuleOptions, getRuleSetting } from '../../common/util';
+import { DataValidationModel } from '../../models/data-validation-model';
+import { DataValidatorRegistryService } from '../../services/data-validator-registry.service';
import { UpdateRuleType } from '../../types/enum/update-rule-type';
+import { AddDataValidationMutation, RemoveDataValidationMutation, UpdateDataValidationMutation } from '../mutations/data-validation.mutation';
+import type { IAddDataValidationMutationParams, IRemoveDataValidationMutationParams, IUpdateDataValidationMutationParams } from '../mutations/data-validation.mutation';
interface ISheetCommandSharedParams {
unitId: string;
diff --git a/packages/data-validation/src/index.ts b/packages/data-validation/src/index.ts
index 71a55c408b..8a6bd11a69 100644
--- a/packages/data-validation/src/index.ts
+++ b/packages/data-validation/src/index.ts
@@ -14,37 +14,37 @@
* limitations under the License.
*/
-export { UniverDataValidationPlugin } from './plugin';
-export { DataValidatorRegistryService, DataValidatorRegistryScope } from './services/data-validator-registry.service';
-export { DataValidationModel, type DataValidationChangeSource, type IRuleChange, type IValidStatusChange } from './models/data-validation-model';
-
+// #region - all commands
+export {
+ AddDataValidationMutation,
+ type IAddDataValidationMutationParams,
+ type IRemoveDataValidationMutationParams,
+ type IUpdateDataValidationMutationParams,
+ RemoveDataValidationMutation,
+ UpdateDataValidationMutation,
+} from './commands/mutations/data-validation.mutation';
export {
getRuleOptions,
getRuleSetting,
} from './common/util';
+export { DataValidationResourceController } from './controllers/dv-resource.controller';
+export { type DataValidationChangeSource, DataValidationModel, type IRuleChange, type IValidStatusChange } from './models/data-validation-model';
+
+export { UniverDataValidationPlugin } from './plugin';
+export { DataValidatorRegistryScope, DataValidatorRegistryService } from './services/data-validator-registry.service';
+export { TextLengthErrorTitleMap } from './types/const/operator-text-map';
+export { TWO_FORMULA_OPERATOR_COUNT } from './types/const/two-formula-operators';
export { UpdateRuleType } from './types/enum/update-rule-type';
+export type { IDataValidationDropdownProps } from './types/interfaces/i-data-validation-drop-down';
export type { IDataValidatorOperatorConfig } from './types/interfaces/i-data-validator-operator-config';
-export type { IFormulaInputProps, IFormulaValue, FormulaInputType } from './types/interfaces/i-formula-input';
+export type { FormulaInputType, IFormulaInputProps, IFormulaValue } from './types/interfaces/i-formula-input';
export type { IUpdateRuleOptionsPayload, IUpdateRulePayload, IUpdateRuleRangePayload, IUpdateRuleSettingPayload } from './types/interfaces/i-update-rule-payload';
-export type { IDataValidationDropdownProps } from './types/interfaces/i-data-validation-drop-down';
export { BaseDataValidator } from './validators/base-data-validator';
export type { IFormulaResult, IValidatorCellInfo } from './validators/base-data-validator';
-export type { IBaseDataValidationWidget } from './validators/base-widget';
export type { IFormulaValidResult } from './validators/base-data-validator';
-export { TWO_FORMULA_OPERATOR_COUNT } from './types/const/two-formula-operators';
-export { DataValidationResourceController } from './controllers/dv-resource.controller';
-export { TextLengthErrorTitleMap } from './types/const/operator-text-map';
-// #region - all commands
-export {
- AddDataValidationMutation,
- RemoveDataValidationMutation,
- UpdateDataValidationMutation,
- type IAddDataValidationMutationParams,
- type IRemoveDataValidationMutationParams,
- type IUpdateDataValidationMutationParams,
-} from './commands/mutations/data-validation.mutation';
+export type { IBaseDataValidationWidget } from './validators/base-widget';
// #endregion
diff --git a/packages/data-validation/src/models/data-validation-model.ts b/packages/data-validation/src/models/data-validation-model.ts
index 3f1fe0786e..b044da6fb2 100644
--- a/packages/data-validation/src/models/data-validation-model.ts
+++ b/packages/data-validation/src/models/data-validation-model.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { DataValidationStatus, IDataValidationRule } from '@univerjs/core';
import { Disposable, ILogService, Tools } from '@univerjs/core';
import { debounceTime, Subject } from 'rxjs';
-import type { IUpdateRulePayload } from '../types/interfaces/i-update-rule-payload';
-import { UpdateRuleType } from '../types/enum/update-rule-type';
+import type { DataValidationStatus, IDataValidationRule } from '@univerjs/core';
import { getRuleOptions, getRuleSetting } from '../common/util';
+import { UpdateRuleType } from '../types/enum/update-rule-type';
+import type { IUpdateRulePayload } from '../types/interfaces/i-update-rule-payload';
type DataValidationChangeType = 'update' | 'add' | 'remove';
export type DataValidationChangeSource = 'command' | 'patched';
diff --git a/packages/data-validation/src/plugin.ts b/packages/data-validation/src/plugin.ts
index df53593b20..8421eda6bc 100644
--- a/packages/data-validation/src/plugin.ts
+++ b/packages/data-validation/src/plugin.ts
@@ -16,13 +16,13 @@
import { ICommandService, IConfigService, Inject, Injector, Plugin, UniverInstanceType } from '@univerjs/core';
import type { Dependency } from '@univerjs/core';
-import { DataValidatorRegistryService } from './services/data-validator-registry.service';
-import { DataValidationModel } from './models/data-validation-model';
import { AddDataValidationCommand, RemoveAllDataValidationCommand, RemoveDataValidationCommand, UpdateDataValidationOptionsCommand, UpdateDataValidationSettingCommand } from './commands/commands/data-validation.command';
import { AddDataValidationMutation, RemoveDataValidationMutation, UpdateDataValidationMutation } from './commands/mutations/data-validation.mutation';
+import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
import { DataValidationResourceController } from './controllers/dv-resource.controller';
+import { DataValidationModel } from './models/data-validation-model';
+import { DataValidatorRegistryService } from './services/data-validator-registry.service';
import type { IUniverDataValidationConfig } from './controllers/config.schema';
-import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
const PLUGIN_NAME = 'UNIVER_DATA_VALIDATION_PLUGIN';
diff --git a/packages/data-validation/src/validators/base-data-validator.ts b/packages/data-validation/src/validators/base-data-validator.ts
index 965d36bd73..1f68e6f81c 100644
--- a/packages/data-validation/src/validators/base-data-validator.ts
+++ b/packages/data-validation/src/validators/base-data-validator.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { CellValue, IDataValidationRule, IDataValidationRuleBase, Nullable, Workbook, Worksheet } from '@univerjs/core';
import { DataValidationOperator, Inject, Injector, LocaleService, Tools } from '@univerjs/core';
+import type { CellValue, IDataValidationRule, IDataValidationRuleBase, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { CellValueType } from '@univerjs/protocol';
import { OperatorErrorTitleMap, OperatorTitleMap } from '../types/const/operator-text-map';
import type { IBaseDataValidationWidget } from './base-widget';
diff --git a/packages/design/src/components/form-layout/FormLayout.tsx b/packages/design/src/components/form-layout/FormLayout.tsx
index b8e70d081b..cc2801c9d2 100644
--- a/packages/design/src/components/form-layout/FormLayout.tsx
+++ b/packages/design/src/components/form-layout/FormLayout.tsx
@@ -27,17 +27,17 @@ export interface IFormLayoutProps {
style?: React.CSSProperties;
className?: string;
-
+ contentStyle?: React.CSSProperties;
error?: string;
}
export const FormLayout = (props: IFormLayoutProps) => {
- const { label, desc, children, style, className, error } = props;
+ const { label, desc, children, style, className, error, contentStyle } = props;
return (
<div className={clsx(styles.formLayout, className)} style={style}>
{label && <div className={styles.formLayoutLabel}>{label}</div>}
{desc && <div className={styles.formLayoutDesc}>{desc}</div>}
- <div className={clsx(styles.formLayoutContent, error ? styles.formLayoutContentError : '')}>
+ <div style={contentStyle} className={clsx(styles.formLayoutContent, error ? styles.formLayoutContentError : '')}>
{children}
{error
? (
diff --git a/packages/design/src/components/popup/RectPopup.tsx b/packages/design/src/components/popup/RectPopup.tsx
index 44e10a8418..f49a3b471d 100644
--- a/packages/design/src/components/popup/RectPopup.tsx
+++ b/packages/design/src/components/popup/RectPopup.tsx
@@ -37,12 +37,14 @@ export interface IRectPopupProps {
excludeRects?: IAbsolutePosition[];
direction?: 'vertical' | 'horizontal' | 'left' | 'top' | 'right' | 'left' | 'bottom' | 'bottom-center' | 'top-center';
+ hidden?: boolean;
// #region closing behavior
-
- closeOnSelfTarget?: boolean;
onClickOutside?: (e: MouseEvent) => void;
excludeOutside?: HTMLElement[];
+ onPinterEnter?: (e: React.PointerEvent<HTMLElement>) => void;
+ onPointerLeave?: (e: React.PointerEvent<HTMLElement>) => void;
+ onClick?: (e: React.MouseEvent<HTMLElement>) => void;
// #endregion
}
@@ -100,7 +102,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbe
};
function RectPopup(props: IRectPopupProps) {
- const { children, anchorRect, direction = 'vertical', onClickOutside, excludeOutside, excludeRects } = props;
+ const { children, anchorRect, direction = 'vertical', onClickOutside, excludeOutside, excludeRects, onPinterEnter, onPointerLeave, onClick, hidden } = props;
const nodeRef = useRef<HTMLElement>(null);
const clickOtherFn = useEvent(onClickOutside ?? (() => { /* empty */ }));
const [position, setPosition] = useState<Partial<IAbsolutePosition>>({
@@ -169,10 +171,13 @@ function RectPopup(props: IRectPopupProps) {
return (
<section
+ onPointerEnter={onPinterEnter}
+ onPointerLeave={onPointerLeave}
ref={nodeRef}
- style={style}
+ style={{ ...style, ...hidden ? { display: 'none' } : null }}
className={styles.popupFixed}
onPointerDown={(e) => e.stopPropagation()}
+ onClick={onClick}
>
<RectPopupContext.Provider value={anchorRect}>
{children}
diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.json
index 4c6d98a12f..5baee7bb27 100644
--- a/packages/docs-drawing-ui/package.json
+++ b/packages/docs-drawing-ui/package.json
@@ -72,6 +72,7 @@
"@univerjs/drawing-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/ui": "workspace:*",
+ "clsx": ">=2.0.0",
"react": "^16.9.0 || ^17.0.0 || ^18.0.0",
"rxjs": ">=7.0.0"
},
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 e73b4551b9..f450686a08 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
@@ -15,6 +15,7 @@
*/
import {
+ BuildTextUtils,
CommandType,
ICommandService,
IUniverInstanceService,
@@ -23,7 +24,7 @@ import {
TextXActionType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import { getCustomBlockIdsInSelections, getRetainAndDeleteFromReplace, getRichTextEditPath } from '@univerjs/docs-ui';
+import { getCustomBlockIdsInSelections, getRichTextEditPath } from '@univerjs/docs-ui';
import type { IAccessor, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IInsertDrawingCommandParams } from './interfaces';
@@ -77,7 +78,7 @@ export const InsertDocDrawingCommand: ICommand = {
});
}
} else {
- const { dos } = getRetainAndDeleteFromReplace(activeTextRange, segmentId, 0, body);
+ const { dos } = BuildTextUtils.selection.getDeleteActions(activeTextRange, segmentId, 0, body);
textX.push(...dos);
const removedCustomBlockIds = getCustomBlockIdsInSelections(body, [activeTextRange]);
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index ba4eac44c7..38dedeaccb 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -38,7 +38,6 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@ICommandService private readonly _commandService: ICommandService,
- @ILocalFileService private readonly _fileOpenerService: ILocalFileService,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
@IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService,
@IImageIoService private readonly _imageIoService: IImageIoService,
@@ -48,7 +47,8 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
@IMessageService private readonly _messageService: IMessageService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
- @Inject(DocRefreshDrawingsService) private readonly _docRefreshDrawingsService: DocRefreshDrawingsService
+ @Inject(DocRefreshDrawingsService) private readonly _docRefreshDrawingsService: DocRefreshDrawingsService,
+ @ILocalFileService private readonly _fileOpenerService: ILocalFileService
) {
super();
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
index b6b4f2bcdd..a0953149e6 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, generateRandomId, type ICommand, ICommandService } from '@univerjs/core';
+import { CommandType, CustomRangeType, generateRandomId, ICommandService } from '@univerjs/core';
import { addCustomRangeBySelectionFactory } from '@univerjs/docs-ui';
+import type { ICommand, ITextRangeParam } from '@univerjs/core';
export interface IAddDocHyperLinkCommandParams {
payload: string;
unitId: string;
+ selection?: ITextRangeParam;
}
export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {
@@ -30,7 +32,7 @@ export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {
return false;
}
- const { payload } = params;
+ const { payload, unitId, selection } = params;
const commandService = accessor.get(ICommandService);
const id = generateRandomId();
const doMutation = addCustomRangeBySelectionFactory(
@@ -41,6 +43,8 @@ export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {
properties: {
url: payload,
},
+ unitId,
+ selection,
}
);
if (doMutation) {
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 3270d56db2..0213dd7d21 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
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, type ICommand, ICommandService } from '@univerjs/core';
+import { CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, getBodySlice, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { replaceSelectionFactory } from '@univerjs/docs-ui';
+import type { DocumentDataModel, ICommand } from '@univerjs/core';
export interface IUpdateDocHyperLinkCommandParams {
unitId: string;
@@ -35,13 +36,21 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
}
const { unitId, payload, segmentId } = params;
const commandService = accessor.get(ICommandService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const currentSelection = docSelectionManagerService.getActiveTextRange();
- if (!currentSelection) {
+ const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ if (!currentSelection || !doc) {
return false;
}
const newId = generateRandomId();
+ const oldBody = getBodySlice(doc.getSelfOrHeaderFooterModel(segmentId).getBody()!, currentSelection.startOffset!, currentSelection.endOffset!);
+ const textRun = oldBody.textRuns?.[0];
+ if (textRun) {
+ textRun.ed = params.label.length + 1;
+ }
+
const replaceSelection = replaceSelectionFactory(accessor, {
unitId,
body: {
@@ -55,6 +64,7 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
url: payload,
},
}],
+ textRuns: textRun ? [textRun] : undefined,
},
selection: {
startOffset: currentSelection.startOffset!,
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 346efa64ad..71220ce032 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
@@ -14,9 +14,8 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, CustomRangeType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
-import { getCustomRangesInterestsWithRange } from '@univerjs/docs-ui';
import type { DocumentDataModel, IAccessor, ICommand, ITextRange } from '@univerjs/core';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
@@ -51,7 +50,7 @@ export const shouldDisableAddLink = (accessor: IAccessor) => {
}
}
- const insertCustomRanges = getCustomRangesInterestsWithRange(activeRange as ITextRange, body.customRanges ?? []);
+ const insertCustomRanges = BuildTextUtils.customRange.getCustomRangesInterestsWithRange(activeRange as ITextRange, body.customRanges ?? []);
// can't insert hyperlink in range contains other custom ranges
return !insertCustomRanges.every((range) => range.rangeType === CustomRangeType.HYPERLINK);
};
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 783314bb03..31c734a199 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
@@ -54,7 +54,6 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
this._docEventManagerService.hoverCustomRanges$.subscribe((ranges) => {
const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);
const activeRanges = this._docSelectionManagerService.getCurrentTextRanges();
-
const currentSegmentId = activeRanges?.[0].segmentId;
if ((link?.segmentId ?? '') !== currentSegmentId) {
this._hideInfoPopup();
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 cb7c34ef7c..16b925b31a 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
@@ -146,7 +146,6 @@ export class DocHyperLinkPopupService extends Disposable {
componentKey: DocLinkPopup.componentKey,
direction: 'top-center',
multipleDirection: 'top',
- closeOnSelfTarget: true,
onClickOutside: () => {
this.hideInfoPopup();
},
diff --git a/packages/docs-hyper-link/package.json b/packages/docs-hyper-link/package.json
index d1e356a050..03fd6cfe57 100644
--- a/packages/docs-hyper-link/package.json
+++ b/packages/docs-hyper-link/package.json
@@ -57,7 +57,7 @@
"build": "tsc && vite build"
},
"peerDependencies": {
- "rxjs": "^7.8.1"
+ "@univerjs/core": "workspace:*"
},
"dependencies": {
"@univerjs/core": "workspace:*",
diff --git a/packages/docs-ui/src/basics/custom-range-factory.ts b/packages/docs-ui/src/basics/custom-range-factory.ts
index 9dbac5ae4c..ecf8e30d70 100644
--- a/packages/docs-ui/src/basics/custom-range-factory.ts
+++ b/packages/docs-ui/src/basics/custom-range-factory.ts
@@ -14,76 +14,14 @@
* limitations under the License.
*/
-import { DataStreamTreeTokenType, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, IUniverInstanceService, JSONX, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import type { CustomRangeType, DocumentDataModel, IAccessor, IDocumentBody, IMutationInfo, ITextRange } from '@univerjs/core';
+import type { CustomRangeType, DocumentDataModel, IAccessor, IAddCustomRangeTextXParam, IDocumentBody, IMutationInfo, ITextRangeParam, Nullable, TextX } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import { getRichTextEditPath } from '../commands/util';
-import { getSelectionForAddCustomRange, normalizeSelection } from './selection';
-interface IAddCustomRangeParam {
+interface IAddCustomRangeParam extends IAddCustomRangeTextXParam {
unitId: string;
- range: ITextRange;
- segmentId?: string;
- rangeId: string;
- rangeType: CustomRangeType;
-}
-
-function addCustomRangeTextX(param: IAddCustomRangeParam, body: IDocumentBody) {
- const { range, rangeId, rangeType, segmentId } = param;
- const actualRange = getSelectionForAddCustomRange(range, body);
- if (!actualRange) {
- return null;
- }
-
- const { startOffset: start, endOffset: end } = actualRange;
-
- const textX = new TextX();
-
- if (start > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: start,
- segmentId,
- });
- }
-
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,
- },
- len: 1,
- line: 0,
- });
-
- textX.push({
- t: TextXActionType.RETAIN,
- body: {
- dataStream: '',
- },
- len: end - start,
- segmentId,
- });
-
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_END,
- customRanges: [
- {
- rangeId,
- rangeType,
- startIndex: -(end - start) - 1,
- endIndex: 0,
- },
- ],
- },
- len: 1,
- line: 0,
- });
-
- return textX;
}
export function addCustomRangeFactory(accessor: IAccessor, param: IAddCustomRangeParam, body: IDocumentBody) {
@@ -103,7 +41,7 @@ export function addCustomRangeFactory(accessor: IAccessor, param: IAddCustomRang
},
};
const jsonX = JSONX.getInstance();
- const textX = addCustomRangeTextX(param, body);
+ const textX = BuildTextUtils.customRange.add({ ...param, body });
if (!textX) {
return false;
}
@@ -118,196 +56,67 @@ interface IAddCustomRangeFactoryParam {
rangeType: CustomRangeType;
wholeEntity?: boolean;
properties?: Record<string, any>;
+ unitId: string;
+ selection?: ITextRangeParam;
}
-// eslint-disable-next-line max-lines-per-function
export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAddCustomRangeFactoryParam) {
- const { rangeId, rangeType, wholeEntity, properties } = param;
+ const { rangeId, rangeType, wholeEntity, properties, unitId, selection: propSelection } = param;
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selection = docSelectionManagerService.getActiveTextRange();
+ const selection = propSelection ?? docSelectionManagerService.getActiveTextRange();
const segmentId = selection?.segmentId;
if (!selection) {
return false;
}
- const documentDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (!documentDataModel) {
return false;
}
const body = documentDataModel.getSelfOrHeaderFooterModel(selection.segmentId).getBody();
- const unitId = documentDataModel.getUnitId();
if (!body) {
return false;
}
- const { startOffset, endOffset } = normalizeSelection(selection);
-
- const customRanges = body.customRanges ?? [];
-
- 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, startOffset) <= Math.min(customRange.endIndex, endOffset - 1)) {
- relativeCustomRanges.push({ ...customRange });
- }
-
- // optimize
- if (customRange.startIndex >= endOffset) {
- break;
- }
- }
- const deletes = relativeCustomRanges.map((i) => [i.startIndex, i.endIndex]).flat().sort((pre, aft) => pre - aft);
-
- let cursor = 0;
- const textX = new TextX();
-
- const range = deletes.length
- ? {
- startOffset: Math.min(deletes[0], startOffset),
- endOffset: Math.max(deletes[deletes.length - 1] + 1, endOffset),
- }
- : selection;
+ const { startOffset, endOffset } = BuildTextUtils.selection.normalizeSelection(selection);
- if (range.startOffset !== cursor) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: range.startOffset - cursor,
- segmentId,
- });
- cursor = range.startOffset;
- }
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,
- },
- len: 1,
- line: 0,
+ const textX = BuildTextUtils.customRange.add({
+ range: { startOffset, endOffset, collapsed: startOffset === endOffset },
+ rangeId,
+ rangeType,
segmentId,
+ wholeEntity,
+ properties,
+ body,
});
-
- deletes.forEach((index, i) => {
- if (index !== cursor) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: index - cursor,
- segmentId,
- });
- cursor = index;
- }
- textX.push({
- t: TextXActionType.DELETE,
- len: 1,
- line: 0,
- segmentId,
- });
- cursor++;
- });
-
- if (cursor !== range.endOffset) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: range.endOffset - cursor,
- segmentId,
- });
- cursor = range.endOffset;
+ if (!textX) {
+ return false;
}
-
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_END,
- customRanges: [
- {
- rangeId,
- rangeType,
- startIndex: -(range.endOffset - range.startOffset - deletes.length + 1),
- endIndex: 0,
- wholeEntity,
- properties,
- },
- ],
- },
- len: 1,
- line: 0,
- segmentId,
- });
const jsonX = JSONX.getInstance();
- const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> & { textX: TextX } = {
id: RichTextEditingMutation.id,
params: {
unitId,
actions: [],
textRanges: undefined,
},
+ textX,
};
const path = getRichTextEditPath(documentDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
return doMutation;
}
-export interface IDeleteCustomRangeParam {
- unitId: string;
+export interface IDeleteCustomRangeFactoryParams {
rangeId: string;
segmentId?: string;
+ unitId: string;
+ insert?: Nullable<IDocumentBody>;
}
-function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangeParam) {
- const { unitId, rangeId, segmentId } = params;
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);
- if (!documentDataModel) {
- return false;
- }
-
- 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 len = endIndex - startIndex + 1;
-
- if (startIndex > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: startIndex,
- segmentId,
- });
- }
-
- textX.push({
- t: TextXActionType.DELETE,
- len: 1,
- segmentId,
- line: 0,
- });
-
- if (len - 2 > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: len - 2,
- segmentId,
- });
- }
-
- textX.push({
- t: TextXActionType.DELETE,
- len: 1,
- segmentId,
- line: 0,
- });
-
- return textX;
-}
-
-export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeParam) {
- const { unitId, segmentId } = params;
+export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeFactoryParams) {
+ const { unitId, segmentId, insert } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);
@@ -325,7 +134,13 @@ export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCus
};
const jsonX = JSONX.getInstance();
- const textX = deleteCustomRangeTextX(accessor, params);
+ const textX = BuildTextUtils.customRange.delete(accessor, {
+ documentDataModel,
+ rangeId: params.rangeId,
+ insert,
+ segmentId,
+ });
+
if (!textX) {
return false;
}
diff --git a/packages/docs-ui/src/basics/plain-text.ts b/packages/docs-ui/src/basics/plain-text.ts
index d5c67593f3..ad1ce35111 100644
--- a/packages/docs-ui/src/basics/plain-text.ts
+++ b/packages/docs-ui/src/basics/plain-text.ts
@@ -17,6 +17,11 @@
import { DataStreamTreeTokenType } from '@univerjs/core';
import type { IDocumentBody, IDocumentData } from '@univerjs/core';
+export const getPlainText = (text: string) => {
+ return text.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')
+ .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
+};
+
/**
* get plain text from rich-text
*/
@@ -26,7 +31,7 @@ export const getPlainTextFormBody = (body: IDocumentBody) => {
str = body.dataStream.slice(0, -2);
}
- return str.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
+ return getPlainText(str);
};
/**
@@ -38,3 +43,27 @@ export const getPlainTextFormDocument = (data: IDocumentData) => {
}
return getPlainTextFormBody(data.body);
};
+
+const tags = [
+ DataStreamTreeTokenType.PARAGRAPH, // 段落
+ DataStreamTreeTokenType.SECTION_BREAK, // 章节
+ DataStreamTreeTokenType.TABLE_START, // 表格开始
+ DataStreamTreeTokenType.TABLE_ROW_START, // 表格开始
+ DataStreamTreeTokenType.TABLE_CELL_START, // 表格开始
+ DataStreamTreeTokenType.TABLE_CELL_END, // 表格开始
+ DataStreamTreeTokenType.TABLE_ROW_END, // 表格开始
+ DataStreamTreeTokenType.TABLE_END, // 表格结束
+ DataStreamTreeTokenType.CUSTOM_RANGE_START, // 自定义范围开始
+ DataStreamTreeTokenType.CUSTOM_RANGE_END, // 自定义范围结束
+ DataStreamTreeTokenType.COLUMN_BREAK, // 换列
+ DataStreamTreeTokenType.PAGE_BREAK, // 换页
+ DataStreamTreeTokenType.DOCS_END, // 文档结尾
+ DataStreamTreeTokenType.TAB, // 制表符
+ DataStreamTreeTokenType.CUSTOM_BLOCK, // 图片 mention 等不参与文档流的场景
+
+];
+
+export function getSelectionText(dataStream: string, start: number, end: number) {
+ const text = dataStream.slice(start, end);
+ return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);
+}
diff --git a/packages/docs-ui/src/basics/replace.ts b/packages/docs-ui/src/basics/replace.ts
index 51623fee59..831ef7dbff 100644
--- a/packages/docs-ui/src/basics/replace.ts
+++ b/packages/docs-ui/src/basics/replace.ts
@@ -14,131 +14,43 @@
* limitations under the License.
*/
-import { IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { BuildTextUtils, IUniverInstanceService, JSONX } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import type { DocumentDataModel, IAccessor, IDeleteAction, IDocumentBody, IMutationInfo, IRetainAction, ITextRange, ITextRangeParam } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, IDocumentBody, IMutationInfo, ITextRangeParam, Nullable, TextX } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { getRichTextEditPath } from '../commands/util';
-import { isIntersecting, shouldDeleteCustomRange } from './custom-range';
-import { getDeleteSelection } from './selection';
-
-// 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,
- 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;
-
- const paragraphInRange = paragraphs?.find(
- (p) => p.startIndex - memoryCursor >= textStart && p.startIndex - memoryCursor < textEnd
- );
-
- const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset));
- 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,
- segmentId,
- });
- }
-
- if (preserveLineBreak) {
- if (paragraphInRange && paragraphInRange.startIndex - memoryCursor > textStart) {
- const paragraphIndex = paragraphInRange.startIndex - memoryCursor;
- retainPoints.add(paragraphIndex);
- }
- }
-
- 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,
- line: 0,
- segmentId,
- });
- }
- dos.push({
- t: TextXActionType.RETAIN,
- len: 1,
- segmentId,
- });
- cursor = pos + 1;
- });
-
- if (cursor < textEnd) {
- dos.push({
- t: TextXActionType.DELETE,
- len: textEnd - cursor,
- line: 0,
- segmentId,
- });
- }
- return dos;
-}
export interface IReplaceSelectionFactoryParams {
unitId: string;
+ /**
+ * slelection to be replaced, if not provided, use the current selection.
+ */
selection?: ITextRangeParam;
- originBody?: IDocumentBody;
-
/** Body to be inserted at the given position. */
body: IDocumentBody; // Do not contain `\r\n` at the end.
-
+ /**
+ * Text ranges to be replaced.
+ */
textRanges?: ITextRangeWithStyle[];
+ doc?: DocumentDataModel;
}
export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSelectionFactoryParams) {
- const { unitId, originBody, body: insertBody } = params;
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);
+ const { unitId, body: insertBody, doc } = params;
+ let docDataModel: Nullable<DocumentDataModel> = doc;
+ if (!docDataModel) {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);
+ }
if (!docDataModel) {
return false;
}
const segmentId = params.selection?.segmentId;
- let body: IDocumentBody | undefined;
- if (!params.originBody) {
- body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
- } else {
- body = originBody;
- }
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+
if (!body) return false;
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
@@ -146,7 +58,6 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSel
if (!selection || !body) {
return false;
}
-
const textRanges = params.textRanges ?? [{
startOffset: selection.startOffset + insertBody.dataStream.length,
endOffset: selection.startOffset + insertBody.dataStream.length,
@@ -154,7 +65,16 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSel
segmentId,
}];
- const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ const textX = BuildTextUtils.selection.replace({
+ selection,
+ body: insertBody,
+ doc: docDataModel,
+ });
+ if (!textX) {
+ return false;
+ }
+
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> & { textX: TextX } = {
id: RichTextEditingMutation.id,
params: {
unitId,
@@ -163,20 +83,10 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSel
debounce: true,
segmentId,
},
+ textX,
};
- const textX = new TextX();
const jsonX = JSONX.getInstance();
- // delete
- textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, body, segmentId));
- // insert
- textX.push({
- t: TextXActionType.INSERT,
- body: insertBody,
- len: insertBody.dataStream.length,
- line: 0,
- segmentId,
- });
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
return doMutation;
diff --git a/packages/docs-ui/src/basics/retain-delete-params.ts b/packages/docs-ui/src/basics/retain-delete-params.ts
deleted file mode 100644
index f29b074d5f..0000000000
--- a/packages/docs-ui/src/basics/retain-delete-params.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { TextXActionType } from '@univerjs/core';
-import type { IDeleteAction, IDocumentBody, IRetainAction, ITextRange } from '@univerjs/core';
-import { isIntersecting, shouldDeleteCustomRange } from './custom-range';
-
-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));
- 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,
- segmentId,
- });
- }
-
- 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,
- line: 0,
- segmentId,
- });
- }
- dos.push({
- t: TextXActionType.RETAIN,
- len: 1,
- segmentId,
- });
- cursor = pos + 1;
- });
-
- if (cursor < textEnd) {
- dos.push({
- t: TextXActionType.DELETE,
- len: textEnd - cursor,
- line: 0,
- segmentId,
- });
- cursor = textEnd + 1;
- }
-
- return {
- dos,
- cursor,
- retain: retainPoints.size,
- };
-}
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 b242309af9..255e2d803f 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-import { BooleanNumber, CommandType, DataStreamTreeTokenType, getBodySlice, ICommandService, IUniverInstanceService, normalizeBody, PresetListType, Tools, updateAttributeByInsert } from '@univerjs/core';
+import { BooleanNumber, BuildTextUtils, CommandType, DataStreamTreeTokenType, getBodySlice, ICommandService, IUniverInstanceService, normalizeBody, PresetListType, Tools, updateAttributeByInsert } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import type { ICommand, IParagraph } from '@univerjs/core';
-import { copyCustomRange } from '../../basics/custom-range';
-import { getInsertSelection } from '../../basics/selection';
import { InsertCommand } from './core-editing.command';
export function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {
@@ -95,14 +93,14 @@ export const BreakLineCommand: ICommand = {
}
const unitId = docDataModel.getUnitId();
- const { startOffset, endOffset } = getInsertSelection(activeTextRange, body);
+ const { startOffset, endOffset } = BuildTextUtils.selection.getInsertSelection(activeTextRange, body);
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
// line breaks to 2
if (prevParagraph && prevParagraph.startIndex > endOffset) {
const bodyAfter = normalizeBody(getBodySlice(body, endOffset, prevParagraph.startIndex + 1));
- bodyAfter.customRanges = bodyAfter.customRanges?.map(copyCustomRange);
+ bodyAfter.customRanges = bodyAfter.customRanges?.map(BuildTextUtils.customRange.copyCustomRange);
const deleteRange = {
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 7cc4653507..909cf55bcd 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -15,6 +15,7 @@
*/
import {
+ BuildTextUtils,
CommandType,
ICommandService,
IUniverInstanceService,
@@ -37,8 +38,6 @@ import type {
} from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentViewModel, IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getRetainAndDeleteAndExcludeLineBreak } from '../../basics/replace';
-import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
import { getCommandSkeleton, getRichTextEditPath } from '../util';
import { getDeleteRowContentActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams } from './table/table';
@@ -187,7 +186,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
segmentId,
});
} else {
- const { dos } = getRetainAndDeleteFromReplace(selection, segmentId, memoryCursor.cursor, originBody);
+ const { dos } = BuildTextUtils.selection.getDeleteActions(selection, segmentId, memoryCursor.cursor, originBody);
textX.push(...dos);
}
@@ -254,7 +253,7 @@ function getCutActionsFromTextRanges(
segmentId,
});
} else {
- textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, originBody, segmentId, memoryCursor.cursor, false));
+ textX.push(...BuildTextUtils.selection.getDeleteExculdeLastLineBreakActions(selection, originBody, segmentId, memoryCursor.cursor, false));
}
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 028e459759..2e5cdc9f21 100644
--- a/packages/docs-ui/src/commands/commands/core-editing.command.ts
+++ b/packages/docs-ui/src/commands/commands/core-editing.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import type {
DocumentDataModel,
@@ -27,9 +27,6 @@ import type {
} from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { isIntersecting, shouldDeleteCustomRange } from '../../basics/custom-range';
-import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
-import { getInsertSelection } from '../../basics/selection';
import { DeleteDirection } from '../../types/delete-direction';
import { getRichTextEditPath } from '../util';
@@ -39,6 +36,7 @@ export interface IInsertCommandParams {
range: ITextRange;
segmentId?: string;
cursorOffset?: number;
+ extendLastRange?: boolean;
}
export const EditorInsertTextCommandId = 'doc.command.insert-text';
@@ -50,10 +48,11 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
id: EditorInsertTextCommandId,
type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor, params: IInsertCommandParams) => {
const commandService = accessor.get(ICommandService);
- const { range, segmentId, body, unitId, cursorOffset } = params;
+ const { range, segmentId, body, unitId, cursorOffset, extendLastRange } = params;
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
@@ -68,7 +67,9 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
if (!originBody) {
return false;
}
- const actualRange = getInsertSelection(range, originBody);
+ const actualRange = extendLastRange
+ ? BuildTextUtils.selection.getDeleteSelection(range, originBody)
+ : BuildTextUtils.selection.getInsertSelection(range, originBody);
const { startOffset, collapsed } = actualRange;
const cursorMove = cursorOffset ?? body.dataStream.length;
const textRanges = [
@@ -102,7 +103,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
});
}
} else {
- const { dos, retain } = getRetainAndDeleteFromReplace(actualRange, segmentId, 0, originBody);
+ const { dos, retain } = BuildTextUtils.selection.getDeleteActions(actualRange, segmentId, 0, originBody);
textX.push(...dos);
doMutation.params.textRanges = [{
startOffset: startOffset + cursorMove + retain,
@@ -160,8 +161,8 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
const dataStream = body.dataStream;
const start = direction === DeleteDirection.LEFT ? startOffset - len : startOffset;
const end = start + len - 1;
- const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, start, end));
- const toDeleteRanges = relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(start, len, customRange, dataStream));
+ 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);
diff --git a/packages/docs-ui/src/commands/commands/delete.command.ts b/packages/docs-ui/src/commands/commands/delete.command.ts
index 05d7dcbfb2..3d56c3a28c 100644
--- a/packages/docs-ui/src/commands/commands/delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/delete.command.ts
@@ -15,6 +15,7 @@
*/
import {
+ BuildTextUtils,
CommandType,
DataStreamTreeTokenType,
generateRandomId,
@@ -35,12 +36,13 @@ import type { IAccessor, ICommand, ICustomBlock, IDocumentBody, IMutationInfo, I
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getDeleteSelection } from '../../basics/selection';
import { DeleteDirection } from '../../types/delete-direction';
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;
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 b9f630f27f..2b20d186ba 100644
--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts
+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts
@@ -14,13 +14,11 @@
* limitations under the License.
*/
-import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService, type ITextRangeWithStyle } from '@univerjs/engine-render';
import type { ICommand, ICommandInfo } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
-import { getInsertSelection } from '../../basics/selection';
import { DocIMEInputManagerService } from '../../services/doc-ime-input-manager.service';
import { getRichTextEditPath } from '../util';
@@ -62,7 +60,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
return false;
}
- const insertRange = getInsertSelection(previousActiveRange, body);
+ const insertRange = BuildTextUtils.selection.getInsertSelection(previousActiveRange, body);
Object.assign(previousActiveRange, insertRange);
const { startOffset } = previousActiveRange;
@@ -90,7 +88,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
const jsonX = JSONX.getInstance();
if (!previousActiveRange.collapsed && isCompositionStart) {
- const { dos, retain } = getRetainAndDeleteFromReplace(previousActiveRange, segmentId, 0, body);
+ const { dos, retain, cursor } = BuildTextUtils.selection.getDeleteActions(previousActiveRange, segmentId, 0, body);
textX.push(...dos);
doMutation.params!.textRanges = [{
startOffset: startOffset + len + retain,
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 a17be47e88..f438b83c43 100644
--- a/packages/docs-ui/src/commands/commands/replace-content.command.ts
+++ b/packages/docs-ui/src/commands/commands/replace-content.command.ts
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, ITextRange } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getRetainAndDeleteAndExcludeLineBreak } from '../../basics/replace';
import { getRichTextEditPath } from '../util';
interface IReplaceContentCommandParams {
@@ -192,7 +191,7 @@ export const ReplaceSelectionCommand: ICommand<IReplaceSelectionCommandParams> =
const textX = new TextX();
const jsonX = JSONX.getInstance();
// delete
- textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, body, '', 0, false));
+ textX.push(...BuildTextUtils.selection.getDeleteExculdeLastLineBreakActions(selection, body, '', 0, false));
// insert
textX.push({
t: TextXActionType.INSERT,
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 f27b27bed2..7733ced200 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
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import type { ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getInsertSelection } from '../../../basics/selection';
import { getCommandSkeleton, getRichTextEditPath } from '../../util';
import { generateParagraphs } from '../break-line.command';
import { genEmptyTable, genTableSource } from './table';
@@ -62,7 +61,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
if (skeleton == null) {
return false;
}
- const { startOffset } = getInsertSelection(activeRange, body);
+ const { startOffset } = BuildTextUtils.selection.getInsertSelection(activeRange, body);
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
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 8d709ca590..62d26b2253 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
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, Inject } from '@univerjs/core';
+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 { DocSkeletonManagerService } from '@univerjs/docs';
import type { DocumentDataModel, Nullable } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
@@ -70,7 +70,7 @@ 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];
await this._commandService.executeCommand(InsertCommand.id, {
unitId,
body: {
@@ -78,6 +78,7 @@ export class DocInputController extends Disposable implements IRenderModule {
},
range: activeRange,
segmentId,
+ extendLastRange: UNITS.includes(unitId),
});
// Space
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index cf87225e2a..b53245fdec 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -20,14 +20,11 @@ export * from './basics';
export type { IDocObjectParam } from './basics/component-tools';
export { getDocObject, getDocObjectById, neoGetDocObject } from './basics/component-tools';
export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleteCustomDecorationFactory } from './basics/custom-decoration-factory';
-export { getCustomRangesInterestsWithRange } from './basics/custom-range';
export { addCustomRangeBySelectionFactory, addCustomRangeFactory, deleteCustomRangeFactory } from './basics/custom-range-factory';
export * from './basics/docs-view-key';
export { hasParagraphInTable } from './basics/paragraph';
-export { getPlainTextFormBody, getPlainTextFormDocument } from './basics/plain-text';
+export { getPlainText, getPlainTextFormBody, getPlainTextFormDocument, getSelectionText } from './basics/plain-text';
export { replaceSelectionFactory } from './basics/replace';
-export { getRetainAndDeleteFromReplace } from './basics/retain-delete-params';
-export { getDeleteSelection, getInsertSelection, getSelectionText, makeSelection } from './basics/selection';
export { docDrawingPositionToTransform, transformToDocDrawingPosition } from './basics/transform-position';
export { AfterSpaceCommand, EnterCommand, type ITabCommandParams, TabCommand } from './commands/commands/auto-format.command';
export { BreakLineCommand } from './commands/commands/break-line.command';
@@ -49,8 +46,8 @@ export {
export { DeleteCustomBlockCommand, DeleteLeftCommand, DeleteRightCommand, type IDeleteCustomBlockParams, MergeTwoParagraphCommand } from './commands/commands/delete.command';
export { getCursorWhenDelete } from './commands/commands/delete.command';
+// #region - all commands
export { IMEInputCommand } from './commands/commands/ime-input.command';
-
export {
ResetInlineFormatTextBackgroundColorCommand,
SetInlineFormatBoldCommand,
@@ -87,12 +84,12 @@ export {
export { CoverContentCommand, ReplaceContentCommand } from './commands/commands/replace-content.command';
export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
export { CreateDocTableCommand, type ICreateDocTableCommandParams } from './commands/commands/table/doc-table-create.command';
-
export { DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand } from './commands/commands/table/doc-table-delete.command';
+
export type { IDocTableDeleteColumnsCommandParams, IDocTableDeleteRowsCommandParams, IDocTableDeleteTableCommandParams } from './commands/commands/table/doc-table-delete.command';
export type { IDocTableInsertColumnCommandParams, IDocTableInsertColumnLeftCommandParams, IDocTableInsertColumnRightCommandParams, IDocTableInsertRowAboveCommandParams, IDocTableInsertRowBellowCommandParams, IDocTableInsertRowCommandParams } from './commands/commands/table/doc-table-insert.command';
-
export { DocTableInsertColumnCommand, DocTableInsertColumnLeftCommand, DocTableInsertColumnRightCommand, DocTableInsertRowAboveCommand, DocTableInsertRowBellowCommand, DocTableInsertRowCommand } from './commands/commands/table/doc-table-insert.command';
+
export type { IDocTableTabCommandParams } from './commands/commands/table/doc-table-tab.command';
export { DocTableTabCommand } from './commands/commands/table/doc-table-tab.command';
export { genTableSource, getEmptyTableCell, getEmptyTableRow, getTableColumn } from './commands/commands/table/table';
@@ -106,8 +103,8 @@ export { DocUIController } from './controllers/doc-ui.controller';
export { menuSchema } from './controllers/menu.schema';
export { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
export { DocRenderController } from './controllers/render-controllers/doc.render-controller';
-
export * from './docs-ui-plugin';
+
export * from './services';
export { IDocClipboardService } from './services/clipboard/clipboard.service';
export { DocEventManagerService } from './services/doc-event-manager.service';
@@ -119,12 +116,13 @@ export { isInSameTableCell, isValidRectRange, NodePositionConvertToRectRange } f
export { NodePositionConvertToCursor } from './services/selection/convert-text-range';
export { getOneTextSelectionRange } from './services/selection/convert-text-range';
export type { IEditorInputConfig } from './services/selection/doc-selection-render.service';
-
export { DocSelectionRenderService } from './services/selection/doc-selection-render.service';
+
export type { IDocRange } from './services/selection/range-interface';
// #region - all commands
export { convertPositionsToRectRanges, RectRange } from './services/selection/rect-range';
export { getCanvasOffsetByEngine } from './services/selection/selection-utils';
export { getAnchorBounding, getLineBounding, TEXT_RANGE_LAYER_INDEX, TextRange } from './services/selection/text-range';
export { whenDocAndEditorFocused } from './shortcuts/utils';
+export { DOC_VERTICAL_PADDING } from './types/const/padding';
// #endregion
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index a62b8860ec..444f7d4c25 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -14,14 +14,12 @@
* limitations under the License.
*/
-import { createIdentifier, CustomRangeType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, getBodySlice, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, createIdentifier, CustomRangeType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, getBodySlice, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
import type { ICustomRange, IDisposable, IDocumentBody, IDocumentData, IParagraph, Nullable } from '@univerjs/core';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
-import { copyCustomRange } from '../../basics/custom-range';
-import { getDeleteSelection } from '../../basics/selection';
import { CutContentCommand, InnerPasteCommand } from '../../commands/commands/clipboard.inner.command';
import { getCursorWhenDelete } from '../../commands/commands/delete.command';
import { copyContentCache, extractId, genId } from './copy-content-cache';
@@ -224,7 +222,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
});
// copy custom ranges
- body.customRanges = body.customRanges?.map(copyCustomRange);
+ body.customRanges = body.customRanges?.map(BuildTextUtils.customRange.copyCustomRange);
const activeRange = this._docSelectionManagerService.getActiveTextRange();
const { segmentId, endOffset: activeEndOffset, style } = activeRange || {};
@@ -278,9 +276,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
private async _setClipboardData(documentBodyList: IDocumentBody[], snapshot: IDocumentData, needCache = true): Promise<void> {
const copyId = genId();
const text =
- documentBodyList.length > 1
+ (documentBodyList.length > 1
? documentBodyList.map((body) => body.dataStream).join('\n')
- : documentBodyList[0].dataStream;
+ : documentBodyList[0].dataStream)
+ .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')
+ .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
+
let html = this._umdToHtml.convert(documentBodyList);
// Only cache copy content when the range is 1.
@@ -375,7 +376,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
continue;
}
- const deleteRange = getDeleteSelection({ startOffset, endOffset, collapsed }, body);
+ const deleteRange = BuildTextUtils.selection.getDeleteSelection({ startOffset, endOffset, collapsed }, body);
const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
if (docBody == null) {
@@ -417,38 +418,59 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
private _generateBody(text: string): IDocumentBody {
// Convert all \n to \r, because we use \r to indicate paragraph break.
- const dataStream = text.replace(/\n/g, '\r');
-
- if (!text.includes('\r') && Tools.isLegalUrl(text)) {
- const id = generateRandomId();
- const urlText = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
- const range: ICustomRange = {
- startIndex: 0,
- endIndex: urlText.length - 1,
- rangeId: id,
- rangeType: CustomRangeType.HYPERLINK,
- properties: {
- url: text,
- },
- };
-
- return {
- dataStream: urlText,
- customRanges: [range],
- };
- }
-
+ const dataStream = text.replace(/\n/g, '\r').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
const paragraphs: IParagraph[] = [];
+ const customRanges: ICustomRange[] = [];
+ let cursor = 0;
+ let newDataStream = '';
+ let linkCount = 0;
+
+ const loopParagraph = (i: number, insertP = true) => {
+ const paragraphText = dataStream.slice(cursor, i);
+ if (Tools.isLegalUrl(paragraphText)) {
+ const id = generateRandomId();
+ const urlText = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${paragraphText}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ const range: ICustomRange = {
+ startIndex: cursor + linkCount * 2,
+ endIndex: cursor + linkCount * 2 + urlText.length - 1,
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: text,
+ },
+ };
+ customRanges.push(range);
+ newDataStream += urlText;
+ cursor = i + 1;
+ linkCount++;
+ if (insertP) {
+ newDataStream += '\r';
+ paragraphs.push({ startIndex: i + linkCount * 2 });
+ }
+ } else {
+ newDataStream += dataStream.slice(cursor, i + 1);
+ cursor = i + 1;
+ if (insertP) {
+ paragraphs.push({ startIndex: i + linkCount * 2 });
+ }
+ }
+ };
+ let end = 0;
for (let i = 0; i < dataStream.length; i++) {
if (dataStream[i] === '\r') {
- paragraphs.push({ startIndex: i });
+ loopParagraph(i);
+ end = i;
}
}
+ if (end !== dataStream.length - 1) {
+ loopParagraph(dataStream.length - 1, false);
+ }
return {
- dataStream,
+ dataStream: newDataStream,
paragraphs,
+ customRanges,
};
}
diff --git a/packages/docs-ui/src/services/doc-auto-format.service.ts b/packages/docs-ui/src/services/doc-auto-format.service.ts
index 36357eafdd..d06fdb6b03 100644
--- a/packages/docs-ui/src/services/doc-auto-format.service.ts
+++ b/packages/docs-ui/src/services/doc-auto-format.service.ts
@@ -14,11 +14,10 @@
* limitations under the License.
*/
-import { Disposable, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, Disposable, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import type { DocumentDataModel, ICommandInfo, ICustomRange, IDisposable, IParagraph, IParagraphRange, ITextRange, Nullable } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { getCustomRangesInterestsWithRange } from '../basics/custom-range';
export interface IAutoFormatContext {
unit: DocumentDataModel;
@@ -122,7 +121,7 @@ export class DocAutoFormatService extends Disposable {
selection,
isBody: !selection.segmentId,
paragraphs: getParagraphsInRange(selection, doc.getBody()?.paragraphs ?? []),
- customRanges: getCustomRangesInterestsWithRange(selection, doc.getBody()?.customRanges ?? []),
+ customRanges: BuildTextUtils.customRange.getCustomRangesInterestsWithRange(selection, doc.getBody()?.customRanges ?? []),
commandId: id,
commandParams: params,
};
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 0567c9ce89..1000c0ff49 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -17,9 +17,10 @@
import { Disposable, fromEventSubject, Inject } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { CURSOR_TYPE, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
-import { distinctUntilChanged, filter, map, mergeMap, Subject, take, throttleTime } from 'rxjs';
+import { BehaviorSubject, distinctUntilChanged, filter, map, mergeMap, Subject, take, throttleTime } from 'rxjs';
import type { DocumentDataModel, ICustomRange, IParagraph, ITextRangeParam, Nullable } from '@univerjs/core';
import type { Documents, DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { DOC_VERTICAL_PADDING } from '../types/const/padding';
import { transformOffset2Bound } from './doc-popup-manager.service';
import { NodePositionConvertToCursor } from './selection/convert-text-range';
import { getLineBounding } from './selection/text-range';
@@ -59,12 +60,13 @@ const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, ske
const bounds = getLineBounding(borderBoxPointGroup);
return bounds.map((rect) => ({
- top: rect.top + documentOffsetConfig.docsTop,
- bottom: rect.bottom + documentOffsetConfig.docsTop,
+ top: rect.top + documentOffsetConfig.docsTop - DOC_VERTICAL_PADDING,
+ bottom: rect.bottom + documentOffsetConfig.docsTop + DOC_VERTICAL_PADDING,
left: rect.left + documentOffsetConfig.docsLeft,
right: rect.right + documentOffsetConfig.docsLeft,
}));
};
+
export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: Documents, skeleton: DocumentSkeleton, pageIndex = -1): IBoundRectNoAngle | undefined => {
const start = skeleton.findPositionByGlyph(glyph, pageIndex);
if (!start) {
@@ -87,15 +89,21 @@ export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: D
};
interface ICustomRangeActive {
- range: ICustomRange; segmentId?: string; segmentPageIndex: number;
+ range: ICustomRange;
+ segmentId?: string;
+ segmentPageIndex: number;
+ rects: IBoundRectNoAngle[];
}
interface IBulletActive {
- paragraph: IParagraph; segmentId?: string; segmentPageIndex: number;
+ paragraph: IParagraph;
+ segmentId?: string;
+ segmentPageIndex: number;
+ rect: IBoundRectNoAngle;
}
export class DocEventManagerService extends Disposable implements IRenderModule {
- private readonly _hoverCustomRanges$ = new Subject<ICustomRangeActive[]>();
+ 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)));
private readonly _clickCustomRanges$ = new Subject<ICustomRangeActive>();
@@ -183,6 +191,10 @@ export class DocEventManagerService extends Disposable implements IRenderModule
this._calcActiveBullet(evt)
);
}));
+ this.disposeWithMe(this._context.scene.onPointerEnter$.subscribeEvent(() => {
+ this._hoverBullet$.next(null);
+ this._hoverCustomRanges$.next([]);
+ }));
const onPointerDown$ = fromEventSubject(this._context.mainComponent!.onPointerDown$);
const onPointerUp$ = fromEventSubject(this._context.scene!.onPointerUp$);
@@ -269,12 +281,12 @@ export class DocEventManagerService extends Disposable implements IRenderModule
return false;
});
});
-
return matchedRanges.map(
(range) => ({
segmentId: range.segmentId,
range: range.customRange,
segmentPageIndex: range.segmentPageIndex,
+ rects: range.rects,
})
);
}
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 73add0d28e..38819645f0 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -19,7 +19,7 @@ import { DocSkeletonManagerService } from '@univerjs/docs';
import { IRenderManagerService, pxToNum } from '@univerjs/engine-render';
import { ICanvasPopupService } from '@univerjs/ui';
import { BehaviorSubject, map } from 'rxjs';
-import type { IDisposable, ITextRangeParam } from '@univerjs/core';
+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';
@@ -83,7 +83,7 @@ export function transformOffset2Bound(offsetX: number, offsetY: number, scene: S
};
}
-export interface IDocCanvasPopup extends Pick<IPopup, 'direction' | 'excludeOutside' | 'closeOnSelfTarget' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'> {
+export interface IDocCanvasPopup extends Pick<IPopup, 'direction' | 'excludeOutside' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'> {
mask?: boolean;
extraProps?: Record<string, any>;
multipleDirection?: IPopup['direction'];
@@ -132,8 +132,6 @@ export class DocCanvasPopManagerService extends Disposable {
super();
}
- // #region attach to object
-
private _createObjectPositionObserver(
targetObject: BaseObject,
currentRender: IRender
@@ -220,6 +218,7 @@ export class DocCanvasPopManagerService extends Disposable {
};
}
+ // #region attach to object
/**
* attach a popup to canvas object
* @param targetObject target canvas object
@@ -233,7 +232,6 @@ export class DocCanvasPopManagerService extends Disposable {
}
const { position, position$, disposable } = this._createObjectPositionObserver(targetObject, currentRender);
-
const id = this._globalPopupManagerService.addPopup({
...popup,
unitId,
@@ -252,6 +250,8 @@ export class DocCanvasPopManagerService extends Disposable {
};
}
+ // #endregion
+ // #region attach to range
/**
* attach a popup to doc range
* @param range doc range
@@ -259,7 +259,7 @@ export class DocCanvasPopManagerService extends Disposable {
* @param unitId unit id
* @returns disposable
*/
- attachPopupToRange(range: ITextRangeParam, popup: IDocCanvasPopup, unitId: string): IDisposable {
+ attachPopupToRange(range: ITextRangeParam, popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {
const doc = this._univerInstanceService.getUnit(unitId);
if (!doc) {
throw new Error(`Document not found, unitId: ${unitId}`);
@@ -293,6 +293,8 @@ export class DocCanvasPopManagerService extends Disposable {
bounds$.complete();
disposable.dispose();
},
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
};
}
+ // #endregion
}
diff --git a/packages/docs-mention-ui/src/controllers/menu.schema.ts b/packages/docs-ui/src/types/const/padding.ts
similarity index 93%
rename from packages/docs-mention-ui/src/controllers/menu.schema.ts
rename to packages/docs-ui/src/types/const/padding.ts
index cf732b1e13..c7fdf4383a 100644
--- a/packages/docs-mention-ui/src/controllers/menu.schema.ts
+++ b/packages/docs-ui/src/types/const/padding.ts
@@ -14,3 +14,4 @@
* limitations under the License.
*/
+export const DOC_VERTICAL_PADDING = 4;
diff --git a/packages/docs/src/controllers/config.schema.ts b/packages/docs/src/controllers/config.schema.ts
index ab2be48d5b..7caddec73a 100644
--- a/packages/docs/src/controllers/config.schema.ts
+++ b/packages/docs/src/controllers/config.schema.ts
@@ -19,6 +19,7 @@ export const PLUGIN_CONFIG_KEY = 'docs.config';
export const configSymbol = Symbol(PLUGIN_CONFIG_KEY);
export interface IUniverDocsConfig {
+ hasScroll?: boolean;
}
export const defaultPluginConfig: IUniverDocsConfig = {};
diff --git a/packages/docs/src/controllers/custom-range.controller.ts b/packages/docs/src/controllers/custom-range.controller.ts
index a176bcfcbd..e0030a0991 100644
--- a/packages/docs/src/controllers/custom-range.controller.ts
+++ b/packages/docs/src/controllers/custom-range.controller.ts
@@ -14,10 +14,9 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { BuildTextUtils, Disposable, ICommandService, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import type { DocumentDataModel } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { isSegmentIntersects } from '../basics/selection';
import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
import { DocSelectionManagerService } from '../services/doc-selection-manager.service';
import type { ISetTextSelectionsOperationParams } from '../commands/operations/text-selection.operation';
@@ -48,7 +47,7 @@ export class DocCustomRangeController extends Disposable {
if (collapsed) {
return range.startIndex < startOffset && range.endIndex >= endOffset;
}
- return isSegmentIntersects(startOffset, endOffset - 1, range.startIndex, range.endIndex);
+ return BuildTextUtils.range.isIntersects(startOffset, endOffset - 1, range.startIndex, range.endIndex);
});
if (customRanges?.length) {
diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.ts
index fe74745cf0..f0eb2a4d8e 100644
--- a/packages/docs/src/doc-plugin.ts
+++ b/packages/docs/src/doc-plugin.ts
@@ -30,10 +30,7 @@ import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.sch
import { DocCustomRangeController } from './controllers/custom-range.controller';
import { DocSelectionManagerService } from './services/doc-selection-manager.service';
import { DocStateEmitService } from './services/doc-state-emit.service';
-
-export interface IUniverDocsConfig {
- hasScroll?: boolean;
-}
+import type { IUniverDocsConfig } from './controllers/config.schema';
const PLUGIN_NAME = 'DOCS_PLUGIN';
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 6dab41456a..f3f588a266 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-export { isSegmentIntersects } from './basics/selection';
// #region - all commands
export {
type IRichTextEditingMutationParams,
@@ -25,7 +24,8 @@ export {
type ISetTextSelectionsOperationParams,
SetTextSelectionsOperation,
} from './commands/operations/text-selection.operation';
-export { type IUniverDocsConfig, UniverDocsPlugin } from './doc-plugin';
+export type { IUniverDocsConfig } from './controllers/config.schema';
+export { UniverDocsPlugin } from './doc-plugin';
export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';
export { DocSelectionManagerService } from './services/doc-selection-manager.service';
diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.json
index c62210cbad..f815c17548 100644
--- a/packages/docs/tsconfig.json
+++ b/packages/docs/tsconfig.json
@@ -5,5 +5,5 @@
"outDir": "lib/types"
},
"references": [{ "path": "./tsconfig.node.json" }],
- "include": ["src"]
+ "include": ["src", "../core/src/docs/data-model/text-x/build-utils/__test__/custom-range.ts"]
}
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-data.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-data.mutation.ts
index b21d7e307c..c4abd93bf8 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-data.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-data.mutation.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IAccessor, IMutation } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
+import type { IAccessor, IMutation } from '@univerjs/core';
import type { IFormulaData } from '../../basics/common';
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
index 9c5a55a605..1c9c8db73f 100644
--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-import type { ICellData, IRange, Nullable } from '@univerjs/core';
import { CellValueType, isNullCell, moveRangeByOffset } from '@univerjs/core';
+import type { ICellData, IRange, Nullable } from '@univerjs/core';
import { FormulaAstLRU } from '../../basics/cache-lru';
-import type { IRuntimeUnitDataType, IUnitData, IUnitSheetNameMap, IUnitStylesData } from '../../basics/common';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { ObjectClassType } from '../../basics/object-class-type';
+import { getCellValue } from '../utils/cell';
+import { getRuntimeFeatureCell } from '../utils/get-runtime-feature-cell';
import { ArrayValueObject, ValueObjectFactory } from '../value-object/array-value-object';
import { type BaseValueObject, ErrorValueObject, type IArrayValueObject } from '../value-object/base-value-object';
import {
@@ -30,8 +31,7 @@ import {
NumberValueObject,
StringValueObject,
} from '../value-object/primitive-object';
-import { getCellValue } from '../utils/cell';
-import { getRuntimeFeatureCell } from '../utils/get-runtime-feature-cell';
+import type { IRuntimeUnitDataType, IUnitData, IUnitSheetNameMap, IUnitStylesData } from '../../basics/common';
export type NodeValueType = BaseValueObject | BaseReferenceObject | AsyncObject | AsyncArrayObject;
diff --git a/packages/engine-formula/src/engine/utils/cell.ts b/packages/engine-formula/src/engine/utils/cell.ts
index fc539ee864..6773aa639c 100644
--- a/packages/engine-formula/src/engine/utils/cell.ts
+++ b/packages/engine-formula/src/engine/utils/cell.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DEFAULT_EMPTY_DOCUMENT_VALUE } from '@univerjs/core';
+import { DataStreamTreeTokenType, DEFAULT_EMPTY_DOCUMENT_VALUE } from '@univerjs/core';
import type { ICellData, Nullable } from '@univerjs/core';
export function getCellValue(cell: Nullable<ICellData>) {
@@ -22,6 +22,7 @@ export function getCellValue(cell: Nullable<ICellData>) {
return 0;
}
+ // TODO: @weird94 this method is need to unified to a same handler function
if (cell?.p) {
const body = cell?.p.body;
@@ -31,7 +32,11 @@ export function getCellValue(cell: Nullable<ICellData>) {
const data = body.dataStream;
const lastString = data.substring(data.length - 2, data.length);
- const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;
+ const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ?
+ data.substring(0, data.length - 2)
+ .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '')
+ .replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '')
+ : data;
return newDataStream;
}
diff --git a/packages/engine-render/src/components/docs/layout/style/custom-range.ts b/packages/engine-render/src/components/docs/layout/style/custom-range.ts
index 4301c00b7a..b7fd56e1b7 100644
--- a/packages/engine-render/src/components/docs/layout/style/custom-range.ts
+++ b/packages/engine-render/src/components/docs/layout/style/custom-range.ts
@@ -23,7 +23,7 @@ export function getCustomRangeStyle(customRange: ICustomRangeForInterceptor): Nu
customRange.rangeType === CustomRangeType.MENTION
) {
return {
- ...customRange.active ? { ul: { s: BooleanNumber.TRUE } } : null,
+ ...(customRange.active ?? true) ? { ul: { s: BooleanNumber.TRUE } } : null,
cl: { rgb: '#274fee' },
};
}
diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.ts
index c932ce29b4..a3ecf9696c 100644
--- a/packages/engine-render/src/components/sheets/extensions/font.ts
+++ b/packages/engine-render/src/components/sheets/extensions/font.ts
@@ -17,7 +17,7 @@
/* eslint-disable max-lines-per-function */
import { HorizontalAlign, WrapStrategy } from '@univerjs/core';
-import type { ICellData, IRange, IScale, ObjectMatrix } from '@univerjs/core';
+import type { ICellDataForSheetInterceptor, IRange, IScale, ObjectMatrix } from '@univerjs/core';
import { FIX_ONE_PIXEL_BLUR_OFFSET } from '../../../basics';
import { VERTICAL_ROTATE_ANGLE } from '../../../basics/text-rotation';
@@ -34,15 +34,7 @@ import type { SheetComponent } from '../sheet-component';
const UNIQUE_KEY = 'DefaultFontExtension';
const EXTENSION_Z_INDEX = 45;
-export interface ISheetFontRenderExtension {
- fontRenderExtension?: {
- leftOffset?: number;
- rightOffset?: number;
- topOffset?: number;
- downOffset?: number;
- isSkip?: boolean;
- };
-};
+
export class Font extends SheetExtension {
override uKey = UNIQUE_KEY;
@@ -177,7 +169,7 @@ export class Font extends SheetExtension {
}
}
- const cellData = worksheet.getCell(rowIndex, columnIndex) as ICellData & ISheetFontRenderExtension || {};
+ const cellData = worksheet.getCell(rowIndex, columnIndex) as ICellDataForSheetInterceptor || {};
if (cellData.fontRenderExtension?.isSkip) {
return true;
}
diff --git a/packages/engine-render/src/components/sheets/interfaces.ts b/packages/engine-render/src/components/sheets/interfaces.ts
index afd8289e5f..83df360a94 100644
--- a/packages/engine-render/src/components/sheets/interfaces.ts
+++ b/packages/engine-render/src/components/sheets/interfaces.ts
@@ -52,13 +52,9 @@ export interface IFontCacheItem {
// content?: string;
}
-interface backgroundCache {
- [key: string]: ObjectMatrix<string>;
-}
+type backgroundCache = Record<string, ObjectMatrix<string>>;
-interface fontCache {
- [key: string]: ObjectMatrix<IFontCacheItem>;
-}
+type fontCache = Record<string, ObjectMatrix<IFontCacheItem>>;
export interface IStylesCache {
background?: backgroundCache;
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index b4967b0be4..4e46b5d607 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -18,7 +18,9 @@
/* eslint-disable no-param-reassign */
import {
BooleanNumber,
+ BuildTextUtils,
CellValueType,
+ CustomRangeType,
DEFAULT_EMPTY_DOCUMENT_VALUE,
DEFAULT_STYLES,
DocumentDataModel,
@@ -33,6 +35,7 @@ import {
LocaleService,
ObjectMatrix,
searchArray,
+ TextX,
Tools,
VerticalAlign,
WrapStrategy,
@@ -43,6 +46,7 @@ import type {
BorderStyleTypes,
IBorderStyleData,
ICellData,
+ ICellDataForSheetInterceptor,
IColumnData,
IColumnRange,
IDocumentData,
@@ -87,6 +91,33 @@ import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-c
import type { IBoundRectNoAngle, IViewportInfo } from '../../basics/vector2';
import type { BorderCache, IFontCacheItem, IStylesCache } from './interfaces';
+function addLinkToDocumentModel(documentModel: DocumentDataModel, linkUrl: string, linkId: string): void {
+ const body = documentModel.getBody()!;
+ if (body.customRanges?.some((range) => range.rangeType === CustomRangeType.HYPERLINK)) {
+ return;
+ }
+
+ const textX = BuildTextUtils.customRange.add({
+ range: {
+ startOffset: 0,
+ endOffset: body.dataStream.length - 1,
+ collapsed: false,
+ },
+ rangeId: linkId,
+ rangeType: CustomRangeType.HYPERLINK,
+ body,
+ properties: {
+ url: linkUrl,
+ refId: linkId,
+ },
+ });
+ if (!textX) {
+ return;
+ }
+
+ TextX.apply(body, textX.serialize());
+}
+
/**
* Obtain the height and width of a cell's text, taking into account scenarios with rotated text.
* @param documentSkeleton Data of the document's ViewModel
@@ -392,6 +423,23 @@ export class SpreadsheetSkeleton extends Skeleton {
this._marginTop = top;
}
+ getFont(rowIndex: number, columnIndex: number): Nullable<IFontCacheItem> {
+ const fontCache = this.stylesCache.font;
+ if (!fontCache) {
+ return null;
+ }
+
+ for (const font in fontCache) {
+ const fontMatrix = fontCache[font];
+ const fontItem = fontMatrix.getValue(rowIndex, columnIndex);
+ if (fontItem) {
+ return fontItem;
+ }
+ }
+
+ return null;
+ }
+
/**
* Get range in visible area (range in viewbounds) and set into this._rowColumnSegment.
* @param bounds
@@ -1094,8 +1142,9 @@ export class SpreadsheetSkeleton extends Skeleton {
});
}
+ // eslint-disable-next-line complexity
private _getCellDocumentModel(
- cell: Nullable<ICellData>,
+ cell: Nullable<ICellDataForSheetInterceptor>,
options: ICellDocumentModelOption = DEFAULT_CELL_DOCUMENT_MODEL_OPTION
): Nullable<IDocumentLayoutObject> {
const { isDeepClone, displayRawFormula, ignoreTextRotation } = {
@@ -1158,6 +1207,9 @@ export class SpreadsheetSkeleton extends Skeleton {
cellValueType: cell.t!,
});
}
+ if (documentModel && cell.linkUrl && cell.linkId) {
+ addLinkToDocumentModel(documentModel, cell.linkUrl, cell.linkId);
+ }
/**
* the alignment mode is returned with respect to the offset of the sheet cell,
diff --git a/packages/facade/package.json b/packages/facade/package.json
index 2907703dc4..4236a71ba0 100644
--- a/packages/facade/package.json
+++ b/packages/facade/package.json
@@ -73,6 +73,8 @@
"@univerjs/sheets-filter": "workspace:*",
"@univerjs/sheets-filter-ui": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
+ "@univerjs/sheets-hyper-link": "workspace:*",
+ "@univerjs/sheets-hyper-link-ui": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-thread-comment": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
@@ -97,6 +99,8 @@
"@univerjs/sheets-filter": "workspace:*",
"@univerjs/sheets-filter-ui": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
+ "@univerjs/sheets-hyper-link": "workspace:*",
+ "@univerjs/sheets-hyper-link-ui": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-thread-comment": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 97fad4c0d4..d093a773bc 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -16,7 +16,6 @@
/* eslint-disable max-lines-per-function */
-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
import {
ILogService,
Inject,
@@ -30,7 +29,9 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
+import { UniverDataValidationPlugin } from '@univerjs/data-validation';
import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { ISocketService, WebSocketService } from '@univerjs/network';
import {
RangeProtectionRuleModel,
@@ -42,6 +43,10 @@ import {
WorksheetProtectionPointModel,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
+import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
+import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
+
+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import {
DescriptionService,
IDescriptionService,
@@ -51,16 +56,11 @@ import {
} from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets-formula/locale/en-US';
import zhCN from '@univerjs/sheets-formula/locale/zh-CN';
-
-import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
-import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
-import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
-import { UniverDataValidationPlugin } from '@univerjs/data-validation';
-import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
-import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
+import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import { IThreadCommentDataSourceService, ThreadCommentDataSourceService, ThreadCommentModel } from '@univerjs/thread-comment';
+import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
+import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
import { FUniver } from '../facade';
function getTestWorkbookDataDemo(): IWorkbookData {
diff --git a/packages/facade/src/apis/docs/f-document.ts b/packages/facade/src/apis/docs/f-document.ts
index 5f3fbe6b26..1021bc7781 100644
--- a/packages/facade/src/apis/docs/f-document.ts
+++ b/packages/facade/src/apis/docs/f-document.ts
@@ -126,4 +126,11 @@ export class FDocument {
, true
);
}
+
+ // setHyperLink(linkUrl: string): FDocument;
+ // setHyperLink(startOffset: number, endOffset: number, linkUrl: string | null): FDocument {
+ // this._commandService.executeCommand(
+ // AddDocHyperLinkCommand.id,
+ // )
+ // }
}
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index 8c854fd202..badd7a8a7f 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -14,17 +14,6 @@
* limitations under the License.
*/
-import type {
- CommandListener,
- Dependency,
- DocumentDataModel,
- IDisposable,
- IDocumentData,
- IExecutionOptions,
- IWorkbookData,
- Nullable,
- Workbook,
-} from '@univerjs/core';
import {
BorderStyleTypes,
debounce,
@@ -40,11 +29,25 @@ import {
UniverInstanceType,
WrapStrategy,
} from '@univerjs/core';
-import type { ISocket } from '@univerjs/network';
+import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { ISocketService, WebSocketService } from '@univerjs/network';
-import type { IRegisterFunctionParams } from '@univerjs/sheets-formula';
+import { DisableCrosshairHighlightOperation, EnableCrosshairHighlightOperation, SetCrosshairHighlightColorOperation } from '@univerjs/sheets-crosshair-highlight';
import { IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
+import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
+import { CopyCommand, PasteCommand } from '@univerjs/ui';
+import type {
+ CommandListener,
+ Dependency,
+ DocumentDataModel,
+ IDisposable,
+ IDocumentData,
+ IExecutionOptions,
+ IWorkbookData,
+ Nullable,
+ Workbook,
+} from '@univerjs/core';
import type {
IColumnsHeaderCfgParam,
IRowsHeaderCfgParam,
@@ -53,19 +56,16 @@ import type {
SheetExtension, SpreadsheetColumnHeader,
SpreadsheetRowHeader,
} from '@univerjs/engine-render';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
-import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import type { ISocket } from '@univerjs/network';
import type { ISetCrosshairHighlightColorOperationParams } from '@univerjs/sheets-crosshair-highlight';
-import { DisableCrosshairHighlightOperation, EnableCrosshairHighlightOperation, SetCrosshairHighlightColorOperation } from '@univerjs/sheets-crosshair-highlight';
-import { CopyCommand, PasteCommand } from '@univerjs/ui';
+import type { IRegisterFunctionParams } from '@univerjs/sheets-formula';
import { FDocument } from './docs/f-document';
-import { FWorkbook } from './sheets/f-workbook';
-import { FSheetHooks } from './sheets/f-sheet-hooks';
import { FHooks } from './f-hooks';
import { FDataValidationBuilder } from './sheets/f-data-validation-builder';
-import { FPermission } from './sheets/f-permission';
import { FFormula } from './sheets/f-formula';
+import { FPermission } from './sheets/f-permission';
+import { FSheetHooks } from './sheets/f-sheet-hooks';
+import { FWorkbook } from './sheets/f-workbook';
export class FUniver {
static BorderStyle = BorderStyleTypes;
diff --git a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
index 3af5d1762a..1253973b60 100644
--- a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
+++ b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
@@ -16,7 +16,6 @@
/* eslint-disable max-lines-per-function */
-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
import {
ILogService,
Inject,
@@ -30,7 +29,9 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
+import { UniverDataValidationPlugin } from '@univerjs/data-validation';
import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { ISocketService, WebSocketService } from '@univerjs/network';
import {
RangeProtectionRuleModel,
@@ -42,6 +43,10 @@ import {
WorksheetProtectionPointModel,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
+import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
+import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
+
+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import {
DescriptionService,
IDescriptionService,
@@ -51,14 +56,9 @@ import {
} from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets-formula/locale/en-US';
import zhCN from '@univerjs/sheets-formula/locale/zh-CN';
-
-import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
-import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
-import { UniverDataValidationPlugin } from '@univerjs/data-validation';
-import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
-import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
+import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
import { FUniver } from '../../facade';
function getTestWorkbookDataDemo(): IWorkbookData {
diff --git a/packages/facade/src/apis/sheets/f-data-validation-builder.ts b/packages/facade/src/apis/sheets/f-data-validation-builder.ts
index 71d58c639a..10baea594d 100644
--- a/packages/facade/src/apis/sheets/f-data-validation-builder.ts
+++ b/packages/facade/src/apis/sheets/f-data-validation-builder.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { IDataValidationRule } from '@univerjs/core';
import { DataValidationErrorStyle, DataValidationOperator, DataValidationType, generateRandomId } from '@univerjs/core';
import { serializeRangeToRefString } from '@univerjs/engine-formula';
-import type { FRange } from './f-range';
+import type { IDataValidationRule } from '@univerjs/core';
import { FDataValidation } from './f-data-validation';
+import type { FRange } from './f-range';
/**
* Builder for data validation rules.
diff --git a/packages/facade/src/apis/sheets/f-range.ts b/packages/facade/src/apis/sheets/f-range.ts
index f4447912db..829437e919 100644
--- a/packages/facade/src/apis/sheets/f-range.ts
+++ b/packages/facade/src/apis/sheets/f-range.ts
@@ -14,6 +14,28 @@
* limitations under the License.
*/
+import { BooleanNumber, CustomRangeType, Dimension, generateRandomId, ICommandService, Inject, Injector, Rectangle, Tools, UserManagerService, WrapStrategy } from '@univerjs/core';
+import { FormulaDataModel } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ addMergeCellsUtil,
+ getAddMergeMutationRangeByType,
+ RemoveWorksheetMergeCommand,
+ SetHorizontalTextAlignCommand,
+ SetRangeValuesCommand,
+ SetStyleCommand,
+ SetTextWrapCommand,
+ SetVerticalTextAlignCommand,
+} from '@univerjs/sheets';
+import { AddSheetDataValidationCommand, ClearRangeDataValidationCommand, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
+import { SheetsFilterService } from '@univerjs/sheets-filter';
+import { SetSheetFilterRangeCommand } from '@univerjs/sheets-filter-ui';
+import { AddHyperLinkCommand, CancelHyperLinkCommand, UpdateHyperLinkCommand } from '@univerjs/sheets-hyper-link-ui';
+import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';
+import { AddCommentCommand, DeleteCommentTreeCommand, SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
+import { CellAlertManagerService, ISheetClipboardService, SheetCanvasPopManagerService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { getDT } from '@univerjs/thread-comment-ui';
+import { ComponentManager } from '@univerjs/ui';
import type {
CellValue,
DataValidationStatus,
@@ -30,40 +52,23 @@ import type {
Workbook,
Worksheet,
} from '@univerjs/core';
-import { BooleanNumber, Dimension, ICommandService, Inject, Injector, Rectangle, Tools, UserManagerService, WrapStrategy } from '@univerjs/core';
import type {
ISetHorizontalTextAlignCommandParams,
ISetStyleCommandParams,
ISetTextWrapCommandParams,
ISetVerticalTextAlignCommandParams,
+ ISheetLocation,
IStyleTypeValue,
} from '@univerjs/sheets';
-import {
- addMergeCellsUtil,
- getAddMergeMutationRangeByType,
- RemoveWorksheetMergeCommand,
- SetHorizontalTextAlignCommand,
- SetRangeValuesCommand,
- SetStyleCommand,
- SetTextWrapCommand,
- SetVerticalTextAlignCommand,
-} from '@univerjs/sheets';
-import type { ISetNumfmtCommandParams } from '@univerjs/sheets-numfmt';
-import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';
-import { FormulaDataModel } from '@univerjs/engine-formula';
-import type { ICanvasPopup } from '@univerjs/sheets-ui';
-import { ISheetClipboardService, SheetCanvasPopManagerService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { IRenderManagerService } from '@univerjs/engine-render';
import type { IAddSheetDataValidationCommandParams, IClearRangeDataValidationCommandParams } from '@univerjs/sheets-data-validation';
-import { AddSheetDataValidationCommand, ClearRangeDataValidationCommand, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import type { FilterModel } from '@univerjs/sheets-filter';
-import { SheetsFilterService } from '@univerjs/sheets-filter';
import type { ISetSheetFilterRangeCommandParams } from '@univerjs/sheets-filter-ui';
-import { SetSheetFilterRangeCommand } from '@univerjs/sheets-filter-ui';
-import { ComponentManager } from '@univerjs/ui';
-import { AddCommentCommand, DeleteCommentTreeCommand, SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
-import { getDT } from '@univerjs/thread-comment-ui';
-import type { FHorizontalAlignment, FVerticalAlignment, IFComponentKey } from './utils';
+import type { IAddHyperLinkCommandParams, ICancelHyperLinkCommandParams, IUpdateHyperLinkCommandParams } from '@univerjs/sheets-hyper-link-ui';
+import type { ISetNumfmtCommandParams } from '@univerjs/sheets-numfmt';
+import type { ICanvasPopup, ICellAlert } from '@univerjs/sheets-ui';
+import { FDataValidation } from './f-data-validation';
+import { FFilter } from './f-filter';
+import { FThreadComment } from './f-thread-comment';
import {
covertCellValue,
covertCellValues,
@@ -74,9 +79,7 @@ import {
transformFacadeHorizontalAlignment,
transformFacadeVerticalAlignment,
} from './utils';
-import { FDataValidation } from './f-data-validation';
-import { FFilter } from './f-filter';
-import { FThreadComment } from './f-thread-comment';
+import type { FHorizontalAlignment, FVerticalAlignment, IFComponentKey } from './utils';
export type FontLine = 'none' | 'underline' | 'line-through';
export type FontStyle = 'normal' | 'italic';
@@ -86,6 +89,14 @@ export interface IFCanvasPopup extends Omit<ICanvasPopup, 'componentKey'>, IFCom
}
+export interface ICellHyperLink {
+ id: string;
+ startIndex: number;
+ endIndex: number;
+ url: string;
+ label: string;
+}
+
export class FRange {
constructor(
private readonly _workbook: Workbook,
@@ -178,7 +189,8 @@ export class FRange {
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const skeleton = this._renderManagerService.getRenderById(unitId)!
- .with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)!.skeleton;
+ .with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)!.skeleton;
return skeleton.getCellByIndex(this._range.startRow, this._range.startColumn);
}
@@ -780,6 +792,33 @@ export class FRange {
return null;
}
+ /**
+ * Attach an alert popup to the start cell of current range.
+ * @param alert The alert to attach
+ * @returns The disposable object to detach the alert.
+ */
+ attachAlertPopup(alert: Omit<ICellAlert, 'location'>): IDisposable {
+ const cellAlertService = this._injector.get(CellAlertManagerService);
+ const location: ISheetLocation = {
+ workbook: this._workbook,
+ worksheet: this._worksheet,
+ row: this._range.startRow,
+ col: this._range.startColumn,
+ unitId: this.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ };
+ cellAlertService.showAlert({
+ ...alert,
+ location,
+ });
+
+ return {
+ dispose: (): void => {
+ cellAlertService.removeAlert(alert.key);
+ },
+ };
+ }
+
/**
* Get the comment of the start cell in the current range.
* @returns The comment of the start cell in the current range. If the cell does not have a comment, return `null`.
@@ -919,4 +958,89 @@ export class FRange {
return this;
}
//#endregion
+
+ // #region hyperlink
+ /**
+ * Set a hyperlink to the cell in the range.
+ * @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(),
+ subUnitId: this._worksheet.getSheetId(),
+ link: {
+ row: this._range.startRow,
+ column: this._range.startColumn,
+ payload: url,
+ display: label,
+ id: generateRandomId(),
+ },
+ };
+
+ return this._commandService.executeCommand(AddHyperLinkCommand.id, params);
+ }
+
+ /**
+ * Get all hyperlinks in the cell in the range.
+ * @returns hyperlinks
+ */
+ getHyperLinks(): ICellHyperLink[] {
+ const cellValue = this._worksheet.getCellRaw(this._range.startRow, this._range.startColumn);
+ if (!cellValue?.p) {
+ return [];
+ }
+
+ return cellValue.p.body?.customRanges
+ ?.filter((range) => range.rangeType === CustomRangeType.HYPERLINK)
+ .map((range) => ({
+ id: range.rangeId,
+ startIndex: range.startIndex,
+ endIndex: range.endIndex,
+ url: range.properties?.url ?? '',
+ label: cellValue.p?.body?.dataStream.slice(range.startIndex + 1, range.endIndex) ?? '',
+ })) ?? [];
+ }
+
+ /**
+ * Update hyperlink in the cell in the range.
+ * @param id id of the hyperlink
+ * @param url url
+ * @param label optional, label of the url
+ * @returns success or not
+ */
+ updateHyperLink(id: string, url: string, label?: string): Promise<boolean> {
+ const params: IUpdateHyperLinkCommandParams = {
+ unitId: this.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ row: this._range.startRow,
+ column: this._range.startColumn,
+ id,
+ payload: {
+ payload: url,
+ display: label,
+ },
+ };
+
+ return this._commandService.executeCommand(UpdateHyperLinkCommand.id, params);
+ }
+
+ /**
+ * Cancel hyperlink in the cell in the range.
+ * @param id id of the hyperlink
+ * @returns success or not
+ */
+ cancelHyperLink(id: string): Promise<boolean> {
+ const params: ICancelHyperLinkCommandParams = {
+ unitId: this.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ row: this._range.startRow,
+ column: this._range.startColumn,
+ id,
+ };
+
+ return this._commandService.executeCommand(CancelHyperLinkCommand.id, params);
+ }
+ // #endregion
}
diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts
index bf2229cd5b..d03b5f393e 100644
--- a/packages/facade/src/apis/sheets/f-workbook.ts
+++ b/packages/facade/src/apis/sheets/f-workbook.ts
@@ -30,7 +30,9 @@ import {
} from '@univerjs/core';
import { getPrimaryForRange, InsertSheetCommand, RemoveSheetCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';
import { AddSheetDataValidationCommand, RemoveSheetAllDataValidationCommand, RemoveSheetDataValidationCommand, SheetDataValidationModel, SheetsDataValidationValidatorService, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '@univerjs/sheets-data-validation';
+import { SheetsHyperLinkResolverService } from '@univerjs/sheets-hyper-link-ui';
import { AddCommentCommand, DeleteCommentCommand, DeleteCommentTreeCommand, ThreadCommentModel, UpdateCommentCommand } from '@univerjs/thread-comment';
+import { IDialogService, ISidebarService } from '@univerjs/ui';
import { filter } from 'rxjs';
import type { CommandListener, ICommandInfo, IDisposable, IExecutionOptions, IRange, IWorkbookData, Nullable, ObjectMatrix, Workbook } from '@univerjs/core';
import type { IRuleChange, IValidStatusChange } from '@univerjs/data-validation';
@@ -41,7 +43,9 @@ import type {
} from '@univerjs/sheets';
import type { IAddSheetDataValidationCommandParams, IDataValidationResCache, IRemoveSheetAllDataValidationCommandParams, IRemoveSheetDataValidationCommandParams, IUpdateSheetDataValidationOptionsCommandParams, IUpdateSheetDataValidationRangeCommandParams, IUpdateSheetDataValidationSettingCommandParams } from '@univerjs/sheets-data-validation';
import type { ICanvasFloatDom } from '@univerjs/sheets-drawing-ui';
+import type { ISheetHyperLinkInfo } from '@univerjs/sheets-hyper-link-ui';
import type { CommentUpdate, IAddCommentCommandParams, IDeleteCommentCommandParams } from '@univerjs/thread-comment';
+import type { IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';
import { FRange } from './f-range';
import { FWorksheet } from './f-worksheet';
import type { IFComponentKey } from './utils';
@@ -242,7 +246,25 @@ export class FWorkbook {
}
// #endregion
+ /**
+ * open a sidebar
+ * @param params the sidebar options
+ * @returns the disposable object
+ */
+ openSiderbar(params: ISidebarMethodOptions): IDisposable {
+ const sideBarService = this._injector.get(ISidebarService);
+ return sideBarService.open(params);
+ }
+ /**
+ * open a dialog
+ * @param dialog the dialog options
+ * @returns the disposable object
+ */
+ openDialog(dialog: IDialogPartMethodOptions): IDisposable {
+ const dialogService = this._injector.get(IDialogService);
+ return dialogService.open(dialog);
+ }
// #region callbacks
/**
@@ -568,4 +590,37 @@ export class FWorkbook {
}
// endregion
+
+ // #region hyperlink
+ /**
+ * create a hyperlink for the sheet
+ * @param sheetId the sheet id to link
+ * @param range the range to link, or define-name id
+ * @returns the hyperlink string
+ */
+ createSheetHyperlink(sheetId: string, range?: string | IRange): string {
+ const resolverService = this._injector.get(SheetsHyperLinkResolverService);
+ return resolverService.buildHyperLink(this.getId(), sheetId, range);
+ }
+
+ /**
+ * parse the hyperlink string to get the hyperlink info
+ * @param hyperlink the hyperlink string
+ * @returns the hyperlink info
+ */
+ parseSheetHyperlink(hyperlink: string): ISheetHyperLinkInfo {
+ const resolverService = this._injector.get(SheetsHyperLinkResolverService);
+ return resolverService.parseHyperLink(hyperlink);
+ }
+
+ /**
+ * navigate to the sheet hyperlink
+ * @param hyperlink the hyperlink string
+ */
+ navigateToSheetHyperlink(hyperlink: string): void {
+ const resolverService = this._injector.get(SheetsHyperLinkResolverService);
+ const info = resolverService.parseHyperLink(hyperlink);
+ info.handler();
+ }
+ // #endregion
}
diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.ts
index 983b96ca32..33bef74497 100644
--- a/packages/facade/src/apis/sheets/f-worksheet.ts
+++ b/packages/facade/src/apis/sheets/f-worksheet.ts
@@ -14,24 +14,24 @@
* limitations under the License.
*/
-import type { IRange, Nullable, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';
-import { copyRangeStyles, InsertColCommand, InsertRowCommand, MoveColsCommand, MoveRowsCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetRowIsAutoHeightCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { Direction, ICommandService, Inject, Injector, RANGE_TYPE } from '@univerjs/core';
-
-import type { IDataValidationResCache } from '@univerjs/sheets-data-validation';
+import { copyRangeStyles, InsertColCommand, InsertRowCommand, MoveColsCommand, MoveRowsCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetRowIsAutoHeightCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { DataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
-import type { FilterModel } from '@univerjs/sheets-filter';
+
+import { SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
import { SheetsFilterService } from '@univerjs/sheets-filter';
import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
import { ComponentManager } from '@univerjs/ui';
-import { SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
-import { FRange } from './f-range';
-import { FSelection } from './f-selection';
+import type { IRange, Nullable, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';
+import type { IDataValidationResCache } from '@univerjs/sheets-data-validation';
+import type { FilterModel } from '@univerjs/sheets-filter';
import { FDataValidation } from './f-data-validation';
import { FFilter } from './f-filter';
+import { FRange } from './f-range';
+import { FSelection } from './f-selection';
import { FThreadComment } from './f-thread-comment';
-import type { FWorkbook, IFICanvasFloatDom } from './f-workbook';
import { covertToColRange, covertToRowRange, transformComponentKey } from './utils';
+import type { FWorkbook, IFICanvasFloatDom } from './f-workbook';
export class FWorksheet {
constructor(
diff --git a/packages/facade/src/apis/sheets/utils.ts b/packages/facade/src/apis/sheets/utils.ts
index 754dbbe80d..f4b9eacbdc 100644
--- a/packages/facade/src/apis/sheets/utils.ts
+++ b/packages/facade/src/apis/sheets/utils.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, IRangeWithCoord, Nullable, Worksheet } from '@univerjs/core';
import {
DisposableCollection,
generateRandomId,
@@ -27,6 +26,7 @@ import {
Tools,
VerticalAlign,
} from '@univerjs/core';
+import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, IRangeWithCoord, Nullable, Worksheet } from '@univerjs/core';
import type { ComponentManager, ComponentType } from '@univerjs/ui';
export type FHorizontalAlignment = 'left' | 'center' | 'normal';
@@ -175,7 +175,7 @@ export function transformComponentKey(component: IFComponentKey, componentManage
if (typeof componentKey === 'string') {
key = componentKey;
} else {
- key = componentManager.getKey(componentKey) ?? `External_${generateRandomId(6)}`;
+ key = `External_${generateRandomId(6)}`;
disposableCollection.add(componentManager.register(key, componentKey, { framework: isVue3 ? 'vue3' : 'react' }));
}
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
index 3cfa8fdaf8..ce22f4b5f3 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
+import type { ICellDataForSheetInterceptor, Workbook } from '@univerjs/core';
import { Disposable, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, Range, UniverInstanceType } from '@univerjs/core';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { bufferTime, filter } from 'rxjs/operators';
-import type { ISheetFontRenderExtension } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import { ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel, DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';
import type { IConditionalFormattingCellData, IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
@@ -237,7 +236,7 @@ export class SheetsCfRenderController extends Disposable {
const styleMap = context.workbook.getStyles();
const defaultStyle = (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};
const s = { ...defaultStyle };
- const cloneCell = { ...cell, s } as IConditionalFormattingCellData & ISheetFontRenderExtension;
+ const cloneCell = { ...cell, s } as IConditionalFormattingCellData & ICellDataForSheetInterceptor;
if (result.style) {
Object.assign(s, result.style);
}
diff --git a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts b/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts
index 554093b713..9852606331 100644
--- a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
import { DataValidationStatus, Disposable, Inject, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
-import type { BaseDataValidator } from '@univerjs/data-validation';
-import { debounceTime } from 'rxjs';
import { IZenZoneService } from '@univerjs/ui';
+import { debounceTime } from 'rxjs';
+import type { Workbook } from '@univerjs/core';
+import type { BaseDataValidator } from '@univerjs/data-validation';
const ALERT_KEY = 'SHEET_DATA_VALIDATION_ALERT';
diff --git a/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts b/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
index 0f26f64d28..488cf9e3cc 100644
--- a/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
@@ -15,10 +15,10 @@
*/
import { DataValidationType, Disposable, Inject, Injector, LifecycleStages, OnLifecycle, Range, Rectangle } from '@univerjs/core';
-import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
-import { DATA_VALIDATION_PLUGIN_NAME } from '../common/const';
+import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { getDataValidationDiffMutations } from '../commands/commands/data-validation.command';
+import { DATA_VALIDATION_PLUGIN_NAME } from '../common/const';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
@OnLifecycle(LifecycleStages.Ready, DataValidationAutoFillController)
diff --git a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
index d9853077a6..a7191b0a37 100644
--- a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';
import { Disposable, Inject, Injector, LifecycleStages, ObjectMatrix, OnLifecycle, Rectangle } from '@univerjs/core';
-import type { IDiscreteRange } from '@univerjs/sheets-ui';
import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME, rangeToDiscreteRange, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
-import { DATA_VALIDATION_PLUGIN_NAME } from '../common/const';
+import type { IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';
+import type { IDiscreteRange } from '@univerjs/sheets-ui';
import { getDataValidationDiffMutations } from '../commands/commands/data-validation.command';
+import { DATA_VALIDATION_PLUGIN_NAME } from '../common/const';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
@OnLifecycle(LifecycleStages.Ready, DataValidationCopyPasteController)
diff --git a/packages/sheets-data-validation/src/controllers/dv-permission.controller.ts b/packages/sheets-data-validation/src/controllers/dv-permission.controller.ts
index 8d6a3faa50..5f58bfa088 100644
--- a/packages/sheets-data-validation/src/controllers/dv-permission.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-permission.controller.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { ICommandInfo } from '@univerjs/core';
import { Disposable, ICommandService, Inject, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';
-import { SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
import { RangeProtectionPermissionEditPoint, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetCellStylePermission } from '@univerjs/sheets';
-import type { IUpdateSheetDataValidationRangeCommandParams } from '../commands/commands/data-validation.command';
+import { SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
+import type { ICommandInfo } from '@univerjs/core';
import { AddSheetDataValidationCommand, UpdateSheetDataValidationRangeCommand } from '../commands/commands/data-validation.command';
+import type { IUpdateSheetDataValidationRangeCommandParams } from '../commands/commands/data-validation.command';
@OnLifecycle(LifecycleStages.Ready, DataValidationPermissionController)
export class DataValidationPermissionController extends Disposable {
diff --git a/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts b/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts
index f7a64d4012..996abdb16f 100644
--- a/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts
@@ -14,16 +14,16 @@
* limitations under the License.
*/
-import type { IRange, ISheetDataValidationRule } from '@univerjs/core';
import { DataValidationType, Disposable, Inject, Injector, isRangesEqual, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';
-import type { EffectRefRangeParams } from '@univerjs/sheets';
-import { handleCommonDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';
-import type { IRemoveDataValidationMutationParams, IUpdateDataValidationMutationParams } from '@univerjs/data-validation';
import { DataValidationModel, RemoveDataValidationMutation, UpdateDataValidationMutation, UpdateRuleType } from '@univerjs/data-validation';
+import { handleCommonDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';
import { FormulaRefRangeService } from '@univerjs/sheets-formula';
+import type { IRange, ISheetDataValidationRule } from '@univerjs/core';
+import type { IRemoveDataValidationMutationParams, IUpdateDataValidationMutationParams } from '@univerjs/data-validation';
+import type { EffectRefRangeParams } from '@univerjs/sheets';
+import { removeDataValidationUndoFactory } from '../commands/commands/data-validation.command';
import { DataValidationCustomFormulaService } from '../services/dv-custom-formula.service';
import { DataValidationFormulaService } from '../services/dv-formula.service';
-import { removeDataValidationUndoFactory } from '../commands/commands/data-validation.command';
@OnLifecycle(LifecycleStages.Starting, DataValidationRefRangeController)
export class DataValidationRefRangeController extends Disposable {
diff --git a/packages/sheets-data-validation/src/controllers/dv-reject-input.controller.ts b/packages/sheets-data-validation/src/controllers/dv-reject-input.controller.ts
index 611dacc9ef..048b78b7cc 100644
--- a/packages/sheets-data-validation/src/controllers/dv-reject-input.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-reject-input.controller.ts
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-import { DataValidationErrorStyle, Disposable, Inject, LifecycleStages, LocaleService, OnLifecycle, UNIVER_INTERNAL } from '@univerjs/core';
+import { DataValidationErrorStyle, Disposable, Inject, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';
import { DataValidatorRegistryService } from '@univerjs/data-validation';
+import { Button } from '@univerjs/design';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { IDialogService } from '@univerjs/ui';
import React from 'react';
-import { Button } from '@univerjs/design';
-import { getCellValueOrigin } from '../utils/get-cell-data-origin';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
+import { getCellValueOrigin } from '../utils/get-cell-data-origin';
@OnLifecycle(LifecycleStages.Ready, DataValidationRejectInputController)
export class DataValidationRejectInputController extends Disposable {
@@ -57,7 +57,7 @@ export class DataValidationRejectInputController extends Disposable {
const success = await validator.validator(
{
value: getCellValueOrigin(cell),
- interceptValue: getCellValueOrigin(cell?.custom?.[UNIVER_INTERNAL]?.origin ?? cell),
+ interceptValue: getCellValueOrigin(context?.origin ?? cell),
row,
column: col,
unitId,
diff --git a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
index 937b715ea4..04735d4c7f 100644
--- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
@@ -14,20 +14,20 @@
* limitations under the License.
*/
-import type { ICellDataForSheetInterceptor, ICellRenderContext, IRange, Workbook } from '@univerjs/core';
import { DataValidationRenderMode, DataValidationStatus, DataValidationType, ICommandService, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, Optional, RxDisposable, sequenceExecute, UniverInstanceType, WrapStrategy } from '@univerjs/core';
import { DataValidatorRegistryService } from '@univerjs/data-validation';
-import { IMenuManagerService } from '@univerjs/ui';
-import { AutoHeightController, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import type { Spreadsheet } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import { InterceptCellContentPriority, INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { AutoHeightController, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { IMenuManagerService } from '@univerjs/ui';
import { bufferTime, debounceTime, filter } from 'rxjs';
-import { getCellValueOrigin } from '../utils/get-cell-data-origin';
-import type { ListValidator } from '../validators';
-import { DataValidationDropdownManagerService } from '../services/dropdown-manager.service';
+import type { ICellDataForSheetInterceptor, ICellRenderContext, IRange, Workbook } from '@univerjs/core';
+import type { Spreadsheet } from '@univerjs/engine-render';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
+import { DataValidationDropdownManagerService } from '../services/dropdown-manager.service';
+import { getCellValueOrigin } from '../utils/get-cell-data-origin';
import { menuSchema } from './menu.schema';
+import type { ListValidator } from '../validators';
const INVALID_MARK = {
tr: {
@@ -139,7 +139,8 @@ export class SheetsDataValidationRenderController extends RxDisposable {
if (!subUnitId) return;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
+ ?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)
?.skeleton;
const currentRender = this._renderManagerService.getRenderById(unitId);
@@ -168,7 +169,8 @@ export class SheetsDataValidationRenderController extends RxDisposable {
const { row, col, unitId, subUnitId, workbook, worksheet } = pos;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
+ ?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)
?.skeleton;
if (!skeleton) {
return next(cell);
@@ -243,11 +245,8 @@ export class SheetsDataValidationRenderController extends RxDisposable {
...(cell?.customRender ?? []),
...(validator?.canvasRender ? [validator.canvasRender] : []),
],
- // @ts-ignore
fontRenderExtension: {
- // @ts-ignore
...cell?.fontRenderExtension,
- // @ts-ignore
isSkip: cell?.fontRenderExtension?.isSkip || validator?.skipDefaultFontRender(rule, cellValue, pos),
},
interceptorStyle: {
@@ -342,7 +341,8 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
if (!subUnitId) return;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
+ ?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)
?.skeleton;
const currentRender = this._renderManagerService.getRenderById(unitId);
@@ -370,7 +370,8 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
const { row, col, unitId, subUnitId, workbook, worksheet } = pos;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
+ ?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)
?.skeleton;
if (!skeleton) {
return next(cell);
@@ -495,7 +496,8 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
.pipe(
filter((change) => change.source === 'command'),
bufferTime(16)
- ).subscribe((infos) => {
+ )
+ .subscribe((infos) => {
const ranges: IRange[] = [];
infos.forEach((info) => {
if (info.rule?.ranges) {
diff --git a/packages/sheets-data-validation/src/controllers/dv-sheet.controller.ts b/packages/sheets-data-validation/src/controllers/dv-sheet.controller.ts
index 4de3255d3c..f5db16c852 100644
--- a/packages/sheets-data-validation/src/controllers/dv-sheet.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-sheet.controller.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
import { Disposable, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
-import type { IAddDataValidationMutationParams, IRemoveDataValidationMutationParams } from '@univerjs/data-validation';
import { AddDataValidationMutation, RemoveDataValidationMutation } from '@univerjs/data-validation';
-import type { IRemoveSheetCommandParams } from '@univerjs/sheets';
import { RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';
+import type { Workbook } from '@univerjs/core';
+import type { IAddDataValidationMutationParams, IRemoveDataValidationMutationParams } from '@univerjs/data-validation';
+import type { IRemoveSheetCommandParams } from '@univerjs/sheets';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
@OnLifecycle(LifecycleStages.Ready, SheetDataValidationSheetController)
diff --git a/packages/sheets-data-validation/src/index.ts b/packages/sheets-data-validation/src/index.ts
index 46dc0eedd4..ec2a5eeaeb 100644
--- a/packages/sheets-data-validation/src/index.ts
+++ b/packages/sheets-data-validation/src/index.ts
@@ -14,43 +14,43 @@
* limitations under the License.
*/
-export { UniverSheetsDataValidationPlugin } from './plugin';
-export { UniverSheetsDataValidationMobilePlugin } from './mobile-plugin';
-export { DataValidationCacheService } from './services/dv-cache.service';
-export type { IDataValidationResCache } from './services/dv-cache.service';
-export { DataValidationFormulaService } from './services/dv-formula.service';
-export { DataValidationCustomFormulaService } from './services/dv-custom-formula.service';
-export { DATA_VALIDATION_PLUGIN_NAME } from './common/const';
-export { SheetsDataValidationValidatorService } from './services/dv-validator-service';
-export { SheetDataValidationModel } from './models/sheet-data-validation-model';
-export { DataValidationModel } from '@univerjs/data-validation';
// #region - all commands
export {
- UpdateSheetDataValidationRangeCommand,
- UpdateSheetDataValidationOptionsCommand,
- UpdateSheetDataValidationSettingCommand,
- AddSheetDataValidationCommand,
AddSheetDataValidationAndOpenCommand,
+ AddSheetDataValidationCommand,
ClearRangeDataValidationCommand,
- RemoveSheetAllDataValidationCommand,
- RemoveSheetDataValidationCommand,
- type IRemoveSheetDataValidationCommandParams,
type IAddSheetDataValidationCommandParams,
- type IUpdateSheetDataValidationRangeCommandParams,
- type IUpdateSheetDataValidationOptionsCommandParams,
- type IUpdateSheetDataValidationSettingCommandParams,
type IClearRangeDataValidationCommandParams,
type IRemoveSheetAllDataValidationCommandParams,
+ type IRemoveSheetDataValidationCommandParams,
+ type IUpdateSheetDataValidationOptionsCommandParams,
+ type IUpdateSheetDataValidationRangeCommandParams,
+ type IUpdateSheetDataValidationSettingCommandParams,
+ RemoveSheetAllDataValidationCommand,
+ RemoveSheetDataValidationCommand,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+ UpdateSheetDataValidationSettingCommand,
} from './commands/commands/data-validation.command';
-
export {
- OpenValidationPanelOperation,
CloseValidationPanelOperation,
- ToggleValidationPanelOperation,
- ShowDataValidationDropdown,
HideDataValidationDropdown,
+ OpenValidationPanelOperation,
+ ShowDataValidationDropdown,
+ ToggleValidationPanelOperation,
} from './commands/operations/data-validation.operation';
+export { DATA_VALIDATION_PLUGIN_NAME } from './common/const';
+export { UniverSheetsDataValidationMobilePlugin } from './mobile-plugin';
+export { SheetDataValidationModel } from './models/sheet-data-validation-model';
+export { UniverSheetsDataValidationPlugin } from './plugin';
+export { DataValidationCacheService } from './services/dv-cache.service';
+export type { IDataValidationResCache } from './services/dv-cache.service';
+export { DataValidationCustomFormulaService } from './services/dv-custom-formula.service';
+export { DataValidationFormulaService } from './services/dv-formula.service';
+export { SheetsDataValidationValidatorService } from './services/dv-validator-service';
+
+export { DATE_DROPDOWN_KEY, LIST_DROPDOWN_KEY } from './views';
-export { LIST_DROPDOWN_KEY, DATE_DROPDOWN_KEY } from './views';
+export { DataValidationModel } from '@univerjs/data-validation';
// #endregion
diff --git a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
index 0b01847518..203712991d 100644
--- a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
+++ b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import type { ICellDataForSheetInterceptor, ISheetDataValidationRule, Nullable, Workbook } from '@univerjs/core';
import { DataValidationStatus, DataValidationType, Disposable, Inject, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, UniverInstanceType } from '@univerjs/core';
-import type { IRuleChange, IUpdateRulePayload, IValidStatusChange } from '@univerjs/data-validation';
import { DataValidationModel, DataValidatorRegistryService, UpdateRuleType } from '@univerjs/data-validation';
import { isReferenceString } from '@univerjs/engine-formula';
-import type { ISheetLocation } from '@univerjs/sheets';
import { Subject } from 'rxjs';
+import type { ICellDataForSheetInterceptor, ISheetDataValidationRule, Nullable, Workbook } from '@univerjs/core';
+import type { IRuleChange, IUpdateRulePayload, IValidStatusChange } from '@univerjs/data-validation';
+import type { ISheetLocation } from '@univerjs/sheets';
import { DataValidationCacheService } from '../services/dv-cache.service';
import { DataValidationCustomFormulaService } from '../services/dv-custom-formula.service';
import { DataValidationFormulaService } from '../services/dv-formula.service';
diff --git a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts b/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
index cf54c2c724..91f2eb8ef9 100644
--- a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
+++ b/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
@@ -14,16 +14,16 @@
* limitations under the License.
*/
-import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
import { Disposable, DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DataValidatorRegistryService } from '@univerjs/data-validation';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { type ISheetLocation, SheetsSelectionsService } from '@univerjs/sheets';
-import { Subject } from 'rxjs';
import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
-import { DataValidatorRegistryService } from '@univerjs/data-validation';
import { IZenZoneService } from '@univerjs/ui';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { DROP_DOWN_KEY } from '../views/drop-down';
+import { Subject } from 'rxjs';
+import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
+import { DROP_DOWN_KEY } from '../views/drop-down';
export interface IDropdownParam {
location: ISheetLocation;
diff --git a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts b/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
index 60243e3fa6..a318534f18 100644
--- a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
+++ b/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { IRange, ISheetDataValidationRule } from '@univerjs/core';
import { DataValidationType, Disposable, ILogService, Inject, isFormulaString, IUniverInstanceService, ObjectMatrix, Range, UniverInstanceType } from '@univerjs/core';
+import { DataValidationModel } from '@univerjs/data-validation';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';
-import { DataValidationModel } from '@univerjs/data-validation';
+import type { IRange, ISheetDataValidationRule } from '@univerjs/core';
import { DataValidationCacheService } from './dv-cache.service';
interface IDataValidationFormula {
diff --git a/packages/sheets-data-validation/src/services/dv-formula.service.ts b/packages/sheets-data-validation/src/services/dv-formula.service.ts
index 123e0d3f5f..9a18a235d1 100644
--- a/packages/sheets-data-validation/src/services/dv-formula.service.ts
+++ b/packages/sheets-data-validation/src/services/dv-formula.service.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
import { Disposable, Inject, isFormulaString, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import type { IFormulaInfo, IOtherFormulaResult } from '@univerjs/sheets-formula';
-import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';
import { DataValidationModel } from '@univerjs/data-validation';
+import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';
+import type { Nullable } from '@univerjs/core';
+import type { IFormulaInfo, IOtherFormulaResult } from '@univerjs/sheets-formula';
import { DataValidationCacheService } from './dv-cache.service';
type RuleId = string;
diff --git a/packages/sheets-data-validation/src/services/dv-validator-service.ts b/packages/sheets-data-validation/src/services/dv-validator-service.ts
index 00b9a403f3..4b65eaebc4 100644
--- a/packages/sheets-data-validation/src/services/dv-validator-service.ts
+++ b/packages/sheets-data-validation/src/services/dv-validator-service.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook } from '@univerjs/core';
import { DataValidationStatus, Inject, IUniverInstanceService, Range, Tools, UniverInstanceType } from '@univerjs/core';
+import type { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook } from '@univerjs/core';
import { SheetDataValidationModel } from '../models/sheet-data-validation-model';
-import type { IDataValidationResCache } from './dv-cache.service';
import { DataValidationCacheService } from './dv-cache.service';
+import type { IDataValidationResCache } from './dv-cache.service';
export class SheetsDataValidationValidatorService {
constructor(
diff --git a/packages/sheets-data-validation/src/utils/create.ts b/packages/sheets-data-validation/src/utils/create.ts
index 9784c22c29..d7af36f48b 100644
--- a/packages/sheets-data-validation/src/utils/create.ts
+++ b/packages/sheets-data-validation/src/utils/create.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
import { DataValidationOperator, DataValidationType, Tools } from '@univerjs/core';
import { SheetsSelectionsService } from '@univerjs/sheets';
+import type { IAccessor } from '@univerjs/core';
export function createDefaultNewRule(accessor: IAccessor) {
const selectionManagerService = accessor.get(SheetsSelectionsService);
diff --git a/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts b/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts
index 03e95b7e75..e6b5f41b3b 100644
--- a/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts
+++ b/packages/sheets-data-validation/src/utils/get-cell-data-origin.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DEFAULT_EMPTY_DOCUMENT_VALUE, type ICellData, type Nullable } from '@univerjs/core';
+import { DataStreamTreeTokenType, DEFAULT_EMPTY_DOCUMENT_VALUE, type ICellData, type Nullable } from '@univerjs/core';
export function getCellValueOrigin(cell: Nullable<ICellData>) {
if (cell === null) {
@@ -32,7 +32,7 @@ export function getCellValueOrigin(cell: Nullable<ICellData>) {
const lastString = data.substring(data.length - 2, data.length);
const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;
- return newDataStream;
+ return newDataStream.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
}
return cell?.v;
diff --git a/packages/sheets-data-validation/src/validators/date-validator.ts b/packages/sheets-data-validation/src/validators/date-validator.ts
index 337e68017d..2dc5c8f93f 100644
--- a/packages/sheets-data-validation/src/validators/date-validator.ts
+++ b/packages/sheets-data-validation/src/validators/date-validator.ts
@@ -15,16 +15,16 @@
*/
import { DataValidationOperator, DataValidationType, isFormulaString, numfmt, Tools } from '@univerjs/core';
-import type { CellValue, IDataValidationRule, IDataValidationRuleBase, Nullable } from '@univerjs/core';
+import { BaseDataValidator } from '@univerjs/data-validation';
import dayjs from 'dayjs';
+import type { CellValue, IDataValidationRule, IDataValidationRuleBase, Nullable } from '@univerjs/core';
import type { IFormulaResult, IFormulaValidResult, IValidatorCellInfo } from '@univerjs/data-validation';
-import { BaseDataValidator } from '@univerjs/data-validation';
-import { BASE_FORMULA_INPUT_NAME } from '../views/formula-input';
-import { TWO_FORMULA_OPERATOR_COUNT } from '../types/const/two-formula-operators';
+import { DateOperatorErrorTitleMap, DateOperatorNameMap, DateOperatorTitleMap } from '../common/date-text-map';
import { DataValidationFormulaService } from '../services/dv-formula.service';
+import { TWO_FORMULA_OPERATOR_COUNT } from '../types/const/two-formula-operators';
import { getFormulaResult } from '../utils/formula';
import { DATE_DROPDOWN_KEY } from '../views';
-import { DateOperatorErrorTitleMap, DateOperatorNameMap, DateOperatorTitleMap } from '../common/date-text-map';
+import { BASE_FORMULA_INPUT_NAME } from '../views/formula-input';
import { DateShowTimeOption } from '../views/show-time';
const FORMULA1 = '{FORMULA1}';
diff --git a/packages/sheets-data-validation/src/views/detail/index.tsx b/packages/sheets-data-validation/src/views/detail/index.tsx
index 2f1fe3aa5b..048b39d61f 100644
--- a/packages/sheets-data-validation/src/views/detail/index.tsx
+++ b/packages/sheets-data-validation/src/views/detail/index.tsx
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-import type { DataValidationOperator, DataValidationType, IDataValidationRuleBase, IDataValidationRuleOptions, IExecutionOptions, ISheetDataValidationRule, IUnitRange } from '@univerjs/core';
import { createInternalEditorID, debounce, ICommandService, isUnitRangesEqual, isValidRange, LocaleService, RedoCommand, shallowEqual, UndoCommand, useDependency } from '@univerjs/core';
import { DataValidationModel, DataValidatorRegistryScope, DataValidatorRegistryService, getRuleOptions, getRuleSetting, TWO_FORMULA_OPERATOR_COUNT } from '@univerjs/data-validation';
import { Button, FormLayout, Select } from '@univerjs/design';
+import { serializeRange } from '@univerjs/engine-formula';
import { ComponentManager, RangeSelector, useEvent, useObservable } from '@univerjs/ui';
import React, { useEffect, useMemo, useState } from 'react';
-import { serializeRange } from '@univerjs/engine-formula';
-import type { IUpdateSheetDataValidationRangeCommandParams } from '../../commands/commands/data-validation.command';
+import type { DataValidationOperator, DataValidationType, IDataValidationRuleBase, IDataValidationRuleOptions, IExecutionOptions, ISheetDataValidationRule, IUnitRange } from '@univerjs/core';
import { RemoveSheetDataValidationCommand, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '../../commands/commands/data-validation.command';
-import { DataValidationOptions } from '../options';
import { DataValidationPanelService } from '../../services/data-validation-panel.service';
+import { DataValidationOptions } from '../options';
import styles from './index.module.less';
+import type { IUpdateSheetDataValidationRangeCommandParams } from '../../commands/commands/data-validation.command';
// debounce execute commands, for better redo-undo experience
const debounceExecuteFactory = (commandService: ICommandService) => debounce(
diff --git a/packages/sheets-data-validation/src/views/item/index.tsx b/packages/sheets-data-validation/src/views/item/index.tsx
index ffdb5d62cd..5ac83ec6c8 100644
--- a/packages/sheets-data-validation/src/views/item/index.tsx
+++ b/packages/sheets-data-validation/src/views/item/index.tsx
@@ -15,12 +15,12 @@
*/
import { ICommandService, type ISheetDataValidationRule } from '@univerjs/core';
-import { DataValidatorRegistryService } from '@univerjs/data-validation';
import { useDependency } from '@univerjs/core';
-import React, { useEffect, useRef, useState } from 'react';
+import { DataValidatorRegistryService } from '@univerjs/data-validation';
import { serializeRange } from '@univerjs/engine-formula';
import { DeleteSingle } from '@univerjs/icons';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import React, { useEffect, useRef, useState } from 'react';
import { RemoveSheetDataValidationCommand } from '../../commands/commands/data-validation.command';
import styles from './index.module.less';
diff --git a/packages/sheets-data-validation/src/views/list/index.tsx b/packages/sheets-data-validation/src/views/list/index.tsx
index d87a2ed569..7dd99f0ed5 100644
--- a/packages/sheets-data-validation/src/views/list/index.tsx
+++ b/packages/sheets-data-validation/src/views/list/index.tsx
@@ -14,19 +14,19 @@
* limitations under the License.
*/
-import React, { useEffect, useState } from 'react';
import { ICommandService, Injector, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
-import type { ISheetDataValidationRule, Workbook } from '@univerjs/core';
import { Button } from '@univerjs/design';
-import { useObservable } from '@univerjs/ui';
import { checkRangesEditablePermission } from '@univerjs/sheets';
-import { DataValidationItem } from '../item';
-import type { IAddSheetDataValidationCommandParams } from '../../commands/commands/data-validation.command';
+import { useObservable } from '@univerjs/ui';
+import React, { useEffect, useState } from 'react';
+import type { ISheetDataValidationRule, Workbook } from '@univerjs/core';
import { AddSheetDataValidationCommand, RemoveSheetAllDataValidationCommand } from '../../commands/commands/data-validation.command';
-import { DataValidationPanelService } from '../../services/data-validation-panel.service';
import { SheetDataValidationModel } from '../../models/sheet-data-validation-model';
+import { DataValidationPanelService } from '../../services/data-validation-panel.service';
import { createDefaultNewRule } from '../../utils/create';
+import { DataValidationItem } from '../item';
import styles from './index.module.less';
+import type { IAddSheetDataValidationCommandParams } from '../../commands/commands/data-validation.command';
export function DataValidationList() {
const univerInstanceService = useDependency(IUniverInstanceService);
diff --git a/packages/sheets-data-validation/src/widgets/checkbox-widget.ts b/packages/sheets-data-validation/src/widgets/checkbox-widget.ts
index 18d185fcea..e476306458 100644
--- a/packages/sheets-data-validation/src/widgets/checkbox-widget.ts
+++ b/packages/sheets-data-validation/src/widgets/checkbox-widget.ts
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-import type { IMouseEvent, IPointerEvent, UniverRenderingContext, UniverRenderingContext2D } from '@univerjs/engine-render';
-import { Checkbox, fixLineWidthByScale, Transform } from '@univerjs/engine-render';
import { HorizontalAlign, ICommandService, Inject, isFormulaString, ThemeService, VerticalAlign } from '@univerjs/core';
-import type { ICellRenderContext, IDataValidationRule, IStyleData, Nullable } from '@univerjs/core';
-import type { ISetRangeValuesCommandParams } from '@univerjs/sheets';
+import { Checkbox, fixLineWidthByScale, Transform } from '@univerjs/engine-render';
import { SetRangeValuesCommand } from '@univerjs/sheets';
+import type { ICellRenderContext, IDataValidationRule, IStyleData, Nullable } from '@univerjs/core';
import type { BaseDataValidator, IBaseDataValidationWidget, IFormulaResult } from '@univerjs/data-validation';
-import type { CheckboxValidator } from '../validators/checkbox-validator';
-import { CHECKBOX_FORMULA_1, CHECKBOX_FORMULA_2, transformCheckboxValue } from '../validators/checkbox-validator';
+import type { IMouseEvent, IPointerEvent, UniverRenderingContext, UniverRenderingContext2D } from '@univerjs/engine-render';
+import type { ISetRangeValuesCommandParams } from '@univerjs/sheets';
import { DataValidationFormulaService } from '../services/dv-formula.service';
import { getFormulaResult } from '../utils/formula';
import { getCellValueOrigin } from '../utils/get-cell-data-origin';
+import { CHECKBOX_FORMULA_1, CHECKBOX_FORMULA_2, transformCheckboxValue } from '../validators/checkbox-validator';
+import type { CheckboxValidator } from '../validators/checkbox-validator';
const MARGIN_H = 6;
diff --git a/packages/sheets-data-validation/src/widgets/dropdown-multiple-widget.ts b/packages/sheets-data-validation/src/widgets/dropdown-multiple-widget.ts
index bab5ff3dc7..bad810a2a3 100644
--- a/packages/sheets-data-validation/src/widgets/dropdown-multiple-widget.ts
+++ b/packages/sheets-data-validation/src/widgets/dropdown-multiple-widget.ts
@@ -79,8 +79,7 @@ export class DropdownMultipleWidget implements IBaseDataValidationWidget {
const { primaryWithCoord, row, col, style, data, subUnitId } = info;
const _cellBounding = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
- // @ts-ignore
- const fontRenderExtension = data.fontRenderExtension as ISheetFontRenderExtension['fontRenderExtension'];
+ const fontRenderExtension = data.fontRenderExtension;
const { leftOffset = 0, rightOffset = 0, topOffset = 0, downOffset = 0 } = fontRenderExtension || {};
const validation = data.dataValidation;
@@ -171,8 +170,7 @@ export class DropdownMultipleWidget implements IBaseDataValidationWidget {
calcCellAutoHeight(info: ICellRenderContext): number | undefined {
const { primaryWithCoord, style, data } = info;
- // @ts-ignore
- const fontRenderExtension = data.fontRenderExtension as ISheetFontRenderExtension['fontRenderExtension'];
+ const fontRenderExtension = data.fontRenderExtension;
const { leftOffset = 0, rightOffset = 0, topOffset = 0, downOffset = 0 } = fontRenderExtension || {};
const _cellBounding = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
const cellBounding = {
diff --git a/packages/sheets-data-validation/src/widgets/dropdown-widget.ts b/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
index 42b92987fd..e7725033ea 100644
--- a/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
+++ b/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
@@ -17,7 +17,7 @@
import { BooleanNumber, DataValidationRenderMode, DataValidationType, DEFAULT_EMPTY_DOCUMENT_VALUE, DEFAULT_STYLES, DocumentDataModel, HorizontalAlign, ICommandService, Inject, LocaleService, Tools, VerticalAlign, WrapStrategy } from '@univerjs/core';
import type { ICellRenderContext, IDocumentData, IPaddingData, IStyleData, Nullable } from '@univerjs/core';
import { Documents, DocumentSkeleton, DocumentViewModel, getDocsSkeletonPageSize, Rect } from '@univerjs/engine-render';
-import type { IMouseEvent, IPointerEvent, ISheetFontRenderExtension, SpreadsheetSkeleton, UniverRenderingContext, UniverRenderingContext2D } from '@univerjs/engine-render';
+import type { IMouseEvent, IPointerEvent, SpreadsheetSkeleton, UniverRenderingContext, UniverRenderingContext2D } from '@univerjs/engine-render';
import type { IBaseDataValidationWidget } from '@univerjs/data-validation';
import { getCellValueOrigin } from '../utils/get-cell-data-origin';
import { type IShowDataValidationDropdownParams, ShowDataValidationDropdown } from '../commands/operations/data-validation.operation';
@@ -155,13 +155,6 @@ export interface IDropdownInfo {
}
export class DropdownWidget implements IBaseDataValidationWidget {
- // static padding: IPaddingData = {
- // l: MARGIN_H + PADDING_H,
- // r: ICON_PLACE + MARGIN_H,
- // t: MARGIN_V,
- // b: MARGIN_V,
- // };
-
private _dropdownInfoMap: Map<string, Map<string, IDropdownInfo>> = new Map();
constructor(
@@ -227,8 +220,7 @@ export class DropdownWidget implements IBaseDataValidationWidget {
const _cellBounding = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
const rule = data.dataValidation?.rule;
const validator = data.dataValidation?.validator as ListValidator;
- // @ts-ignore
- const fontRenderExtension = data.fontRenderExtension as ISheetFontRenderExtension['fontRenderExtension'];
+ const fontRenderExtension = data.fontRenderExtension;
const { leftOffset = 0, rightOffset = 0, topOffset = 0, downOffset = 0 } = fontRenderExtension || {};
if (!rule || !validator || !validator || validator.id.indexOf(DataValidationType.LIST) !== 0) {
@@ -358,8 +350,7 @@ export class DropdownWidget implements IBaseDataValidationWidget {
const { primaryWithCoord, style, data } = info;
const _cellBounding = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
- // @ts-ignore
- const fontRenderExtension = data.fontRenderExtension as ISheetFontRenderExtension['fontRenderExtension'];
+ const fontRenderExtension = data.fontRenderExtension;
const { leftOffset = 0, rightOffset = 0, topOffset = 0, downOffset = 0 } = fontRenderExtension || {};
const rule = data.dataValidation?.rule;
diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui-desktop.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui-desktop.controller.ts
index 88c8b260de..c995db5555 100644
--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui-desktop.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui-desktop.controller.ts
@@ -131,7 +131,6 @@ export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileControl
this._popupDisposable = this._sheetCanvasPopupService.attachPopupToCell(startRow, col, {
componentKey: FILTER_PANEL_POPUP_KEY,
direction: 'horizontal',
- closeOnSelfTarget: true,
onClickOutside: () => this._commandService.syncExecuteCommand(CloseFilterPanelOperation.id),
offset: [5, 0],
});
diff --git a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
index abdec48a3c..d5b7f68448 100644
--- a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
+++ b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
@@ -185,9 +185,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
return next({
...cell,
- // @ts-ignore
fontRenderExtension: {
- // @ts-ignore
...cell?.fontRenderExtension,
rightOffset: FILTER_ICON_SIZE,
},
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index d69c14db41..9691ba6538 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -20,6 +20,7 @@ import {
ICommandService,
Inject,
Injector,
+ isInternalEditorID,
IUniverInstanceService,
LifecycleStages,
ObjectMatrix,
@@ -224,7 +225,8 @@ export class UpdateFormulaController extends Disposable {
this._univerInstanceService.getTypeOfUnitAdded$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
this._univerInstanceService.getTypeOfUnitAdded$<SlideDataModel>(UniverInstanceType.UNIVER_SLIDE)
).pipe(
- filter((unit) => this._editorService.getEditor(unit.getUnitId()) == null)
+ filter((unit) => this._editorService.getEditor(unit.getUnitId()) == null),
+ filter((unit) => !isInternalEditorID(unit.getUnitId()))
).subscribe((unit) => this._handleUnitAdded(unit))
)
);
diff --git a/packages/sheets-hyper-link-ui/package.json b/packages/sheets-hyper-link-ui/package.json
index 01b08b686e..add0023f57 100644
--- a/packages/sheets-hyper-link-ui/package.json
+++ b/packages/sheets-hyper-link-ui/package.json
@@ -68,7 +68,6 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
- "@univerjs/docs-hyper-link": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
diff --git a/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts b/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts
index a29ff8cf20..4963e00a69 100644
--- a/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts
@@ -14,11 +14,15 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';
-import { SheetInterceptorService } from '@univerjs/sheets';
-import type { ICellHyperLink } from '@univerjs/sheets-hyper-link';
-import { AddHyperLinkMutation, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { BuildTextUtils, CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { addCustomRangeBySelectionFactory } from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';
+import { AddHyperLinkMutation, HyperLinkModel, type ICellHyperLink, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { ICommand, IDocumentData, IMutationInfo, Workbook } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
export interface IAddHyperLinkCommandParams {
unitId: string;
@@ -31,35 +35,135 @@ export interface IAddHyperLinkCommandParams {
export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
type: CommandType.COMMAND,
id: 'sheets.command.add-hyper-link',
+
+ // eslint-disable-next-line max-lines-per-function
async handler(accessor, params) {
if (!params) {
return false;
}
- const sheetInterceptorService = accessor.get(SheetInterceptorService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
+ const renderManagerService = accessor.get(IRenderManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const hyperLinkModel = accessor.get(HyperLinkModel);
+
const { unitId, subUnitId, link } = params;
- const { redos, undos } = sheetInterceptorService.onCommandExecute({
- id: AddHyperLinkCommand.id,
- params,
- });
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const currentRender = renderManagerService.getRenderById(unitId);
+ if (!currentRender || !workbook) {
+ return false;
+ }
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ const skeletonManagerService = currentRender.with(SheetSkeletonManagerService);
+ const skeleton = skeletonManagerService.getCurrent()?.skeleton;
+ if (!worksheet || !skeleton) {
+ return false;
+ }
+ const { payload, display, row, column, id } = link;
+ const cellData = worksheet.getCell(row, column);
+ const doc = skeleton.getBlankCellDocumentModel(cellData);
+ const snapshot = doc.documentModel!.getSnapshot();
+ const body = snapshot.body;
+ if (!body) {
+ return false;
+ }
+
+ let textX: TextX | false;
+ if (display) {
+ textX = BuildTextUtils.selection.replace({
+ selection: {
+ startOffset: 0,
+ endOffset: body.dataStream.length - 2,
+ collapsed: true,
+ },
+ body: {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ customRanges: [{
+ startIndex: 0,
+ endIndex: display.length + 1,
+ rangeType: CustomRangeType.HYPERLINK,
+ rangeId: id,
+ properties: {
+ url: payload,
+ // refId: id,
+ },
+ }],
+ },
+ doc: doc.documentModel!,
+ });
+ } else {
+ textX = BuildTextUtils.customRange.add({
+ body,
+ range: { startOffset: 0, endOffset: body.dataStream.length - 2, collapsed: false },
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: payload,
+ refId: id,
+ },
+ });
+ }
+
+ if (!textX) {
+ return false;
+ }
+
+ const newBody = TextX.apply(body, textX.serialize());
+ const rangeValue: IDocumentData = {
+ ...snapshot,
+ body: newBody,
+ };
+
+ const redoParams: ISetRangeValuesMutationParams = {
+ unitId,
+ subUnitId,
+ cellValue: {
+ [link.row]: {
+ [link.column]: {
+ p: rangeValue,
+ t: CellValueType.STRING,
+ },
+ },
+ },
+ };
+
const redo: IMutationInfo = {
- id: AddHyperLinkMutation.id,
- params,
+ id: SetRangeValuesMutation.id,
+ params: redoParams,
};
+ const undoParams = SetRangeValuesUndoMutationFactory(accessor, redoParams);
+
const undo: IMutationInfo = {
- id: RemoveHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- id: link.id,
- },
+ id: SetRangeValuesMutation.id,
+ params: undoParams,
};
- const res = await sequenceExecuteAsync([redo, ...redos], commandService);
- if (res.result) {
+ const redos = [redo];
+ const undos = [undo];
+ const modelLink = hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);
+ if (modelLink) {
+ redos.push({
+ id: RemoveHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ id: modelLink.id,
+ },
+ });
+ undos.push({
+ id: AddHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ link: modelLink,
+ },
+ });
+ }
+
+ const res = await sequenceExecuteAsync(redos, commandService);
+ if (res) {
undoRedoService.pushUndoRedo({
- redoMutations: [redo, ...redos],
- undoMutations: [undo, ...undos],
+ redoMutations: redos,
+ undoMutations: undos,
unitID: unitId,
});
return true;
@@ -68,3 +172,45 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
return false;
},
};
+
+export interface IAddRichHyperLinkCommandParams {
+ /**
+ * url of link
+ */
+ documentId: string;
+ link: ICellHyperLink;
+}
+
+export const AddRichHyperLinkCommand: ICommand<IAddRichHyperLinkCommandParams> = {
+ id: 'sheets.command.add-rich-hyper-link',
+ type: CommandType.COMMAND,
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const { documentId, link } = params;
+ const commandService = accessor.get(ICommandService);
+ const textSelectionService = accessor.get(DocSelectionManagerService);
+ const newId = generateRandomId();
+ const { payload } = link;
+ const range = textSelectionService.getActiveTextRange();
+ if (!range) {
+ return false;
+ }
+ const replaceSelection = addCustomRangeBySelectionFactory(accessor, {
+ unitId: documentId,
+ rangeId: newId,
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: payload,
+ refId: newId,
+ },
+ });
+
+ if (replaceSelection) {
+ return commandService.syncExecuteCommand(replaceSelection.id, replaceSelection.params);
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-hyper-link-ui/src/commands/commands/remove-hyper-link.command.ts b/packages/sheets-hyper-link-ui/src/commands/commands/remove-hyper-link.command.ts
index 785755c248..19c3f34a02 100644
--- a/packages/sheets-hyper-link-ui/src/commands/commands/remove-hyper-link.command.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/commands/remove-hyper-link.command.ts
@@ -14,102 +14,171 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';
-import { SheetInterceptorService } from '@univerjs/sheets';
-import type { IAddHyperLinkMutationParams } from '@univerjs/sheets-hyper-link';
+import { BuildTextUtils, CellValueType, CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute, TextX, Tools, UniverInstanceType } from '@univerjs/core';
+import { deleteCustomRangeFactory } from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';
import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, Nullable, Workbook } from '@univerjs/core';
+import type { IAddHyperLinkMutationParams } from '@univerjs/sheets-hyper-link';
-export interface IRemoveHyperLinkCommandParams {
+export interface ICancelHyperLinkCommandParams {
unitId: string;
subUnitId: string;
/**
* id of link
*/
id: string;
+ row: number;
+ column: number;
}
-export const RemoveHyperLinkCommand: ICommand<IRemoveHyperLinkCommandParams> = {
+export const CancelHyperLinkCommand: ICommand<ICancelHyperLinkCommandParams> = {
type: CommandType.COMMAND,
- id: 'sheets.command.remove-hyper-link',
- async handler(accessor, params) {
+ id: 'sheets.command.cancel-hyper-link',
+
+ // eslint-disable-next-line max-lines-per-function
+ handler(accessor, params) {
if (!params) {
return false;
}
- const sheetInterceptorService = accessor.get(SheetInterceptorService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const model = accessor.get(HyperLinkModel);
- const { unitId, subUnitId, id } = params;
- const link = model.getHyperLink(unitId, subUnitId, id);
- const { redos, undos } = sheetInterceptorService.onCommandExecute({
- id: RemoveHyperLinkCommand.id,
- params,
- });
+ const renderManagerService = accessor.get(IRenderManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const hyperLinkModel = accessor.get(HyperLinkModel);
- const redo: IMutationInfo = {
- id: RemoveHyperLinkMutation.id,
- params,
- };
- const undo: IMutationInfo = {
- id: AddHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- link,
- } as IAddHyperLinkMutationParams,
+ const { unitId, subUnitId, row, column, id } = params;
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const currentRender = renderManagerService.getRenderById(unitId);
+ if (!currentRender || !workbook) {
+ return false;
+ }
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ const skeletonManagerService = currentRender.with(SheetSkeletonManagerService);
+ const skeleton = skeletonManagerService.getCurrent()?.skeleton;
+ if (!worksheet || !skeleton) {
+ return false;
+ }
+ const cellData = worksheet.getCell(row, column);
+ if (!cellData) {
+ return false;
+ }
+ const doc = skeleton.getCellDocumentModelWithFormula(cellData);
+ if (!doc?.documentModel) {
+ return false;
+ }
+ const snapshot = Tools.deepClone(doc.documentModel!.getSnapshot());
+
+ const range = snapshot.body?.customRanges?.find((range) => range.rangeId === id);
+ if (!range) {
+ return false;
+ }
+
+ const textX = BuildTextUtils.customRange.delete(accessor, { documentDataModel: doc.documentModel, rangeId: id });
+
+ if (!textX) {
+ return false;
+ }
+
+ const newBody = TextX.apply(snapshot.body!, textX.serialize());
+ const redos: IMutationInfo[] = [];
+ const undos: IMutationInfo[] = [];
+ const setRangeParams = {
+ unitId,
+ subUnitId,
+ cellValue: {
+ [row]: {
+ [column]: {
+ p: {
+ ...snapshot,
+ body: newBody,
+ },
+ t: CellValueType.STRING,
+ },
+ },
+ },
};
- const res = await sequenceExecuteAsync([redo, ...redos], commandService);
- if (res.result) {
+ redos.push({
+ id: SetRangeValuesMutation.id,
+ params: setRangeParams,
+ });
+
+ const undoParams = SetRangeValuesUndoMutationFactory(accessor, setRangeParams);
+
+ undos.push({
+ id: SetRangeValuesMutation.id,
+ params: undoParams,
+ });
+
+ const link = hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);
+ if (link) {
+ redos.push({
+ id: RemoveHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ id,
+ },
+ });
+ undos.push({
+ id: AddHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ link: {
+ ...link,
+ },
+ } as IAddHyperLinkMutationParams,
+ });
+ }
+
+ const res = sequenceExecute(redos, commandService).result;
+
+ if (res) {
undoRedoService.pushUndoRedo({
- redoMutations: [redo, ...redos],
- undoMutations: [undo, ...undos],
+ redoMutations: redos,
+ undoMutations: undos,
unitID: unitId,
});
return true;
}
-
return false;
},
};
-export const CancelHyperLinkCommand: ICommand<IRemoveHyperLinkCommandParams> = {
+export interface ICancelRichHyperLinkCommandParams extends ICancelHyperLinkCommandParams {
+ /**
+ * document id
+ */
+ documentId: string;
+}
+
+export const CancelRichHyperLinkCommand: ICommand<ICancelRichHyperLinkCommandParams> = {
type: CommandType.COMMAND,
- id: 'sheets.command.cancel-hyper-link',
- async handler(accessor, params) {
+ id: 'sheets.command.cancel-rich-hyper-link',
+ handler(accessor, params) {
if (!params) {
return false;
}
+ const { id: linkId, documentId } = params;
const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const model = accessor.get(HyperLinkModel);
- const { unitId, subUnitId, id } = params;
- const link = model.getHyperLink(unitId, subUnitId, id);
-
- const redo: IMutationInfo = {
- id: RemoveHyperLinkMutation.id,
- params,
- };
- const undo: IMutationInfo = {
- id: AddHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- link,
- } as IAddHyperLinkMutationParams,
- };
-
- const res = await sequenceExecuteAsync([redo], commandService);
- if (res.result) {
- undoRedoService.pushUndoRedo({
- redoMutations: [redo],
- undoMutations: [undo],
- unitID: unitId,
- });
- return true;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const doc = univerInstanceService.getUnit<DocumentDataModel>(documentId, UniverInstanceType.UNIVER_DOC);
+ const link = doc?.getBody()?.customRanges?.find((i) => i.rangeId === linkId);
+ let insert: Nullable<IDocumentBody> = null;
+ if (link && link.endIndex === doc!.getBody()!.dataStream.length - 3) {
+ insert = {
+ dataStream: ' ',
+ };
+ }
+ const doMutation = deleteCustomRangeFactory(accessor, { unitId: documentId, rangeId: linkId, insert });
+ if (!doMutation) {
+ return false;
}
- return false;
+ return commandService.syncExecuteCommand(doMutation.id, doMutation.params);
},
};
diff --git a/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts b/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts
index aec73a536b..539c625d89 100644
--- a/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts
@@ -14,68 +14,217 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';
-import { SheetInterceptorService } from '@univerjs/sheets';
-import type { ICellHyperLink, ICellLinkContent } from '@univerjs/sheets-hyper-link';
-import { HyperLinkModel, UpdateHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, getBodySlice, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, UniverInstanceType } from '@univerjs/core';
+import { replaceSelectionFactory } from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';
+import { AddHyperLinkMutation, HyperLinkModel, type ICellLinkContent, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { DocumentDataModel, ICommand, IMutationInfo, Workbook } from '@univerjs/core';
export interface IUpdateHyperLinkCommandParams {
unitId: string;
subUnitId: string;
id: string;
payload: ICellLinkContent;
-}
-
-function getHyperLinkContent(link: ICellHyperLink) {
- const { row, column, id, ...content } = link;
- return content;
+ row: number;
+ column: number;
}
export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {
type: CommandType.COMMAND,
id: 'sheets.command.update-hyper-link',
+ // eslint-disable-next-line max-lines-per-function, complexity
async handler(accessor, params) {
if (!params) {
return false;
}
- const sheetInterceptorService = accessor.get(SheetInterceptorService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const model = accessor.get(HyperLinkModel);
- const { unitId, subUnitId, id } = params;
- const link = model.getHyperLink(unitId, subUnitId, id);
- if (!link) {
+ const renderManagerService = accessor.get(IRenderManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const hyperLinkModel = accessor.get(HyperLinkModel);
+ const { unitId, subUnitId, payload: link, row, column, id } = params;
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const currentRender = renderManagerService.getRenderById(unitId);
+ if (!currentRender || !workbook) {
+ return false;
+ }
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ const skeletonManagerService = currentRender.with(SheetSkeletonManagerService);
+ const skeleton = skeletonManagerService.getCurrent()?.skeleton;
+ if (!worksheet || !skeleton) {
return false;
}
- const { redos, undos } = sheetInterceptorService.onCommandExecute({
- id: UpdateHyperLinkCommand.id,
- params,
+ const { payload, display = '' } = link;
+ const cellData = worksheet.getCell(row, column);
+ if (!cellData) {
+ return false;
+ }
+ const doc = skeleton.getCellDocumentModelWithFormula(cellData);
+ if (!doc?.documentModel) {
+ return false;
+ }
+ const snapshot = doc.documentModel.getSnapshot();
+
+ const range = snapshot.body?.customRanges?.find((range) => range.rangeId === id);
+ if (!range) {
+ return false;
+ }
+
+ const newId = generateRandomId();
+ const oldBody = getBodySlice(doc.documentModel.getBody()!, range.startIndex, range.endIndex + 1);
+ const textRun = oldBody.textRuns?.[0];
+ if (textRun) {
+ textRun.ed = display.length + 1;
+ }
+
+ const replaceSelection = replaceSelectionFactory(accessor, {
+ unitId,
+ body: {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ customRanges: [{
+ rangeId: newId,
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: display.length + 1,
+ properties: {
+ url: payload,
+ },
+ }],
+ textRuns: textRun ? [textRun] : undefined,
+ },
+ selection: {
+ startOffset: range.startIndex,
+ endOffset: range.endIndex + 1,
+ collapsed: false,
+ },
+ doc: doc.documentModel,
});
- const redo: IMutationInfo = {
- id: UpdateHyperLinkMutation.id,
- params,
- };
- const undo: IMutationInfo = {
- id: UpdateHyperLinkMutation.id,
+ if (!replaceSelection) {
+ return false;
+ }
+ const newBody = TextX.apply(snapshot.body!, replaceSelection.textX.serialize());
+
+ const redo = {
+ id: SetRangeValuesMutation.id,
params: {
unitId,
subUnitId,
- id,
- payload: getHyperLinkContent(link),
+ cellValue: {
+ [row]: {
+ [column]: {
+ p: {
+ ...snapshot,
+ body: newBody,
+ },
+ t: CellValueType.STRING,
+ },
+ },
+ },
},
};
+ const undoParams = SetRangeValuesUndoMutationFactory(accessor, redo.params);
- const res = await sequenceExecuteAsync([redo, ...redos], commandService);
- if (res.result) {
+ const undo = {
+ id: SetRangeValuesMutation.id,
+ params: undoParams,
+ };
+ const redos: IMutationInfo[] = [redo];
+ const undos: IMutationInfo[] = [undo];
+ const modelLink = hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);
+ if (modelLink) {
+ redos.push({
+ id: RemoveHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ id: modelLink.id,
+ },
+ });
+ undos.push({
+ id: AddHyperLinkMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ link: modelLink,
+ },
+ });
+ }
+
+ const res = await sequenceExecuteAsync(redos, commandService);
+ if (res) {
undoRedoService.pushUndoRedo({
- redoMutations: [redo, ...redos],
- undoMutations: [undo, ...undos],
+ redoMutations: redos,
+ undoMutations: undos,
unitID: unitId,
});
return true;
}
-
return false;
},
};
+
+export interface IUpdateRichHyperLinkCommandParams {
+ documentId: string;
+ id: string;
+ payload: ICellLinkContent;
+}
+
+export const UpdateRichHyperLinkCommand: ICommand<IUpdateRichHyperLinkCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheets.command.update-rich-hyper-link',
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const { documentId: unitId, payload, id: rangeId } = params;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ if (!doc) {
+ return false;
+ }
+ const range = doc.getBody()?.customRanges?.find((range) => range.rangeId === rangeId);
+ if (!range) {
+ return false;
+ }
+
+ const display = params.payload.display ?? '';
+ const newId = generateRandomId();
+ const oldBody = getBodySlice(doc.getBody()!, range.startIndex, range.endIndex + 1);
+ const textRun = oldBody.textRuns?.[0];
+ if (textRun) {
+ textRun.ed = display.length + 1;
+ }
+
+ const replaceSelection = replaceSelectionFactory(accessor, {
+ unitId,
+ body: {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${display}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ customRanges: [{
+ rangeId: newId,
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: display.length + 1,
+ properties: {
+ url: payload.payload,
+ },
+ }],
+ textRuns: textRun ? [textRun] : undefined,
+ },
+ selection: {
+ startOffset: range.startIndex,
+ endOffset: range.endIndex + 1,
+ collapsed: false,
+ },
+ doc,
+ });
+
+ if (!replaceSelection) {
+ return false;
+ }
+
+ return commandService.syncExecuteCommand(replaceSelection.id, replaceSelection.params);
+ },
+};
diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts b/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
similarity index 60%
rename from packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts
rename to packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
index 4b6773265c..edcd8e8838 100644
--- a/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
@@ -14,54 +14,43 @@
* limitations under the License.
*/
-import { CommandType, type ICommand, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { CommandType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, type ICommand, ICommandService, IUniverInstanceService } from '@univerjs/core';
import { getSheetCommandTarget, type ISheetCommandSharedParams, SheetsSelectionsService } from '@univerjs/sheets';
-import { HyperLinkModel } from '@univerjs/sheets-hyper-link';
-import { ISidebarService } from '@univerjs/ui';
-import { CellLinkEdit } from '../../views/CellLinkEdit';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { SheetsHyperLinkPopupService } from '../../services/popup.service';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
-export interface IOpenHyperLinkSidebarOperationParams extends ISheetCommandSharedParams {
+export interface IOpenHyperLinkEditPanelOperationParams extends ISheetCommandSharedParams {
row: number;
- column: number;
+ col: number;
+ customRangeId?: string;
+ type: HyperLinkEditSourceType;
}
-export const OpenHyperLinkSidebarOperation: ICommand<IOpenHyperLinkSidebarOperationParams> = {
+export const OpenHyperLinkEditPanelOperation: ICommand<IOpenHyperLinkEditPanelOperationParams> = {
type: CommandType.OPERATION,
- id: 'sheet.operation.open-hyper-link-sidebar',
+ id: 'sheet.operation.open-hyper-link-edit-panel',
handler(accessor, params) {
if (!params) {
return false;
}
- const { unitId, subUnitId, row, column } = params;
- const hyperLinkModel = accessor.get(HyperLinkModel);
- const sidebarService = accessor.get(ISidebarService);
const popupService = accessor.get(SheetsHyperLinkPopupService);
- const currentLink = hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);
- popupService.startEditing(params);
-
- sidebarService.open({
- header: {
- title: !currentLink ? 'hyperLink.form.addTitle' : 'hyperLink.form.editTitle',
- },
- children: {
- label: CellLinkEdit.componentKey,
- },
- });
-
+ if (!params.customRangeId) {
+ popupService.startAddEditing(params);
+ } else {
+ popupService.startEditing(params as Required<IOpenHyperLinkEditPanelOperationParams>);
+ }
return true;
},
};
-export const CloseHyperLinkSidebarOperation: ICommand = {
+export const CloseHyperLinkPopupOperation: ICommand = {
type: CommandType.OPERATION,
- id: 'sheet.operation.close-hyper-link-sidebar',
+ id: 'sheet.operation.close-hyper-link-popup',
handler(accessor) {
- const sidebarService = accessor.get(ISidebarService);
const popupService = accessor.get(SheetsHyperLinkPopupService);
- sidebarService.close();
popupService.endEditing();
return true;
},
@@ -73,6 +62,7 @@ export const InsertHyperLinkOperation: ICommand = {
handler(accessor) {
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService);
+ const editorBridgeService = accessor.get(IEditorBridgeService);
if (!target) {
return false;
}
@@ -83,13 +73,18 @@ export const InsertHyperLinkOperation: ICommand = {
return false;
}
- const row = selection.primary.startRow;
- const column = selection.primary.startColumn;
- return commandService.executeCommand(OpenHyperLinkSidebarOperation.id, {
+ const row = selection.range.startRow;
+ const col = selection.range.startColumn;
+ const visible = editorBridgeService.isVisible();
+ const isZenEditor = univerInstanceService.getFocusedUnit()?.getUnitId() === DOCS_ZEN_EDITOR_UNIT_ID_KEY;
+ return commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
unitId: target.unitId,
subUnitId: target.subUnitId,
row,
- column,
+ col,
+ type: isZenEditor ?
+ HyperLinkEditSourceType.ZEN_EDITOR
+ : visible.visible ? HyperLinkEditSourceType.EDITING : HyperLinkEditSourceType.VIEWING,
});
},
};
@@ -101,7 +96,7 @@ export const InsertHyperLinkToolbarOperation: ICommand = {
const commandService = accessor.get(ICommandService);
const popupService = accessor.get(SheetsHyperLinkPopupService);
if (popupService.currentEditing) {
- return commandService.executeCommand(CloseHyperLinkSidebarOperation.id);
+ return commandService.executeCommand(CloseHyperLinkPopupOperation.id);
} else {
return commandService.executeCommand(InsertHyperLinkOperation.id);
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
index 425cbf9359..f8d77bb605 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
@@ -20,7 +20,7 @@ import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@
import type { IDiscreteRange, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME, rangeToDiscreteRange, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
import { SHEET_HYPER_LINK_UI_PLUGIN } from '../types/const';
-import { isLegalLink, serializeUrl } from '../common/util';
+import { isLegalLink } from '../common/util';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkCopyPasteController)
@@ -71,9 +71,8 @@ export class SheetsHyperLinkCopyPasteController extends Disposable {
},
onPastePlainText: (pasteTo: ISheetDiscreteRangeLocation, clipText: string) => {
const filterResult = this._filterPlainText(clipText);
- if (isLegalLink(clipText) && filterResult) {
- const text = serializeUrl(clipText);
+ if (isLegalLink(clipText) && filterResult) {
const { range, unitId, subUnitId } = pasteTo;
const { ranges: [pasteToRange], mapFunc } = virtualizeDiscreteRanges([range]);
const redos: IMutationInfo[] = [];
@@ -91,28 +90,6 @@ export class SheetsHyperLinkCopyPasteController extends Disposable {
},
});
}
- const newId = Tools.generateRandomId();
- redos.push({
- id: AddHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- link: {
- id: newId,
- row,
- column,
- payload: text,
- },
- },
- });
- undos.push({
- id: RemoveHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- id: newId,
- },
- });
if (link) {
undos.push({
id: AddHyperLinkMutation.id,
diff --git a/packages/sheets-hyper-link-ui/src/controllers/menu.schema.ts b/packages/sheets-hyper-link-ui/src/controllers/menu.schema.ts
index 96ab157758..287d2dd484 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/menu.schema.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/menu.schema.ts
@@ -16,8 +16,8 @@
import type { MenuSchemaType } from '@univerjs/ui';
import { ContextMenuGroup, ContextMenuPosition, RibbonStartGroup } from '@univerjs/ui';
-import { InsertHyperLinkToolbarOperation } from '../commands/operations/sidebar.operations';
-import { insertLinkMenuFactory, insertLinkMenuToolbarFactory } from './menu';
+import { InsertHyperLinkToolbarOperation } from '../commands/operations/popup.operations';
+import { genZenEditorMenuId, insertLinkMenuFactory, insertLinkMenuToolbarFactory, zenEditorInsertLinkMenuFactory, zenEditorInsertLinkMenuToolbarFactory } from './menu';
export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.OTHERS]: {
@@ -25,6 +25,10 @@ export const menuSchema: MenuSchemaType = {
order: 2,
menuItemFactory: insertLinkMenuToolbarFactory,
},
+ [genZenEditorMenuId(InsertHyperLinkToolbarOperation.id)]: {
+ order: 2,
+ menuItemFactory: zenEditorInsertLinkMenuToolbarFactory,
+ },
},
[ContextMenuPosition.MAIN_AREA]: {
[ContextMenuGroup.OTHERS]: {
@@ -33,6 +37,10 @@ export const menuSchema: MenuSchemaType = {
order: 0,
menuItemFactory: insertLinkMenuFactory,
},
+ [genZenEditorMenuId(InsertHyperLinkToolbarOperation.id)]: {
+ order: 0,
+ menuItemFactory: zenEditorInsertLinkMenuFactory,
+ },
},
},
};
diff --git a/packages/sheets-hyper-link-ui/src/controllers/menu.ts b/packages/sheets-hyper-link-ui/src/controllers/menu.ts
index 4b414a7acd..250542a415 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/menu.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/menu.ts
@@ -14,34 +14,177 @@
* limitations under the License.
*/
-import { UniverInstanceType } from '@univerjs/core';
+import { BuildTextUtils, CustomRangeType, DataValidationType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import type { IMenuItem, IShortcutItem } from '@univerjs/ui';
-import { getMenuHiddenObservable, KeyCode, MenuItemType, MetaKeys } from '@univerjs/ui';
-import type { IAccessor } from '@univerjs/core';
-import { getCurrentRangeDisable$, getObservableWithExclusiveRange$, whenSheetEditorFocused } from '@univerjs/sheets-ui';
-import { RangeProtectionPermissionEditPoint, WorkbookEditablePermission, WorksheetEditPermission, WorksheetInsertHyperlinkPermission, WorksheetSetCellValuePermission } from '@univerjs/sheets';
-import { InsertHyperLinkOperation, InsertHyperLinkToolbarOperation } from '../commands/operations/sidebar.operations';
+import { getMenuHiddenObservable, KeyCode, MenuGroup, MenuItemType, MenuPosition, MetaKeys } from '@univerjs/ui';
+import type { DocumentDataModel, IAccessor, ITextRange, Workbook } from '@univerjs/core';
+import { getCurrentRangeDisable$, whenSheetEditorFocused } from '@univerjs/sheets-ui';
+import { RangeProtectionPermissionEditPoint, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetInsertHyperlinkPermission, WorksheetSetCellValuePermission } from '@univerjs/sheets';
+import { map, mergeMap, Observable } from 'rxjs';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { InsertHyperLinkOperation, InsertHyperLinkToolbarOperation } from '../commands/operations/popup.operations';
+
+const getLinkDisable$ = (accessor: IAccessor) => {
+ const disableRange$ = getCurrentRangeDisable$(accessor, { workbookTypes: [WorkbookEditablePermission], worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission, WorksheetInsertHyperlinkPermission], rangeTypes: [RangeProtectionPermissionEditPoint] });
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const sheetSelectionService = accessor.get(SheetsSelectionsService);
+ const disableCell$ = univerInstanceService.focused$.pipe(
+ map((focused) => {
+ if (!focused) {
+ return null;
+ }
+ const unit = univerInstanceService.getUnit<Workbook>(focused, UniverInstanceType.UNIVER_SHEET);
+ return unit;
+ }),
+ mergeMap((unit) => {
+ if (!unit) {
+ return new Observable<null>((sub) => {
+ sub.next(null);
+ });
+ }
+ return unit.activeSheet$;
+ }),
+ mergeMap((sheet) => sheetSelectionService.selectionMoveEnd$.pipe(map((selections) => sheet && { selections, sheet }))),
+ map((sheetWithSelection) => {
+ if (!sheetWithSelection) {
+ return true;
+ }
+ const { selections, sheet } = sheetWithSelection;
+ if (!selections.length) {
+ return true;
+ }
+ const row = selections[0].range.startRow;
+ const col = selections[0].range.startColumn;
+ const cell = sheet.getCell(row, col);
+ if (cell?.f || cell?.si) {
+ return true;
+ }
+ const disables = [
+ DataValidationType.CHECKBOX,
+ DataValidationType.LIST,
+ DataValidationType.LIST_MULTIPLE,
+ ];
+
+ if (cell?.dataValidation && disables.includes(cell.dataValidation.rule.type)) {
+ return true;
+ }
+
+ return false;
+ })
+ );
+
+ return disableRange$.pipe(mergeMap(((disableRange) => disableCell$.pipe(map((disableCell) => disableRange || disableCell)))));
+};
+
+export const shouldDisableAddLink = (accessor: IAccessor) => {
+ const textSelectionService = accessor.get(DocSelectionManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const textRanges = textSelectionService.getDocRanges();
+ if (!textRanges.length || textRanges.length > 1) {
+ return true;
+ }
+
+ const activeRange = textRanges[0];
+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!doc || !activeRange || activeRange.collapsed) {
+ return true;
+ }
+
+ const body = doc.getSelfOrHeaderFooterModel(activeRange.segmentId).getBody();
+ const paragraphs = body?.paragraphs;
+ if (!paragraphs) {
+ return true;
+ }
+
+ for (let i = 0, len = paragraphs.length; i < len; i++) {
+ const p = paragraphs[i];
+ if (activeRange.startOffset! <= p.startIndex && activeRange.endOffset! > p.startIndex) {
+ return true;
+ }
+
+ if (p.startIndex > activeRange.endOffset!) {
+ break;
+ }
+ }
+
+ const insertCustomRanges = BuildTextUtils.customRange.getCustomRangesInterestsWithRange(activeRange as ITextRange, body.customRanges ?? []);
+ // can't insert hyperlink in range contains other custom ranges
+ return !insertCustomRanges.every((range) => range.rangeType === CustomRangeType.HYPERLINK);
+};
+
+const getZenLinkDisable$ = (accessor: IAccessor) => {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ return univerInstanceService.focused$.pipe(
+ mergeMap((focused) => {
+ if (!focused || focused !== DOCS_ZEN_EDITOR_UNIT_ID_KEY) {
+ return new Observable<null>((sub) => sub.next(null));
+ }
+ const textSelectionManagerService = accessor.get(DocSelectionManagerService);
+ return textSelectionManagerService.textSelection$;
+ }),
+ map((selection) => {
+ if (!selection || selection.unitId !== DOCS_ZEN_EDITOR_UNIT_ID_KEY) {
+ return true;
+ }
+
+ return shouldDisableAddLink(accessor);
+ })
+ );
+};
+
+const linkMenu = {
+ commandId: InsertHyperLinkOperation.id,
+ type: MenuItemType.BUTTON,
+ positions: [MenuPosition.CONTEXT_MENU],
+ title: 'hyperLink.menu.add',
+ icon: 'LinkSingle',
+};
+
+export const genZenEditorMenuId = (id: string) => `${id}-zen-editor`;
export const insertLinkMenuFactory = (accessor: IAccessor) => {
return {
- id: InsertHyperLinkOperation.id,
- type: MenuItemType.BUTTON,
- title: 'hyperLink.menu.add',
+ ...linkMenu,
+ id: linkMenu.commandId,
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
- icon: 'LinkSingle',
- disabled$: getObservableWithExclusiveRange$(accessor, getCurrentRangeDisable$(accessor, { workbookTypes: [WorkbookEditablePermission], worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission, WorksheetInsertHyperlinkPermission], rangeTypes: [RangeProtectionPermissionEditPoint] })),
+ disabled$: getLinkDisable$(accessor),
+ // disabled$: getObservableWithExclusiveRange$(accessor, getCurrentRangeDisable$(accessor, { workbookTypes: [WorkbookEditablePermission], worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission, WorksheetInsertHyperlinkPermission], rangeTypes: [RangeProtectionPermissionEditPoint] })),
} as IMenuItem;
};
+export const zenEditorInsertLinkMenuFactory = (accessor: IAccessor) => {
+ return {
+ ...linkMenu,
+ id: genZenEditorMenuId(linkMenu.commandId),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC, DOCS_ZEN_EDITOR_UNIT_ID_KEY),
+ disabled$: getZenLinkDisable$(accessor),
+ } as IMenuItem;
+};
+
+const linkToolbarMenu = {
+ tooltip: 'hyperLink.form.addTitle',
+ positions: MenuPosition.TOOLBAR_START,
+ group: MenuGroup.TOOLBAR_OTHERS,
+ commandId: InsertHyperLinkToolbarOperation.id,
+ type: MenuItemType.BUTTON,
+ icon: 'LinkSingle',
+};
+
export const insertLinkMenuToolbarFactory = (accessor: IAccessor) => {
return {
- tooltip: 'hyperLink.form.addTitle',
- id: InsertHyperLinkToolbarOperation.id,
- type: MenuItemType.BUTTON,
- icon: 'LinkSingle',
+ ...linkToolbarMenu,
+ id: linkToolbarMenu.commandId,
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
- disabled$: getObservableWithExclusiveRange$(accessor, getCurrentRangeDisable$(accessor, { workbookTypes: [WorkbookEditablePermission], worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission, WorksheetInsertHyperlinkPermission], rangeTypes: [RangeProtectionPermissionEditPoint] })),
+ disabled$: getLinkDisable$(accessor),
+ };
+};
+export const zenEditorInsertLinkMenuToolbarFactory = (accessor: IAccessor) => {
+ return {
+ ...linkToolbarMenu,
+ id: genZenEditorMenuId(linkToolbarMenu.commandId),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC, DOCS_ZEN_EDITOR_UNIT_ID_KEY),
+ disabled$: getZenLinkDisable$(accessor),
};
};
diff --git a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
index 0047ea07a7..798b039a27 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
@@ -14,12 +14,32 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, Inject, IPermissionService, LifecycleStages, OnLifecycle, Rectangle } from '@univerjs/core';
-import { HoverManagerService, SheetPermissionInterceptorBaseController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { debounceTime } from 'rxjs';
+import type { Nullable } from '@univerjs/core';
+import { CustomRangeType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, Inject, IPermissionService, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle } from '@univerjs/core';
+import { HoverManagerService, HoverRenderController, IEditorBridgeService, SheetPermissionInterceptorBaseController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { Subscription } from 'rxjs';
+import { debounceTime, map, mergeMap, Observable } from 'rxjs';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, WorkbookCopyPermission, WorkbookEditablePermission, WorkbookViewPermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetInsertHyperlinkPermission, WorksheetViewPermission } from '@univerjs/sheets';
+import type { ISheetLocationBase } from '@univerjs/sheets';
+import {
+ ClearSelectionAllCommand,
+ ClearSelectionContentCommand,
+ ClearSelectionFormatCommand,
+ RangeProtectionPermissionEditPoint,
+ RangeProtectionPermissionViewPoint,
+ WorkbookCopyPermission,
+ WorkbookEditablePermission,
+ WorkbookViewPermission,
+ WorksheetCopyPermission,
+ WorksheetEditPermission,
+ WorksheetInsertHyperlinkPermission,
+ WorksheetViewPermission,
+} from '@univerjs/sheets';
+import { DocEventManagerService } from '@univerjs/docs-ui';
+import { IZenZoneService } from '@univerjs/ui';
+import { DocSelectionManagerService } from '@univerjs/docs';
import { SheetsHyperLinkPopupService } from '../services/popup.service';
+import { HyperLinkEditSourceType } from '../types/enums/edit-source';
@OnLifecycle(LifecycleStages.Rendered, SheetsHyperLinkPopupController)
export class SheetsHyperLinkPopupController extends Disposable {
@@ -29,29 +49,70 @@ export class SheetsHyperLinkPopupController extends Disposable {
@Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
@Inject(IPermissionService) private readonly _permissionService: IPermissionService,
@Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IZenZoneService private readonly _zenZoneService: IZenZoneService
) {
super();
this._initHoverListener();
this._initCommandListener();
+ this._initHoverEditingListener();
+ this._initTextSelectionListener();
+ this._initZenEditor();
+ }
+
+ private _getLinkPermission(location: ISheetLocationBase) {
+ const { unitId, subUnitId, row: currentRow, col: currentCol } = location;
+ const viewPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
+ workbookTypes: [WorkbookViewPermission],
+ worksheetTypes: [WorksheetViewPermission],
+ rangeTypes: [RangeProtectionPermissionViewPoint],
+ }, [{ startRow: currentRow, startColumn: currentCol, endRow: currentRow, endColumn: currentCol }]);
+
+ const editPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetInsertHyperlinkPermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ }, [{ startRow: currentRow, startColumn: currentCol, endRow: currentRow, endColumn: currentCol }]);
+
+ const copyPermission = this._permissionService.composePermission([new WorkbookCopyPermission(unitId).id, new WorksheetCopyPermission(unitId, subUnitId).id]).every((permission) => permission.value);
+
+ return {
+ viewPermission,
+ editPermission,
+ copyPermission,
+ };
}
private _initHoverListener() {
this.disposeWithMe(
- this._hoverManagerService.currentCell$.pipe(debounceTime(200)).subscribe((currentCell) => {
+ // hover over not editing cell
+ this._hoverManagerService.currentRichText$.pipe(debounceTime(200)).subscribe((currentCell) => {
if (!currentCell) {
this._sheetsHyperLinkPopupService.hideCurrentPopup();
return;
}
- const skeleton = this._renderManagerService.getRenderById(currentCell.location.unitId)
- ?.with(SheetSkeletonManagerService)
- .getWorksheetSkeleton(currentCell.location.subUnitId)
+ const { unitId, subUnitId, row, col } = currentCell;
+ const renderer = this._renderManagerService.getRenderById(unitId);
+ if (!renderer) {
+ return;
+ }
+ const hoverRenderController = renderer.with(HoverRenderController);
+ if (!hoverRenderController.active) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.VIEWING);
+ return;
+ }
+
+ const skeleton = renderer?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(subUnitId)
?.skeleton;
- const currentCol = currentCell.location.col;
- const currentRow = currentCell.location.row;
+ const currentCol = col;
+ const currentRow = row;
let targetRow = currentRow;
let targetCol = currentCol;
@@ -64,38 +125,161 @@ export class SheetsHyperLinkPopupController extends Disposable {
});
}
- const viewPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
- workbookTypes: [WorkbookViewPermission],
- worksheetTypes: [WorksheetViewPermission],
- rangeTypes: [RangeProtectionPermissionViewPoint],
- }, [{ startRow: currentRow, startColumn: currentCol, endRow: currentRow, endColumn: currentCol }]);
- if (!viewPermission) {
+ const { viewPermission, editPermission, copyPermission } = this._getLinkPermission(currentCell);
+
+ if (!viewPermission || !currentCell.customRange) {
this._sheetsHyperLinkPopupService.hideCurrentPopup();
return;
}
- const editPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
- workbookTypes: [WorkbookEditablePermission],
- worksheetTypes: [WorksheetEditPermission, WorksheetInsertHyperlinkPermission],
- rangeTypes: [RangeProtectionPermissionEditPoint],
- }, [{ startRow: currentRow, startColumn: currentCol, endRow: currentRow, endColumn: currentCol }]);
-
- const unitId = currentCell.location.unitId;
- const subUnitId = currentCell.location.subUnitId;
-
- const copyPermission = this._permissionService.composePermission([new WorkbookCopyPermission(unitId).id, new WorksheetCopyPermission(unitId, subUnitId).id]).every((permission) => permission.value);
-
this._sheetsHyperLinkPopupService.showPopup({
- ...currentCell.location,
row: targetRow,
col: targetCol,
editPermission,
copyPermission,
+ customRange: currentCell.customRange,
+ customRangeRect: currentCell.rect,
+ type: HyperLinkEditSourceType.VIEWING,
+ unitId,
+ subUnitId,
});
})
);
}
+ private _initHoverEditingListener() {
+ let subscribe: Nullable<Subscription> = null;
+ this.disposeWithMe(
+ this._editorBridgeService.currentEditCellState$
+ .pipe(mergeMap((state) => this._editorBridgeService.visible$.pipe(map((visible) => ({ visible, state })))))
+ .subscribe(({ visible, state }) => {
+ if (!state) {
+ return;
+ }
+ if (state.editorUnitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ if (!visible.visible) {
+ subscribe?.unsubscribe();
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.EDITING);
+ this._sheetsHyperLinkPopupService.endEditing(HyperLinkEditSourceType.EDITING);
+ return;
+ }
+
+ const { editorUnitId, unitId, sheetId, row, column } = state;
+ const renderer = this._renderManagerService.getRenderById(editorUnitId);
+ if (!renderer) {
+ return;
+ }
+ const { editPermission, viewPermission, copyPermission } = this._getLinkPermission({ unitId, subUnitId: sheetId, row, col: column });
+ const docEventService = renderer.with(DocEventManagerService);
+ if (!viewPermission) {
+ return;
+ }
+ subscribe?.unsubscribe();
+ subscribe = docEventService.hoverCustomRanges$.pipe(debounceTime(200)).subscribe((customRanges) => {
+ const customRange = customRanges.find((customRange) => customRange.range.rangeType === CustomRangeType.HYPERLINK);
+ if (!customRange) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ return;
+ }
+ const rect = customRange.rects[customRange.rects.length - 1];
+ const skeleton = this._renderManagerService.getRenderById(unitId)
+ ?.with(SheetSkeletonManagerService)
+ .getWorksheetSkeleton(sheetId)
+ ?.skeleton;
+ if (!skeleton || !rect) {
+ return;
+ }
+ const canvasClientRect = renderer.engine.getCanvasElement().getBoundingClientRect();
+
+ this._sheetsHyperLinkPopupService.showPopup({
+ unitId,
+ subUnitId: sheetId,
+ row,
+ col: column,
+ customRange: customRange.range,
+ customRangeRect: {
+ left: rect.left + canvasClientRect.left,
+ top: rect.top + canvasClientRect.top,
+ bottom: rect.bottom + canvasClientRect.top,
+ right: rect.right + canvasClientRect.left,
+ },
+ editPermission,
+ copyPermission,
+ type: HyperLinkEditSourceType.EDITING,
+ });
+ });
+ })
+ );
+
+ this.disposeWithMe(() => {
+ subscribe?.unsubscribe();
+ });
+ }
+
+ private _initZenEditor() {
+ this.disposeWithMe(
+ this._zenZoneService.visible$.subscribe((visible) => {
+ if (visible) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.VIEWING);
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.EDITING);
+ this._sheetsHyperLinkPopupService.endEditing(HyperLinkEditSourceType.EDITING);
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.VIEWING);
+ }
+ })
+ );
+
+ this.disposeWithMe(
+ this._univerInstanceService.focused$.pipe(
+ mergeMap((id) => {
+ const render = id === DOCS_ZEN_EDITOR_UNIT_ID_KEY ? this._renderManagerService.getRenderById(id) : null;
+ if (render) {
+ return render.with(DocEventManagerService).hoverCustomRanges$.pipe(debounceTime(200));
+ }
+
+ return new Observable<null>((sub) => {
+ sub.next(null);
+ });
+ })
+ ).subscribe((value) => {
+ const range = value?.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);
+ const state = this._editorBridgeService.getEditCellState();
+ if (range && state) {
+ const { unitId, sheetId, row, column } = state;
+ const { editPermission, viewPermission, copyPermission } = this._getLinkPermission({ unitId, subUnitId: sheetId, row, col: column });
+ if (viewPermission) {
+ this._sheetsHyperLinkPopupService.showPopup({
+ type: HyperLinkEditSourceType.ZEN_EDITOR,
+ unitId,
+ subUnitId: sheetId,
+ row,
+ col: column,
+ customRange: range.range,
+ editPermission,
+ copyPermission,
+ });
+ }
+ } else {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.ZEN_EDITOR);
+ }
+ })
+ );
+ }
+
+ private _initTextSelectionListener() {
+ this.disposeWithMe(
+ this._textSelectionManagerService.textSelection$.subscribe((selection) => {
+ if (!selection || selection.unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ this._sheetsHyperLinkPopupService.endEditing(HyperLinkEditSourceType.EDITING);
+ })
+ );
+ }
+
private _initCommandListener() {
const HIDE_COMMAND_LIST = [ClearSelectionContentCommand.id, ClearSelectionAllCommand.id, ClearSelectionFormatCommand.id];
this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
diff --git a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
index 978102783e..320d003bde 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
@@ -15,7 +15,7 @@
*/
import type { Workbook } from '@univerjs/core';
-import { BooleanNumber, Disposable, Inject, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';
+import { Disposable, Inject, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import type { IRenderContext, IRenderModule, Spreadsheet } from '@univerjs/engine-render';
@@ -81,19 +81,12 @@ export class SheetsHyperLinkRenderManagerController extends Disposable {
handler: (cell, pos, next) => {
const { row, col, unitId, subUnitId } = pos;
const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);
- const styleSheet = this._themeService.getCurrentTheme();
if (link) {
return next({
...cell,
- interceptorStyle: {
- ul: {
- s: BooleanNumber.TRUE,
- },
- cl: {
- rgb: styleSheet.blue500,
- },
- },
+ linkUrl: link.payload,
+ linkId: link.id,
});
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts
new file mode 100644
index 0000000000..a9772ff977
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/rich-text-ref-range.controller.ts
@@ -0,0 +1,231 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDisposable, IDocumentData, IRange, Nullable, Workbook } from '@univerjs/core';
+import { CustomRangeType, Disposable, DisposableCollection, ICommandService, Inject, isValidRange, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Tools, UniverInstanceType } from '@univerjs/core';
+import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';
+import type { EffectRefRangeParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import { handleDefaultRangeChangeWithEffectRefCommands, RefRangeService, SetRangeValuesMutation } from '@univerjs/sheets';
+import { ERROR_RANGE } from '@univerjs/sheets-hyper-link';
+
+@OnLifecycle(LifecycleStages.Starting, SheetsHyperLinkRichTextRefRangeController)
+export class SheetsHyperLinkRichTextRefRangeController extends Disposable {
+ private _refRangeMap: Map<string, Map<string, ObjectMatrix<IDisposable>>> = new Map();
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(RefRangeService) private readonly _refRangeService: RefRangeService
+ ) {
+ super();
+ this._initWorkbookLoad();
+ this._initWorkbookUnload();
+ this._initSetRangesListener();
+ }
+
+ private _enusreMap(unitId: string, subUnitId: string) {
+ let unitMap = this._refRangeMap.get(unitId);
+ if (!unitMap) {
+ unitMap = new Map();
+ this._refRangeMap.set(unitId, unitMap);
+ }
+ let subUnitMap = unitMap.get(subUnitId);
+ if (!subUnitMap) {
+ subUnitMap = new ObjectMatrix();
+ unitMap.set(subUnitId, subUnitMap);
+ }
+ return subUnitMap;
+ }
+
+ private _isLegalRangeUrl(unitId: string, payload: string): Nullable<IRange> {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) {
+ return null;
+ }
+ if (payload && payload.startsWith('#')) {
+ const search = new URLSearchParams(payload.slice(1));
+
+ // range, gid, rangeid
+ const searchObj = {
+ gid: search.get('gid') ?? '',
+ range: search.get('range') ?? '',
+ rangeid: search.get('rangeid') ?? '',
+ };
+
+ if (searchObj.range && searchObj.gid) {
+ const subUnitId = searchObj.gid;
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
+ if (!worksheet) {
+ return null;
+ }
+ const range = deserializeRangeWithSheet(searchObj.range).range;
+ if (isValidRange(range, worksheet) && searchObj.range !== ERROR_RANGE) {
+ return range;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private _registerRange(unitId: string, subUnitId: string, row: number, col: number, p: IDocumentData) {
+ const map = this._enusreMap(unitId, subUnitId);
+ const data = Tools.deepClone(p);
+ const handleRangeChange = (commandInfo: EffectRefRangeParams) => {
+ const dataCopy = Tools.deepClone(data);
+ dataCopy.body?.customRanges?.forEach((customRange) => {
+ if (customRange.rangeType === CustomRangeType.HYPERLINK) {
+ const payload = customRange.properties?.url;
+ const range = this._isLegalRangeUrl(unitId, payload);
+ if (range) {
+ const resultRange = handleDefaultRangeChangeWithEffectRefCommands(range, commandInfo);
+ const newPayload = `#gid=${subUnitId}&range=${resultRange ? serializeRange(resultRange) : ERROR_RANGE}`;
+ customRange.properties!.url = newPayload;
+ }
+ }
+ });
+ const position = handleDefaultRangeChangeWithEffectRefCommands({ startRow: row, endRow: row, startColumn: col, endColumn: col }, commandInfo);
+
+ if (!position) {
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+
+ return {
+ redos: [{
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ cellValue: {
+ [position.startRow]: {
+ [position.startColumn]: {
+ p: dataCopy,
+ },
+ },
+ },
+ },
+ }],
+ undos: [
+ {
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ cellValue: {
+ [row]: {
+ [col]: {
+ p: data,
+ },
+ },
+ },
+ },
+ },
+ ],
+ };
+ };
+
+ if (p.body?.customRanges?.some((customRange) => customRange.rangeType === CustomRangeType.HYPERLINK && this._isLegalRangeUrl(unitId, customRange.properties?.url))) {
+ const disposableCollection = new DisposableCollection();
+ p.body?.customRanges?.forEach((customRange) => {
+ if (customRange.rangeType === CustomRangeType.HYPERLINK) {
+ const payload = customRange.properties?.url;
+ const range = this._isLegalRangeUrl(unitId, payload);
+ if (range) {
+ disposableCollection.add(this._refRangeService.registerRefRange(range, handleRangeChange, unitId, subUnitId));
+ }
+ }
+ });
+
+ map.setValue(row, col, disposableCollection);
+ }
+ }
+
+ private _initWorkbookLoad() {
+ const handleWorkbook = (workbook: Workbook) => {
+ const unitId = workbook.getUnitId();
+ workbook.getSheets().forEach((sheet) => {
+ const subUnitId = sheet.getSheetId();
+ const map = this._enusreMap(unitId, subUnitId);
+ sheet.getCellMatrix().forValue((row, col, cell) => {
+ const dispose = map.getValue(row, col);
+ if (dispose) {
+ dispose.dispose();
+ }
+
+ if (cell && cell.p) {
+ this._registerRange(unitId, subUnitId, row, col, cell.p);
+ }
+ });
+ });
+ };
+
+ this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET).forEach((workbook) => {
+ handleWorkbook(workbook);
+ });
+ this.disposeWithMe(
+ this._univerInstanceService.unitAdded$.subscribe((unit) => {
+ if (unit.type === UniverInstanceType.UNIVER_SHEET) {
+ const workbook = unit as Workbook;
+ handleWorkbook(workbook);
+ }
+ })
+ );
+ }
+
+ private _initWorkbookUnload() {
+ this._univerInstanceService.unitDisposed$.subscribe((unit) => {
+ if (unit.type === UniverInstanceType.UNIVER_SHEET) {
+ const workbook = unit as Workbook;
+ const unitId = workbook.getUnitId();
+ workbook.getSheets().forEach((sheet) => {
+ const subUnitId = sheet.getSheetId();
+ const map = this._enusreMap(unitId, subUnitId);
+ map.forValue((row, col, dispose) => {
+ if (dispose) {
+ dispose.dispose();
+ }
+ });
+ });
+ this._refRangeMap.delete(unitId);
+ }
+ });
+ }
+
+ private _initSetRangesListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetRangeValuesMutation.id) {
+ const params = commandInfo.params as ISetRangeValuesMutationParams;
+ const { unitId, subUnitId, cellValue } = params;
+ const map = this._enusreMap(unitId, subUnitId);
+ if (cellValue) {
+ new ObjectMatrix(cellValue).forValue((row, col, cell) => {
+ const dispose = map.getValue(row, col);
+ if (dispose) {
+ dispose.dispose();
+ }
+ if (cell && cell.p) {
+ this._registerRange(unitId, subUnitId, row, col, cell.p);
+ }
+ });
+ }
+ }
+ })
+ );
+ }
+}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
index 595b1b3660..53a71eb3f9 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
@@ -14,137 +14,37 @@
* limitations under the License.
*/
-import { CellValueType, CustomRangeType, Disposable, Inject, Injector, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Tools, UniverInstanceType } from '@univerjs/core';
-import { getPlainTextFormDocument } from '@univerjs/docs-ui';
-import { ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, getSheetCommandTarget, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { BuildTextUtils, CustomRangeType, DataStreamTreeTokenType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, Inject, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, TextX, Tools } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { 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 type { IMutationInfo, Workbook } from '@univerjs/core';
+import { IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { IMutationInfo } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { AddHyperLinkCommand } from '../commands/commands/add-hyper-link.command';
-import { UpdateHyperLinkCommand } from '../commands/commands/update-hyper-link.command';
-import { isLegalLink, serializeUrl } from '../common/util';
-import type { IAddHyperLinkCommandParams } from '../commands/commands/add-hyper-link.command';
-import type { IUpdateHyperLinkCommandParams } from '../commands/commands/update-hyper-link.command';
@OnLifecycle(LifecycleStages.Starting, SheetHyperLinkSetRangeController)
export class SheetHyperLinkSetRangeController extends Disposable {
constructor(
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
- @Inject(Injector) private readonly _injector: Injector,
@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
) {
super();
this._initCommandInterceptor();
+ this._initAfterEditor();
}
private _initCommandInterceptor() {
- this._initAddHyperLinkCommandInterceptor();
this._initSetRangeValuesCommandInterceptor();
- this._initUpdateHyperLinkCommandInterceptor();
this._initClearSelectionCommandInterceptor();
- this._initRichTextEditorInterceptor();
- }
-
- private _getCurrentCell(unitId: string, subUnitId: string, row: number, col: number) {
- return this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)?.getSheetBySheetId(subUnitId)?.getCell(row, col);
- }
-
- private _initAddHyperLinkCommandInterceptor() {
- this.disposeWithMe(this._sheetInterceptorService.interceptCommand({
-
- getMutations: (command) => {
- if (command.id === AddHyperLinkCommand.id) {
- const params = command.params as IAddHyperLinkCommandParams;
- const { unitId, subUnitId, link } = params;
- const currentCell = this._getCurrentCell(unitId, subUnitId, link.row, link.column);
- const redoParams: ISetRangeValuesMutationParams = {
- unitId,
- subUnitId,
- cellValue: {
- [link.row]: {
- [link.column]: {
- v: link.display,
- // t: CellValueType.STRING, // Setting a link to a number is still a number
- p: null,
- t: currentCell?.t ?? undefined, // Keep force string type
- },
- },
- },
- };
-
- return {
- redos: [{
- id: SetRangeValuesMutation.id,
- params: redoParams,
- }],
- undos: [{
- id: SetRangeValuesMutation.id,
- params: SetRangeValuesUndoMutationFactory(this._injector, redoParams),
-
- }],
- };
- }
-
- return {
- redos: [],
- undos: [],
- };
- },
- }));
- }
-
- private _initUpdateHyperLinkCommandInterceptor() {
- this.disposeWithMe(this._sheetInterceptorService.interceptCommand({
- getMutations: (command) => {
- if (command.id === UpdateHyperLinkCommand.id) {
- const params = command.params as IUpdateHyperLinkCommandParams;
- const { unitId, subUnitId, id, payload } = params;
- const current = this._hyperLinkModel.getHyperLink(unitId, subUnitId, id);
- if (current && current.display !== payload.display) {
- const redoParams: ISetRangeValuesMutationParams = {
- unitId,
- subUnitId,
- cellValue: {
- [current.row]: {
- [current.column]: {
- v: payload.display,
- t: CellValueType.STRING,
- p: null,
- },
- },
- },
- };
-
- return {
- redos: [{
- id: SetRangeValuesMutation.id,
- params: redoParams,
- }],
- undos: [{
- id: SetRangeValuesMutation.id,
- params: SetRangeValuesUndoMutationFactory(this._injector, redoParams),
-
- }],
- };
- }
- }
-
- return {
- redos: [],
- undos: [],
- };
- },
- }));
}
private _initSetRangeValuesCommandInterceptor() {
this.disposeWithMe(this._sheetInterceptorService.interceptCommand({
-
getMutations: (command) => {
if (command.id === SetRangeValuesCommand.id) {
const params = command.params as ISetRangeValuesMutationParams;
@@ -152,41 +52,10 @@ export class SheetHyperLinkSetRangeController extends Disposable {
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
if (params.cellValue) {
- new ObjectMatrix(params.cellValue).forValue((row, col, cell) => {
- const cellValueRaw = cell?.v ?? cell?.p?.body?.dataStream.slice(0, -2);
- const cellValue = (cellValueRaw ?? '').toString();
+ new ObjectMatrix(params.cellValue).forValue((row, col) => {
const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);
- if (!link) {
- if (isLegalLink(cellValue) || cell?.custom?.__link_url) {
- const url = cell?.custom?.__link_url ?? cellValue;
- const id = Tools.generateRandomId();
- undos.push({
- id: RemoveHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- id,
- },
- });
- redos.push({
- id: AddHyperLinkMutation.id,
- params: {
- unitId,
- subUnitId,
- link: {
- id,
- row,
- column: col,
- display: cellValue,
- payload: serializeUrl(url),
- },
- },
- });
- }
- return;
- }
-
- if (cellValueRaw === '' || cell?.custom?.__link_url === '') {
+ if (link) {
+ // rich-text can store link in custom-range, don't save to link model
redos.push({
id: RemoveHyperLinkMutation.id,
params: {
@@ -195,6 +64,7 @@ export class SheetHyperLinkSetRangeController extends Disposable {
id: link.id,
},
});
+
undos.push({
id: AddHyperLinkMutation.id,
params: {
@@ -271,33 +141,65 @@ export class SheetHyperLinkSetRangeController extends Disposable {
}));
}
- private _initRichTextEditorInterceptor() {
- this.disposeWithMe(
- this._editorBridgeService.interceptor.intercept(
- this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT,
- {
- handler: (data, context, next) => {
- if (data?.p) {
- const range = data.p.body?.customRanges?.find((i) => i.rangeType === CustomRangeType.HYPERLINK);
- if (range) {
- const url = range.properties?.url;
-
- return next({
- ...data,
- p: null,
- v: getPlainTextFormDocument(data.p),
- t: CellValueType.STRING,
- custom: {
- __link_url: url,
- },
- });
- }
- }
+ private _initAfterEditor() {
+ this.disposeWithMe(this._editorBridgeService.interceptor.intercept(this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT, {
+ handler: (cell, context, next) => {
+ if (!cell || cell.p) {
+ return next(cell);
+ }
- return next(data);
- },
+ if (typeof cell.v === 'string' && Tools.isLegalUrl(cell.v) && cell.v[cell.v.length - 1] !== ' ') {
+ const { unitId, subUnitId } = context;
+ const renderer = this._renderManagerService.getRenderById(unitId);
+ const skeleton = renderer?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
+ if (!skeleton) {
+ return next(cell);
+ }
+ const doc = skeleton.skeleton.getBlankCellDocumentModel(cell);
+ if (!doc.documentModel) {
+ return next(cell);
+ }
+ const textX = BuildTextUtils.selection.replace({
+ selection: {
+ startOffset: 0,
+ endOffset: cell.v.length,
+ collapsed: false,
+ },
+ body: {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${cell.v}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ customRanges: [{
+ startIndex: 0,
+ endIndex: cell.v.length,
+ rangeId: generateRandomId(),
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: cell.v,
+ },
+ }],
+ },
+ doc: doc.documentModel,
+ });
+ if (!textX) {
+ return next(cell);
+ }
+ const body = doc.documentModel.getBody()!;
+ TextX.apply(body, textX.serialize());
+ return next({
+ ...cell,
+ p: {
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body,
+ documentStyle: {
+ pageSize: {
+ width: Infinity,
+ height: Infinity,
+ },
+ },
+ },
+ });
}
- )
- );
+ return next(cell);
+ },
+ }));
}
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts
index 730e093d84..1dd7de6d0b 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts
@@ -19,12 +19,12 @@ import { ComponentManager, IMenuManagerService, IShortcutService } from '@univer
import { LinkSingle } from '@univerjs/icons';
import { CellLinkPopup } from '../views/CellLinkPopup';
import { CellLinkEdit } from '../views/CellLinkEdit';
-import { CloseHyperLinkSidebarOperation, InsertHyperLinkOperation, InsertHyperLinkToolbarOperation, OpenHyperLinkSidebarOperation } from '../commands/operations/sidebar.operations';
-import { AddHyperLinkCommand } from '../commands/commands/add-hyper-link.command';
-import { UpdateHyperLinkCommand } from '../commands/commands/update-hyper-link.command';
-import { CancelHyperLinkCommand, RemoveHyperLinkCommand } from '../commands/commands/remove-hyper-link.command';
-import { InsertLinkShortcut } from './menu';
+import { CloseHyperLinkPopupOperation, InsertHyperLinkOperation, InsertHyperLinkToolbarOperation, OpenHyperLinkEditPanelOperation } from '../commands/operations/popup.operations';
+import { AddHyperLinkCommand, AddRichHyperLinkCommand } from '../commands/commands/add-hyper-link.command';
+import { UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '../commands/commands/update-hyper-link.command';
+import { CancelHyperLinkCommand, CancelRichHyperLinkCommand } from '../commands/commands/remove-hyper-link.command';
import { menuSchema } from './menu.schema';
+import { InsertLinkShortcut } from './menu';
@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkUIController)
export class SheetsHyperLinkUIController extends Disposable {
@@ -55,15 +55,17 @@ export class SheetsHyperLinkUIController extends Disposable {
private _initCommands() {
[
- OpenHyperLinkSidebarOperation,
- CloseHyperLinkSidebarOperation,
+ OpenHyperLinkEditPanelOperation,
+ CloseHyperLinkPopupOperation,
InsertHyperLinkOperation,
InsertHyperLinkToolbarOperation,
AddHyperLinkCommand,
UpdateHyperLinkCommand,
- RemoveHyperLinkCommand,
CancelHyperLinkCommand,
+ UpdateRichHyperLinkCommand,
+ CancelRichHyperLinkCommand,
+ AddRichHyperLinkCommand,
].forEach((command) => {
this._commandService.registerCommand(command);
});
diff --git a/packages/sheets-hyper-link-ui/src/index.ts b/packages/sheets-hyper-link-ui/src/index.ts
index bb3b2c4da5..81a185ca9b 100644
--- a/packages/sheets-hyper-link-ui/src/index.ts
+++ b/packages/sheets-hyper-link-ui/src/index.ts
@@ -14,22 +14,23 @@
* limitations under the License.
*/
-export { SheetsHyperLinkSidePanelService, type ICustomHyperLinkView } from './services/side-panel.service';
-export { SheetsHyperLinkPopupService } from './services/popup.service';
-export { SheetsHyperLinkResolverService } from './services/resolver.service';
-export { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';
-export { UniverSheetsHyperLinkUIPlugin } from './plugin';
-export { InsertLinkShortcut } from './controllers/menu';
-
+export { AddHyperLinkCommand, type IAddHyperLinkCommandParams } from './commands/commands/add-hyper-link.command';
+export { CancelHyperLinkCommand, type ICancelHyperLinkCommandParams } from './commands/commands/remove-hyper-link.command';
+export { type IUpdateHyperLinkCommandParams, UpdateHyperLinkCommand } from './commands/commands/update-hyper-link.command';
// #region - all commands
export {
- OpenHyperLinkSidebarOperation,
+ CloseHyperLinkPopupOperation,
InsertHyperLinkOperation,
- CloseHyperLinkSidebarOperation,
- type IOpenHyperLinkSidebarOperationParams,
-} from './commands/operations/sidebar.operations';
+ type IOpenHyperLinkEditPanelOperationParams,
+ OpenHyperLinkEditPanelOperation,
+} from './commands/operations/popup.operations';
+export { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';
+export { InsertLinkShortcut } from './controllers/menu';
+export { UniverSheetsHyperLinkUIPlugin } from './plugin';
-export { AddHyperLinkCommand, type IAddHyperLinkCommandParams } from './commands/commands/add-hyper-link.command';
-export { RemoveHyperLinkCommand, CancelHyperLinkCommand, type IRemoveHyperLinkCommandParams } from './commands/commands/remove-hyper-link.command';
-export { UpdateHyperLinkCommand, type IUpdateHyperLinkCommandParams } from './commands/commands/update-hyper-link.command';
+export { SheetsHyperLinkPopupService } from './services/popup.service';
+
+export { SheetsHyperLinkResolverService } from './services/resolver.service';
+export { type ICustomHyperLinkView, SheetsHyperLinkSidePanelService } from './services/side-panel.service';
+export type { ISheetHyperLinkInfo, ISheetUrlParams } from './types/interfaces';
// #endregion
diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.ts
index e46126f240..0e6aa12eaa 100644
--- a/packages/sheets-hyper-link-ui/src/plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/plugin.ts
@@ -18,6 +18,7 @@ import type { Dependency } from '@univerjs/core';
import { DependentOn, IConfigService, Inject, Injector, Plugin, UniverInstanceType } from '@univerjs/core';
import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';
import { SheetsHyperLinkRenderController, SheetsHyperLinkRenderManagerController } from './controllers/render-controllers/render.controller';
import { SheetsHyperLinkPopupService } from './services/popup.service';
@@ -33,8 +34,9 @@ import { SheetsHyperLinkPermissionController } from './controllers/hyper-link-pe
import { SheetsHyperLinkSidePanelService } from './services/side-panel.service';
import type { IUniverSheetsHyperLinkUIConfig } from './controllers/config.schema';
import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
+import { SheetsHyperLinkRichTextRefRangeController } from './controllers/rich-text-ref-range.controller';
-@DependentOn(UniverSheetsHyperLinkPlugin)
+@DependentOn(UniverSheetsHyperLinkPlugin, UniverDocsUIPlugin)
export class UniverSheetsHyperLinkUIPlugin extends Plugin {
static override pluginName: string = SHEET_HYPER_LINK_UI_PLUGIN;
static override type = UniverInstanceType.UNIVER_SHEET;
@@ -70,6 +72,7 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
[SheetsHyperLinkCopyPasteController],
[SheetsHyperLinkPermissionController],
[SheetHyperLinkUrlController],
+ [SheetsHyperLinkRichTextRefRangeController],
];
dependencies.forEach((dep) => this._injector.add(dep));
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 e3575f01e2..036d10aab9 100644
--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
@@ -15,41 +15,66 @@
*/
import type { ISheetLocationBase } from '@univerjs/sheets';
-import { HyperLinkModel } from '@univerjs/sheets-hyper-link';
-import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
-import type { IDisposable } from '@univerjs/core';
-import { Disposable, Inject } from '@univerjs/core';
+import type { ICanvasPopup } from '@univerjs/sheets-ui';
+import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
+import type { DocumentDataModel, ICustomRange, IDisposable, INeedCheckDisposable, ITextRange, Nullable, Workbook } from '@univerjs/core';
+import { BuildTextUtils, createInternalEditorID, CustomRangeType, Disposable, DOCS_ZEN_EDITOR_UNIT_ID_KEY, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { BehaviorSubject, Subject } from 'rxjs';
+import type { IBoundRectNoAngle } from '@univerjs/engine-render';
+import { DocCanvasPopManagerService, getPlainText, getPlainTextFormBody, getPlainTextFormDocument } from '@univerjs/docs-ui';
+import { IEditorService, IRangeSelectorService, IZenZoneService } from '@univerjs/ui';
+import { DocSelectionManagerService } from '@univerjs/docs';
import { CellLinkPopup } from '../views/CellLinkPopup';
+import { CellLinkEdit } from '../views/CellLinkEdit';
+import { HyperLinkEditSourceType } from '../types/enums/edit-source';
export interface IHyperLinkPopup {
unitId: string;
subUnitId: string;
- id: string;
- disposable?: IDisposable;
+ disposable: INeedCheckDisposable;
row: number;
col: number;
- editPermission: boolean;
- copyPermission: boolean;
+ editPermission?: boolean;
+ copyPermission?: boolean;
+ customRange?: ICustomRange;
+ type: HyperLinkEditSourceType;
}
interface IHyperLinkEditing {
unitId: string;
subUnitId: string;
row: number;
- column: number;
+ col: number;
+ customRangeId?: string;
+ type: HyperLinkEditSourceType;
}
-const isEqualLink = (a: ISheetLocationBase, b: ISheetLocationBase) => {
- return a.unitId === b.unitId && a.subUnitId === b.subUnitId && a.row === b.row && a.col === b.col;
+const isEqualLink = (a: IHyperLinkPopupOptions, b: Omit<IHyperLinkPopup, 'disposable' | 'editPermission'>) => {
+ return (
+ a.unitId === b.unitId
+ && a.subUnitId === b.subUnitId
+ && a.row === b.row
+ && a.col === b.col
+ && a.customRange?.rangeId === b.customRange?.rangeId
+ && a.type === b.type
+ );
};
+interface IHyperLinkPopupOptions extends ISheetLocationBase {
+ editPermission?: boolean;
+ copyPermission?: boolean;
+ customRange?: Nullable<ICustomRange>;
+ customRangeRect?: Nullable<IBoundRectNoAngle>;
+ type: HyperLinkEditSourceType;
+}
+
export class SheetsHyperLinkPopupService extends Disposable {
private _currentPopup: IHyperLinkPopup | null = null;
private _currentPopup$ = new Subject<IHyperLinkPopup | null>();
currentPopup$ = this._currentPopup$.asObservable();
+ private _currentEditingPopup: Nullable<IDisposable> = null;
- private _currentEditing$ = new BehaviorSubject<IHyperLinkEditing | null>(null);
+ private _currentEditing$ = new BehaviorSubject<(IHyperLinkEditing & { customRange?: ICustomRange; label?: string }) | null>(null);
currentEditing$ = this._currentEditing$.asObservable();
get currentPopup() {
@@ -61,8 +86,15 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
constructor(
- @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
- @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService
+ @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
+ @Inject(DocCanvasPopManagerService) private readonly _docCanvasPopManagerService: DocCanvasPopManagerService,
+ @IEditorService private readonly _editorService: IEditorService,
+ @IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService,
+ @IZenZoneService private readonly _zenZoneService: IZenZoneService
) {
super();
@@ -75,55 +107,270 @@ export class SheetsHyperLinkPopupService extends Disposable {
});
}
- showPopup(location: ISheetLocationBase & { editPermission?: boolean; copyPermission?: boolean }) {
+ showPopup(location: IHyperLinkPopupOptions) {
if (this._currentPopup && isEqualLink(location, this._currentPopup)) {
return;
}
- this.hideCurrentPopup();
- const { unitId, subUnitId, row, col } = location;
-
- const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);
- if (!link) {
+ this.hideCurrentPopup(undefined, true);
+ if (location.type !== HyperLinkEditSourceType.ZEN_EDITOR && this._zenZoneService.visible) {
+ return;
+ }
+ const currentEditing = this._currentEditing$.getValue();
+ if (currentEditing && isEqualLink(location, currentEditing)) {
return;
}
- const disposable = this._sheetCanvasPopManagerService.attachPopupToCell(row, col, {
+ const { unitId, subUnitId, row, col, customRangeRect, customRange } = location;
+ if (!customRange) {
+ return;
+ }
+ let disposable: Nullable<INeedCheckDisposable>;
+ const popup: ICanvasPopup = {
componentKey: CellLinkPopup.componentKey,
direction: 'bottom',
- closeOnSelfTarget: true,
onClickOutside: () => {
this.hideCurrentPopup();
},
- });
+ onClick: () => {
+ this.hideCurrentPopup(location.type, true);
+ },
+ };
+ if (location.type === HyperLinkEditSourceType.EDITING) {
+ disposable = customRangeRect && this._sheetCanvasPopManagerService.attachPopupToAbsolutePosition(
+ customRangeRect,
+ popup
+ );
+ } else if (location.type === HyperLinkEditSourceType.ZEN_EDITOR) {
+ disposable = this._docCanvasPopManagerService.attachPopupToRange(
+ {
+ startOffset: customRange.startIndex,
+ endOffset: customRange.endIndex + 1,
+ collapsed: false,
+ },
+ popup,
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ );
+ } else {
+ disposable = customRangeRect && this._sheetCanvasPopManagerService.attachPopupByPosition(
+ customRangeRect,
+ popup
+ );
+ }
+
if (disposable) {
this._currentPopup = {
unitId,
subUnitId,
- id: link.id,
disposable,
row,
col,
editPermission: !!location.editPermission,
copyPermission: !!location.copyPermission,
+ customRange,
+ type: location.type,
};
this._currentPopup$.next(this._currentPopup);
}
}
- hideCurrentPopup() {
- if (this._currentPopup) {
- this._currentPopup.disposable?.dispose();
+ hideCurrentPopup(type?: HyperLinkEditSourceType, force?: boolean) {
+ if (!this._currentPopup) {
+ return;
+ }
+
+ if (((!type || type === this._currentPopup.type) && this._currentPopup.disposable.canDispose()) || force) {
+ this._currentPopup?.disposable?.dispose();
this._currentPopup = null;
this._currentPopup$.next(null);
}
}
- startEditing(link: IHyperLinkEditing) {
- this._currentEditing$.next(link);
+ private _getEditingRange(): Nullable<ITextRange & { label: string }> {
+ const visible = this._editorBridgeService.isVisible().visible;
+ const state = this._editorBridgeService.getEditCellState();
+ if (visible && state) {
+ const textRange = this._textSelectionManagerService.getActiveTextRange();
+ const body = state.documentLayoutObject.documentModel?.getBody();
+ if (!body) {
+ return null;
+ }
+ if (!textRange || textRange.collapsed) {
+ return {
+ startOffset: 0,
+ endOffset: body.dataStream.length - 2,
+ collapsed: body.dataStream.length - 2 === 0,
+ label: getPlainTextFormBody(body),
+ };
+ }
+ const links = BuildTextUtils.customRange.getCustomRangesInterestsWithRange(textRange, body.customRanges?.filter((i) => i.rangeType === CustomRangeType.HYPERLINK) ?? []);
+ let start = textRange.startOffset;
+ let end = textRange.endOffset;
+ links.forEach((link) => {
+ start = Math.min(start, link.startIndex);
+ end = Math.max(end, link.endIndex + 1);
+ });
+ return {
+ startOffset: start,
+ endOffset: end,
+ collapsed: start === end,
+ label: getPlainText(body.dataStream.slice(start, end)),
+ };
+ }
+
+ return null;
+ }
+
+ private get _editPopup() {
+ const popup: ICanvasPopup = {
+ componentKey: CellLinkEdit.componentKey,
+ direction: 'bottom',
+ onClickOutside: () => {
+ const hyperLinkRangeSelectorId = createInternalEditorID('hyper-link-edit');
+ if (this._editorService.getFocusId() === hyperLinkRangeSelectorId) {
+ return;
+ }
+ if (this._rangeSelectorService.getCurrentSelectorId() === hyperLinkRangeSelectorId && this._rangeSelectorService.selectorModalVisible) {
+ return;
+ }
+ this.endEditing();
+ },
+ hiddenType: 'hide',
+ };
+ return popup;
}
- endEditing() {
- this._currentEditing$.next(null);
+ startAddEditing(link: IHyperLinkEditing) {
+ const { unitId, subUnitId, type } = link;
+ if (type === HyperLinkEditSourceType.ZEN_EDITOR) {
+ const document: Nullable<DocumentDataModel> = this._univerInstanceService.getUnit(DOCS_ZEN_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);
+ if (!document) {
+ return;
+ }
+ const range = this._textSelectionManagerService.getActiveTextRange();
+ if (!range) {
+ return;
+ }
+ this._currentEditingPopup = this._docCanvasPopManagerService.attachPopupToRange(
+ range,
+ this._editPopup,
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ );
+ const label = document.getBody()?.dataStream.slice(range.startOffset, range.endOffset - 1);
+ this._currentEditing$.next({
+ ...link,
+ label,
+ });
+ } else if (type === HyperLinkEditSourceType.EDITING) {
+ const range = this._getEditingRange();
+
+ if (range) {
+ this._textSelectionManagerService.replaceTextRanges([{ ...range }]);
+ }
+
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(
+ link.row,
+ link.col,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
+ this._currentEditing$.next({
+ ...link,
+ label: range?.label ?? '',
+ });
+ } else {
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(
+ link.row,
+ link.col,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ const cell = worksheet?.getCellRaw(link.row, link.col);
+ this._currentEditing$.next({
+ ...link,
+ label: cell?.p ? getPlainTextFormDocument(cell.p) : (cell?.v ?? '').toString(),
+ });
+ }
+ }
+
+ startEditing(link: Required<IHyperLinkEditing>) {
+ this._currentEditingPopup?.dispose();
+ this.hideCurrentPopup(undefined, true);
+
+ const { unitId, subUnitId } = link;
+ let customRange;
+ let label;
+ 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) : '';
+ if (!customRange || !label) {
+ return;
+ }
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: customRange.startIndex,
+ endOffset: customRange.endIndex + 1,
+ },
+ ]);
+ this._currentEditingPopup = this._docCanvasPopManagerService.attachPopupToRange(
+ {
+ startOffset: customRange.startIndex,
+ endOffset: customRange.endIndex,
+ collapsed: false,
+ },
+ this._editPopup,
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ );
+ } else if (link.type === HyperLinkEditSourceType.EDITING) {
+ const customRangeInfo = getEditingCustomRangePosition(this._injector, link.unitId, link.subUnitId, link.row, link.col, link.customRangeId);
+ if (!customRangeInfo || !customRangeInfo.rects?.length) {
+ return;
+ }
+ customRange = customRangeInfo.customRange;
+ label = customRangeInfo.label;
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: customRange.startIndex,
+ endOffset: customRange.endIndex + 1,
+ },
+ ]);
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToAbsolutePosition(
+ customRangeInfo.rects.pop()!,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
+ } else {
+ const customRangeInfo = getCustomRangePosition(this._injector, link.unitId, link.subUnitId, link.row, link.col, link.customRangeId);
+ if (!customRangeInfo || !customRangeInfo.rects?.length) {
+ return;
+ }
+ customRange = customRangeInfo.customRange;
+ label = customRangeInfo.label;
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupByPosition(
+ customRangeInfo.rects.pop()!,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
+ }
+ this._currentEditing$.next({
+ ...link,
+ customRange,
+ label,
+ });
+ }
+
+ endEditing(type?: HyperLinkEditSourceType) {
+ const current = this._currentEditing$.getValue();
+ if (current && (!type || type === current.type)) {
+ this._currentEditingPopup?.dispose();
+ this._currentEditing$.next(null);
+ }
}
}
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 d51a57ffa2..b811b58a30 100644
--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
@@ -14,23 +14,19 @@
* limitations under the License.
*/
-import type { IRange, Workbook, Worksheet } from '@univerjs/core';
import { ICommandService, IConfigService, Inject, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
-import { deserializeRangeWithSheet, IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';
-import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
-import { ERROR_RANGE } from '@univerjs/sheets-hyper-link';
+import { ERROR_RANGE, SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
import { IMessageService } from '@univerjs/ui';
-import type { IUniverSheetsHyperLinkUIConfig } from '../controllers/config.schema';
+import type { IRange, Workbook, Worksheet } from '@univerjs/core';
+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
import { PLUGIN_CONFIG_KEY } from '../controllers/config.schema';
-
-interface ISheetUrlParams {
- gid?: string;
- range?: string;
- rangeid?: string;
-}
+import type { IUniverSheetsHyperLinkUIConfig } from '../controllers/config.schema';
+import type { ISheetHyperLinkInfo } from '../types/interfaces/i-sheet-hyper-link-info';
+import type { ISheetUrlParams } from '../types/interfaces/i-sheet-url-params';
function getContainRange(range: IRange, worksheet: Worksheet) {
const mergedCells = worksheet.getMergeData();
@@ -58,13 +54,6 @@ function getContainRange(range: IRange, worksheet: Worksheet) {
return Rectangle.realUnion(range, ...relativeCells);
}
-export interface IHyperLinkInfo<T extends string> {
- type: T;
- name: string;
- url: string;
- handler: () => void;
-}
-
export class SheetsHyperLinkResolverService {
constructor(
@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,
@@ -76,61 +65,57 @@ export class SheetsHyperLinkResolverService {
) { }
private _getURLName(params: ISheetUrlParams) {
- const { gid, range, rangeid } = params;
- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const { gid, range, rangeid, unitid } = params;
+ const workbook = unitid ?
+ this._univerInstanceService.getUnit<Workbook>(unitid, UniverInstanceType.UNIVER_SHEET)
+ : this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const invalidLink = {
+ type: SheetHyperLinkType.INVALID,
+ name: this._localeService.t('hyperLink.message.refError'),
+ };
+
if (!workbook) {
- return null;
+ return invalidLink;
}
const sheet = gid ? workbook.getSheetBySheetId(gid) : workbook.getActiveSheet();
const sheetName = sheet?.getName() ?? '';
if (range) {
+ if (!sheet) return invalidLink;
const rangeObj = deserializeRangeWithSheet(range).range;
- if (isValidRange(rangeObj) && range !== ERROR_RANGE) {
+ if (isValidRange(rangeObj, sheet) && range !== ERROR_RANGE) {
return {
- type: 'range',
+ type: SheetHyperLinkType.RANGE,
name: serializeRangeWithSheet(sheetName, rangeObj),
- } as const;
- } else {
- return {
- type: 'range-error',
- name: this._localeService.t('hyperLink.message.refError'),
- } as const;
+ };
}
+ return invalidLink;
}
if (rangeid) {
const range = this._definedNamesService.getValueById(workbook.getUnitId(), rangeid);
if (range) {
return {
- type: 'defineName',
+ type: SheetHyperLinkType.DEFINE_NAME,
name: range.formulaOrRefString,
- } as const;
- } else {
- return {
- type: 'range-error',
- name: this._localeService.t('hyperLink.message.refError'),
- } as const;
+ };
}
+ return invalidLink;
}
if (gid) {
const worksheet = workbook.getSheetBySheetId(gid);
if (worksheet) {
return {
- type: 'sheet',
+ type: SheetHyperLinkType.SHEET,
name: worksheet.getName(),
- } as const;
- } else {
- return {
- type: 'sheet-error',
- name: this._localeService.t('hyperLink.message.refError'),
- } as const;
+ };
}
+ return invalidLink;
}
- return null;
+ return invalidLink;
}
navigateTo(params: ISheetUrlParams) {
@@ -159,34 +144,41 @@ export class SheetsHyperLinkResolverService {
this.navigateToSheetById(unitId, gid);
}
- parseHyperLink(urlStr: string) {
- if (urlStr?.startsWith('#')) {
+ buildHyperLink(unitId: string, sheetId: string, range?: string | IRange): string {
+ return `#${SheetHyperLinkType.SHEET}=${sheetId}}${range ? `${typeof range === 'string' ? SheetHyperLinkType.DEFINE_NAME : SheetHyperLinkType.RANGE}=${typeof range === 'string' ? range : serializeRange(range)}` : ''}`;
+ }
+
+ parseHyperLink(urlStr: string): ISheetHyperLinkInfo {
+ if (urlStr.startsWith('#')) {
const search = new URLSearchParams(urlStr.slice(1));
// range, gid, rangeid
const searchObj: ISheetUrlParams = {
gid: search.get('gid') ?? '',
range: search.get('range') ?? '',
rangeid: search.get('rangeid') ?? '',
+ unitid: search.get('unitid') ?? '',
};
const urlInfo = this._getURLName(searchObj);
+
return {
- type: urlInfo?.type || 'link',
- name: urlInfo?.name || urlStr,
+ type: urlInfo.type,
+ name: urlInfo.name,
url: urlStr,
searchObj,
handler: () => {
this.navigateTo(searchObj);
},
- } as const;
+ };
} else {
return {
- type: 'outer',
+ type: SheetHyperLinkType.URL,
name: urlStr,
url: urlStr,
handler: () => {
this.navigateToOtherWebsite(urlStr);
},
- } as const;
+ searchObj: null,
+ };
}
}
diff --git a/packages/sheets-hyper-link-ui/src/services/side-panel.service.ts b/packages/sheets-hyper-link-ui/src/services/side-panel.service.ts
index 74a64a583e..316352e79b 100644
--- a/packages/sheets-hyper-link-ui/src/services/side-panel.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/side-panel.service.ts
@@ -16,9 +16,10 @@
import { Disposable } from '@univerjs/core';
import type { ICellHyperLink } from '@univerjs/sheets-hyper-link';
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
import type React from 'react';
-export interface CustomHyperLinkFormProps {
+export interface ICustomHyperLinkFormProps {
linkId: string;
payload: string;
display: string;
@@ -34,23 +35,16 @@ export interface ICustomHyperLinkView {
label: string;
value: string;
};
- Form: React.FC<CustomHyperLinkFormProps>;
+ Form: React.FC<ICustomHyperLinkFormProps>;
convert: (link: ICellHyperLink) => { display: string; payload: string; type: string };
match: (link: ICellHyperLink) => boolean;
}
-export enum LinkType {
- link = 'link',
- range = 'range',
- sheet = 'gid',
- definedName = 'rangeid',
-}
-
export class SheetsHyperLinkSidePanelService extends Disposable {
private _customHyperLinks = new Map<string, ICustomHyperLinkView>();
- isBuiltInLinkType(type: string) {
- return Boolean((LinkType as any)[type]);
+ isBuiltInLinkType(type: SheetHyperLinkType | string) {
+ return type !== SheetHyperLinkType.URL;
}
getOptions() {
diff --git a/packages/sheets-hyper-link-ui/src/types/enums/edit-source.ts b/packages/sheets-hyper-link-ui/src/types/enums/edit-source.ts
new file mode 100644
index 0000000000..4246f55914
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/types/enums/edit-source.ts
@@ -0,0 +1,21 @@
+/**
+ * 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 enum HyperLinkEditSourceType {
+ EDITING = 'editing',
+ VIEWING = 'viewing',
+ ZEN_EDITOR = 'zen_mode',
+}
diff --git a/packages/sheets-hyper-link-ui/src/types/enums/index.ts b/packages/sheets-hyper-link-ui/src/types/enums/index.ts
new file mode 100644
index 0000000000..f1245e7089
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/types/enums/index.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 { HyperLinkEditSourceType } from './edit-source';
diff --git a/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-hyper-link-info.ts b/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-hyper-link-info.ts
new file mode 100644
index 0000000000..0fa5ba4357
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-hyper-link-info.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+import type { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
+import type { ISheetUrlParams } from './i-sheet-url-params';
+
+export interface ISheetHyperLinkInfo {
+ type: SheetHyperLinkType;
+ name: string;
+ url: string;
+ searchObj: Nullable<ISheetUrlParams>;
+ handler: () => void;
+}
diff --git a/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-url-params.ts b/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-url-params.ts
new file mode 100644
index 0000000000..0454b9e4bd
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/types/interfaces/i-sheet-url-params.ts
@@ -0,0 +1,22 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export interface ISheetUrlParams {
+ gid?: string;
+ range?: string;
+ rangeid?: string;
+ unitid?: string;
+}
diff --git a/packages/sheets-hyper-link-ui/src/types/interfaces/index.ts b/packages/sheets-hyper-link-ui/src/types/interfaces/index.ts
new file mode 100644
index 0000000000..b5fa96c68c
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/types/interfaces/index.ts
@@ -0,0 +1,18 @@
+/**
+ * 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 type { ISheetHyperLinkInfo } from './i-sheet-hyper-link-info';
+export type { ISheetUrlParams } from './i-sheet-url-params';
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less
index a18b5b4038..554f9245c2 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less
@@ -1,3 +1,14 @@
+.cell-link-edit {
+ padding: 16px;
+ background-color: rgb(var(--color-white));
+ box-sizing: border-box;
+ width: 296px;
+ box-sizing: border-box;
+ border-radius: var(--border-radius-xl);
+ border: 1px solid rgb(var(--grey-200));
+ box-shadow: 0px 4px 10px -1px rgba(17, 22, 40, 0.1);
+}
+
.cell-link-edit-buttons {
display: flex;
flex-direction: row;
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 5a56f346e9..1672f8feae 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -14,149 +14,215 @@
* limitations under the License.
*/
-import React, { useEffect, useMemo, useRef, useState } from 'react';
+import { BuildTextUtils, createInternalEditorID, CustomRangeType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
import { Button, FormLayout, Input, Select } from '@univerjs/design';
-import { createInternalEditorID, ICommandService, isValidRange, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
-import type { IUnitRangeWithName, Workbook } from '@univerjs/core';
-import { RangeSelector, useEvent, useObservable } from '@univerjs/ui';
+import { DocSelectionManagerService } from '@univerjs/docs';
import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeToRefString, serializeRangeWithSheet } from '@univerjs/engine-formula';
-import { ERROR_RANGE, HyperLinkModel } from '@univerjs/sheets-hyper-link';
-import { SetWorksheetActiveOperation } from '@univerjs/sheets';
-import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
+import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { IZenZoneService, RangeSelector, useEvent, useObservable } from '@univerjs/ui';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
+import type { DocumentDataModel, IUnitRangeWithName, Nullable, Workbook } from '@univerjs/core';
+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { AddHyperLinkCommand, AddRichHyperLinkCommand } from '../../commands/commands/add-hyper-link.command';
+import { UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '../../commands/commands/update-hyper-link.command';
+import { CloseHyperLinkPopupOperation } from '../../commands/operations/popup.operations';
+import { getCellValueOrigin, isLegalLink, serializeUrl } from '../../common/util';
import { SheetsHyperLinkPopupService } from '../../services/popup.service';
import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
-import { CloseHyperLinkSidebarOperation } from '../../commands/operations/sidebar.operations';
-import { getCellValueOrigin, isLegalLink, serializeUrl } from '../../common/util';
-import { LinkType, SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
-import { AddHyperLinkCommand } from '../../commands/commands/add-hyper-link.command';
-import { UpdateHyperLinkCommand } from '../../commands/commands/update-hyper-link.command';
+import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
import styles from './index.module.less';
export const CellLinkEdit = () => {
const [id, setId] = useState('');
+ const [hide, setHide] = useState(false);
const [display, setDisplay] = useState('');
- const [type, setType] = useState<LinkType | string>(LinkType.link);
+ const [showLabel, setShowLabel] = useState(true);
+ const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
const [payload, setPayload] = useState('');
const localeService = useDependency(LocaleService);
const definedNameService = useDependency(IDefinedNamesService);
+ const editorBridgeService = useDependency(IEditorBridgeService);
const univerInstanceService = useDependency(IUniverInstanceService);
const popupService = useDependency(SheetsHyperLinkPopupService);
const editing = useObservable(popupService.currentEditing$);
- const hyperLinkModel = useDependency(HyperLinkModel);
const resolverService = useDependency(SheetsHyperLinkResolverService);
const commandService = useDependency(ICommandService);
const sidePanelService = useDependency(SheetsHyperLinkSidePanelService);
const sidePanelOptions = useMemo(() => sidePanelService.getOptions(), [sidePanelService]);
+ const zenZoneService = useDependency(IZenZoneService);
+ const markSelectionService = useDependency(IMarkSelectionService);
+ const textSelectionService = useDependency(DocSelectionManagerService);
+ const contextService = useDependency(IContextService);
const customHyperLinkSidePanel = useMemo(() => {
if (sidePanelService.isBuiltInLinkType(type)) {
return;
}
return sidePanelService.getCustomHyperLink(type);
}, [sidePanelService, type]);
+
const [showError, setShowError] = useState(false);
const setByPayload = useRef(false);
useEffect(() => {
- if (editing?.row !== undefined && editing.column !== undefined) {
- const link = hyperLinkModel.getHyperLinkByLocationSync(editing.unitId, editing.subUnitId, editing.row, editing.column);
+ if (editing?.row !== undefined && editing.col !== undefined) {
+ const { label, customRange, row, col } = editing;
+ let link;
+ if (customRange) {
+ link = {
+ id: customRange?.rangeId ?? '',
+ display: label ?? '',
+ payload: customRange?.properties?.url ?? '',
+ row,
+ column: col,
+ };
+ } else {
+ if (editing.type === HyperLinkEditSourceType.VIEWING) {
+ const workbook = univerInstanceService.getUnit<Workbook>(editing.unitId);
+ const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);
+ const cell = worksheet?.getCellRaw(editing.row, editing.col);
+ const range = cell?.p?.body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK && range.properties?.url);
+ const cellValue = `${getCellValueOrigin(cell) ?? ''}`;
+ if (cell && (cell.p || cellValue)) {
+ setShowLabel(false);
+ }
+ link = {
+ id: '',
+ display: '',
+ payload: range?.properties?.url ?? '',
+ row,
+ column: col,
+ };
+ } else {
+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = textSelectionService.getActiveTextRange();
+ const customRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithRange(selection, doc?.getBody()?.customRanges ?? [])?.[0];
- if (link) {
- setId(link.id);
- const customLink = sidePanelService.findCustomHyperLink(link);
- if (customLink) {
- const customLinkInfo = customLink.convert(link);
- setType(customLinkInfo.type);
- setPayload(customLinkInfo.payload);
- setDisplay(customLinkInfo.display);
- return;
+ setShowLabel(false);
+ link = {
+ id: '',
+ display: label ?? '',
+ payload: customRange?.properties?.url ?? '',
+ row,
+ column: col,
+ };
}
- setDisplay(link.display);
- const linkInfo = resolverService.parseHyperLink(link.payload);
- if (linkInfo.type === 'outer') {
- setType(LinkType.link);
+ }
+
+ setId(link.id);
+ const customLink = sidePanelService.findCustomHyperLink(link);
+ if (customLink) {
+ const customLinkInfo = customLink.convert(link);
+ setType(customLinkInfo.type);
+ setPayload(customLinkInfo.payload);
+ setDisplay(customLinkInfo.display);
+ return;
+ }
+ setDisplay(link.display);
+ const linkInfo = resolverService.parseHyperLink(link.payload);
+ setType(linkInfo.type === SheetHyperLinkType.INVALID ? SheetHyperLinkType.RANGE : linkInfo.type);
+ switch (linkInfo.type) {
+ case SheetHyperLinkType.URL:{
setPayload(linkInfo.url);
if (linkInfo.url === link.display) {
setByPayload.current = true;
}
- return;
- } else {
- const params = linkInfo.searchObj;
- if (params.rangeid) {
- setType(LinkType.definedName);
- setPayload(params.rangeid);
-
- return;
- }
-
- if (params.range) {
- const sheetName = params.gid ?
- univerInstanceService
- .getUnit<Workbook>(editing.unitId)
- ?.getSheetBySheetId(params.gid)
- ?.getName()
+ break;
+ }
+ case SheetHyperLinkType.RANGE:{
+ const params = linkInfo.searchObj!;
+ const sheetName = params.gid ?
+ univerInstanceService
+ .getUnit<Workbook>(editing.unitId)
+ ?.getSheetBySheetId(params.gid)
+ ?.getName()
?? ''
- : '';
- setType(LinkType.range);
- if (params.range === ERROR_RANGE) {
- setPayload('');
- } else {
- const payload = (serializeRangeWithSheet(sheetName, deserializeRangeWithSheet(params.range).range));
- setPayload(payload);
- if (payload === link.display) {
- setByPayload.current = true;
- }
- }
-
- return;
- }
-
- if (params.gid) {
- setType(LinkType.sheet);
- setPayload(params.gid);
- return;
+ : '';
+ const payload = (serializeRangeWithSheet(sheetName, deserializeRangeWithSheet(params.range!).range));
+ setPayload(payload);
+ if (payload === link.display) {
+ setByPayload.current = true;
}
+ break;
+ }
+ case SheetHyperLinkType.SHEET:{
+ const params = linkInfo.searchObj!;
+ setPayload(params.gid!);
+ break;
}
+ case SheetHyperLinkType.DEFINE_NAME:{
+ const params = linkInfo.searchObj!;
+ setPayload(params.rangeid!);
+ break;
+ }
+ default:
+ setPayload('');
+ break;
}
- const workbook = univerInstanceService.getUnit<Workbook>(editing.unitId);
- const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);
- const cell = worksheet?.getCellRaw(editing.row, editing.column);
-
- const cellValue = getCellValueOrigin(cell);
- setType(LinkType.link);
- setPayload('');
- setDisplay((cellValue ?? '').toString());
- setId('');
- return;
}
+ }, [editing, resolverService, sidePanelService, textSelectionService, univerInstanceService]);
- setType(LinkType.link);
- setPayload('');
- setDisplay('');
- setId('');
- }, [editing, hyperLinkModel, resolverService, univerInstanceService]);
+ useEffect(() => {
+ let id: Nullable<string> = null;
+ if (editing && editing.type === HyperLinkEditSourceType.VIEWING && Tools.isDefine(editing.row) && Tools.isDefine(editing.col)) {
+ id = markSelectionService.addShape(
+ {
+ range: {
+ startColumn: editing.col,
+ endColumn: editing.col,
+ startRow: editing.row,
+ endRow: editing.row,
+ },
+ style: {
+ hasAutoFill: false,
+ fill: 'rgb(255, 189, 55, 0.35)',
+ strokeWidth: 1,
+ stroke: '#FFBD37',
+ widgets: {},
+ },
+ primary: null,
+ },
+ [],
+ -1
+ );
+ }
+ return () => {
+ if (id) {
+ markSelectionService.removeShape(id);
+ }
+ };
+ }, [editing, markSelectionService]);
const payloadInitial = useMemo(() => payload, [type]);
+ useEffect(() => {
+ return () => {
+ editorBridgeService.disableForceKeepVisible();
+ };
+ }, [editorBridgeService]);
+
const linkTypeOptions: Array<{
label: string;
- value: LinkType | string;
+ value: SheetHyperLinkType | string;
}> = [
{
label: localeService.t('hyperLink.form.link'),
- value: LinkType.link,
+ value: SheetHyperLinkType.URL,
},
{
label: localeService.t('hyperLink.form.range'),
- value: LinkType.range,
+ value: SheetHyperLinkType.RANGE,
},
{
label: localeService.t('hyperLink.form.worksheet'),
- value: LinkType.sheet,
+ value: SheetHyperLinkType.SHEET,
},
{
label: localeService.t('hyperLink.form.definedName'),
- value: LinkType.definedName,
+ value: SheetHyperLinkType.DEFINE_NAME,
},
...sidePanelOptions,
];
@@ -172,12 +238,12 @@ export const CellLinkEdit = () => {
value: value.id,
}));
- const formatUrl = (type: LinkType | string, payload: string) => {
- if (type === LinkType.link) {
+ const formatUrl = (type: SheetHyperLinkType | string, payload: string) => {
+ if (type === SheetHyperLinkType.URL) {
return serializeUrl(payload);
}
- if (type === LinkType.range) {
+ if (type === SheetHyperLinkType.RANGE) {
const info = deserializeRangeWithSheet(payload);
const worksheet = workbook.getSheetBySheetName(info.sheetName);
if (worksheet) {
@@ -208,30 +274,40 @@ export const CellLinkEdit = () => {
const handleSubmit = async () => {
if (editing) {
if (id) {
- await commandService.executeCommand(UpdateHyperLinkCommand.id, {
+ const commandId = (editing.type === HyperLinkEditSourceType.ZEN_EDITOR || editing.type === HyperLinkEditSourceType.EDITING) ? UpdateRichHyperLinkCommand.id : UpdateHyperLinkCommand.id;
+ await commandService.executeCommand(commandId, {
+ id,
unitId: editing.unitId,
subUnitId: editing.subUnitId,
- id,
payload: {
- display,
+ display: showLabel ? display : '',
payload: formatUrl(type, payload),
},
+ row: editing.row,
+ column: editing.col,
+ documentId: editing.type === HyperLinkEditSourceType.ZEN_EDITOR ?
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ : editorBridgeService.getCurrentEditorId(),
});
} else {
- await commandService.executeCommand(AddHyperLinkCommand.id, {
+ const commandId = (editing.type === HyperLinkEditSourceType.ZEN_EDITOR || editing.type === HyperLinkEditSourceType.EDITING) ? AddRichHyperLinkCommand.id : AddHyperLinkCommand.id;
+ await commandService.executeCommand(commandId, {
unitId: editing.unitId,
subUnitId: editing.subUnitId,
link: {
- id: Tools.generateRandomId(),
+ id: generateRandomId(),
row: editing.row,
- column: editing.column,
+ column: editing.col,
payload: formatUrl(type, payload),
- display,
+ display: showLabel ? display : '',
},
+ documentId: editing.type === HyperLinkEditSourceType.ZEN_EDITOR ?
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ : editorBridgeService.getCurrentEditorId(),
});
}
}
- if (editing) {
+ if (editing?.type === HyperLinkEditSourceType.VIEWING) {
await commandService.executeCommand(SetWorksheetActiveOperation.id, {
unitId: editing.unitId,
subUnitId: editing.subUnitId,
@@ -242,41 +318,49 @@ export const CellLinkEdit = () => {
range: {
startRow: Math.max(editing.row - GAP, 0),
endRow: editing.row + GAP,
- startColumn: Math.max(editing.column - GAP, 0),
- endColumn: editing.column + GAP,
+ startColumn: Math.max(editing.col - GAP, 0),
+ endColumn: editing.col + GAP,
},
});
}
- commandService.executeCommand(CloseHyperLinkSidebarOperation.id);
+ commandService.executeCommand(CloseHyperLinkPopupOperation.id);
};
+ if (!editing) {
+ return null;
+ }
+
return (
- <div>
- <FormLayout
- label={localeService.t('hyperLink.form.label')}
- error={showError && !display ? localeService.t('hyperLink.form.inputError') : ''}
- >
- <Input
- value={display}
- onChange={(v) => {
- setDisplay(v);
- setByPayload.current = false;
- }}
- placeholder={localeService.t('hyperLink.form.labelPlaceholder')}
- />
- </FormLayout>
- <FormLayout label={localeService.t('hyperLink.form.type')}>
+ <div className={styles.cellLinkEdit} style={{ display: hide ? 'none' : 'block' }}>
+ {showLabel
+ ? (
+ <FormLayout
+ label={localeService.t('hyperLink.form.label')}
+ error={showError && !display ? localeService.t('hyperLink.form.inputError') : ''}
+ >
+ <Input
+ value={display}
+ onChange={(v) => {
+ setDisplay(v);
+ setByPayload.current = false;
+ }}
+ placeholder={localeService.t('hyperLink.form.labelPlaceholder')}
+ />
+ </FormLayout>
+ )
+ : null}
+ <FormLayout label={localeService.t('hyperLink.form.type')} contentStyle={{ marginBottom: 0 }}>
<Select
options={linkTypeOptions}
value={type}
onChange={(newType) => {
- setType(newType as LinkType);
+ setType(newType as SheetHyperLinkType);
setPayload('');
}}
/>
</FormLayout>
- {type === LinkType.link && (
+ {type === SheetHyperLinkType.URL && (
<FormLayout
error={showError ? !payload ? localeService.t('hyperLink.form.inputError') : !isLegalLink(payload) ? localeService.t('hyperLink.form.linkError') : '' : ''}
>
@@ -293,7 +377,7 @@ export const CellLinkEdit = () => {
/>
</FormLayout>
)}
- {type === LinkType.range && (
+ {type === SheetHyperLinkType.RANGE && (
<FormLayout error={showError && !payload ? localeService.t('hyperLink.form.inputError') : ''}>
<RangeSelector
openForSheetUnitId={workbook.getUnitId()}
@@ -301,10 +385,37 @@ export const CellLinkEdit = () => {
isSingleChoice
value={payloadInitial}
onChange={handleRangeChange}
+ disableInput={editing.type === HyperLinkEditSourceType.ZEN_EDITOR}
+ onSelectorVisibleChange={async (visible) => {
+ if (visible) {
+ if (editing.type === HyperLinkEditSourceType.ZEN_EDITOR) {
+ zenZoneService.hide();
+ contextService.setContextValue(FOCUSING_SHEET, true);
+ }
+ if (editing.type !== HyperLinkEditSourceType.VIEWING) {
+ editorBridgeService.enableForceKeepVisible();
+ }
+ setHide(true);
+ } else {
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col });
+ if (editing.type === HyperLinkEditSourceType.ZEN_EDITOR) {
+ await commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId: editing.unitId,
+ subUnitId: editing.subUnitId,
+ selections: [{ range: { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col } }],
+ } as ISetSelectionsOperationParams);
+
+ zenZoneService.show();
+ contextService.setContextValue(FOCUSING_SHEET, false);
+ }
+ editorBridgeService.disableForceKeepVisible();
+ setHide(false);
+ }
+ }}
/>
</FormLayout>
)}
- {type === LinkType.sheet && (
+ {type === SheetHyperLinkType.SHEET && (
<FormLayout error={showError && !payload ? localeService.t('hyperLink.form.selectError') : ''}>
<Select
options={sheetsOption}
@@ -321,7 +432,7 @@ export const CellLinkEdit = () => {
/>
</FormLayout>
)}
- {type === LinkType.definedName && (
+ {type === SheetHyperLinkType.DEFINE_NAME && (
<FormLayout error={showError && !payload ? localeService.t('hyperLink.form.selectError') : ''}>
<Select
options={definedNames}
@@ -356,12 +467,9 @@ export const CellLinkEdit = () => {
<Button
onClick={() => {
if (editing) {
- commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId: editing.unitId,
- subUnitId: editing.subUnitId,
- });
+ resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col });
}
- commandService.executeCommand(CloseHyperLinkSidebarOperation.id);
+ commandService.executeCommand(CloseHyperLinkPopupOperation.id);
}}
>
{localeService.t('hyperLink.form.cancel')}
@@ -370,7 +478,7 @@ export const CellLinkEdit = () => {
type="primary"
style={{ marginLeft: 8 }}
onClick={async () => {
- if (!display || !payload || (type === LinkType.link && !isLegalLink(payload))) {
+ if ((showLabel && !display) || !payload || (type === SheetHyperLinkType.URL && !isLegalLink(payload))) {
setShowError(true);
return;
}
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 cbf65ab8be..2b17389f42 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx
@@ -14,38 +14,38 @@
* limitations under the License.
*/
-import { ICommandService, LocaleService, useDependency } from '@univerjs/core';
-import { HyperLinkModel } from '@univerjs/sheets-hyper-link';
+import { DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, LocaleService, useDependency } from '@univerjs/core';
import React, { useEffect, useState } from 'react';
import { AllBorderSingle, CopySingle, LinkSingle, UnlinkSingle, WriteSingle, Xlsx } from '@univerjs/icons';
import cs from 'clsx';
import { MessageType, Tooltip } from '@univerjs/design';
import { IMessageService } from '@univerjs/ui';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
import type { IHyperLinkPopup } from '../../services/popup.service';
import { SheetsHyperLinkPopupService } from '../../services/popup.service';
import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
-import { OpenHyperLinkSidebarOperation } from '../../commands/operations/sidebar.operations';
-import { CancelHyperLinkCommand } from '../../commands/commands/remove-hyper-link.command';
+import { OpenHyperLinkEditPanelOperation } from '../../commands/operations/popup.operations';
+import { CancelHyperLinkCommand, CancelRichHyperLinkCommand } from '../../commands/commands/remove-hyper-link.command';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
import styles from './index.module.less';
const iconsMap = {
- outer: <LinkSingle />,
- link: <LinkSingle />,
- sheet: <Xlsx />,
- range: <AllBorderSingle />,
- defineName: <AllBorderSingle />,
- 'range-error': <AllBorderSingle />,
- 'sheet-error': <Xlsx />,
+ [SheetHyperLinkType.URL]: <LinkSingle />,
+ [SheetHyperLinkType.SHEET]: <Xlsx />,
+ [SheetHyperLinkType.RANGE]: <AllBorderSingle />,
+ [SheetHyperLinkType.DEFINE_NAME]: <AllBorderSingle />,
+ [SheetHyperLinkType.INVALID]: <AllBorderSingle />,
};
export const CellLinkPopup = () => {
const popupService = useDependency(SheetsHyperLinkPopupService);
- const hyperLinkModel = useDependency(HyperLinkModel);
const commandService = useDependency(ICommandService);
const messageService = useDependency(IMessageService);
const localeService = useDependency(LocaleService);
const [currentPopup, setCurrentPopup] = useState<IHyperLinkPopup | null>(null);
const resolverService = useDependency(SheetsHyperLinkResolverService);
+ const editorBridgeService = useDependency(IEditorBridgeService);
useEffect(() => {
setCurrentPopup(popupService.currentPopup);
@@ -60,13 +60,13 @@ export const CellLinkPopup = () => {
if (!currentPopup) {
return null;
}
- const { unitId, subUnitId, id } = currentPopup;
- const link = hyperLinkModel.getHyperLink(unitId, subUnitId, id);
- if (!link) {
+
+ const { unitId, subUnitId, customRange, row, col } = currentPopup;
+ if (!customRange?.properties?.url) {
return null;
}
- const linkObj = resolverService.parseHyperLink(link.payload);
- const isError = linkObj.type.indexOf('error') > -1;
+ const linkObj = resolverService.parseHyperLink(customRange.properties.url ?? '');
+ const isError = linkObj.type === SheetHyperLinkType.INVALID;
return (
<div className={styles.cellLink} onClick={() => popupService.hideCurrentPopup()}>
@@ -86,7 +86,7 @@ export const CellLinkPopup = () => {
if (isError) {
return;
}
- if (linkObj.type !== 'outer') {
+ if (linkObj.type !== SheetHyperLinkType.URL) {
const url = new URL(window.location.href);
url.hash = linkObj.url.slice(1);
navigator.clipboard.writeText(url.href);
@@ -110,11 +110,13 @@ export const CellLinkPopup = () => {
<div
className={styles.cellLinkOperation}
onClick={() => {
- commandService.executeCommand(OpenHyperLinkSidebarOperation.id, {
+ commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
unitId,
subUnitId,
- row: link.row,
- column: link.column,
+ row,
+ col,
+ customRangeId: customRange.rangeId,
+ type: currentPopup.type,
});
}}
>
@@ -125,11 +127,19 @@ export const CellLinkPopup = () => {
<div
className={styles.cellLinkOperation}
onClick={() => {
- commandService.executeCommand(CancelHyperLinkCommand.id, {
+ const commandId = (currentPopup.type === HyperLinkEditSourceType.EDITING || currentPopup.type === HyperLinkEditSourceType.ZEN_EDITOR) ? CancelRichHyperLinkCommand.id : CancelHyperLinkCommand.id;
+ if (commandService.syncExecuteCommand(commandId, {
unitId,
subUnitId,
- id: link.id,
- });
+ id: customRange.rangeId,
+ row,
+ column: col,
+ documentId: currentPopup.type === HyperLinkEditSourceType.ZEN_EDITOR ?
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY
+ : editorBridgeService.getCurrentEditorId(),
+ })) {
+ popupService.hideCurrentPopup(undefined, true);
+ }
}}
>
<Tooltip placement="bottom" title={localeService.t('hyperLink.popup.cancel')}>
diff --git a/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts b/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts
index 1f53ac328e..7258ebcf80 100644
--- a/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts
+++ b/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts
@@ -32,7 +32,6 @@ export const AddHyperLinkMutation: ICommand<IAddHyperLinkMutationParams> = {
if (!params) {
return false;
}
-
const model = accessor.get(HyperLinkModel);
const { unitId, subUnitId, link } = params;
return model.addHyperLink(unitId, subUnitId, link);
diff --git a/packages/sheets-hyper-link/src/index.ts b/packages/sheets-hyper-link/src/index.ts
index e41a9f88cc..e71ada8867 100644
--- a/packages/sheets-hyper-link/src/index.ts
+++ b/packages/sheets-hyper-link/src/index.ts
@@ -15,7 +15,7 @@
*/
export { HyperLinkModel } from './models/hyper-link.model';
-export { HyperLinkType } from './types/enums/hyper-link-type';
+export { SheetHyperLinkType } from './types/enums/hyper-link-type';
export { UniverSheetsHyperLinkPlugin } from './plugin';
export type { ICellHyperLink, ICellLinkContent } from './types/interfaces/i-hyper-link';
diff --git a/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts b/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts
index 461c51e190..301cae7f7c 100644
--- a/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts
+++ b/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts
@@ -14,7 +14,10 @@
* limitations under the License.
*/
-export enum HyperLinkType {
- range = 0,
- link = 1,
+export enum SheetHyperLinkType {
+ SHEET = 'gid',
+ RANGE = 'range',
+ DEFINE_NAME = 'rangeid',
+ INVALID = 'invalid',
+ URL = 'url',
}
diff --git a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts
index 9b92adadef..315d26b363 100644
--- a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts
+++ b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { ICellDataForSheetInterceptor, Workbook, Worksheet } from '@univerjs/core';
import { createInterceptorKey, ICommandService, InterceptorManager, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import type { ISetNumfmtMutationParams, ISheetLocation } from '@univerjs/sheets';
import { SetNumfmtMutation } from '@univerjs/sheets';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { beforeEach, describe, expect, it } from 'vitest';
+import type { ICellDataForSheetInterceptor, Workbook, Worksheet } from '@univerjs/core';
+import type { ISetNumfmtMutationParams, ISheetLocation } from '@univerjs/sheets';
import { SheetsNumfmtCellContentController } from '../numfmt.cell-content.controller';
import { NumfmtEditorController } from '../numfmt.editor.controller';
@@ -74,6 +74,7 @@ describe('test editor', () => {
};
commandService.syncExecuteCommand(SetNumfmtMutation.id, params);
const editorBridgeService = testBed.get(IEditorBridgeService);
+ const cellData = worksheet.getCell(0, 0);
const location = {
workbook,
worksheet,
@@ -81,8 +82,9 @@ describe('test editor', () => {
subUnitId,
row: 0,
col: 0,
+ origin: cellData,
};
- const cellData = worksheet.getCell(0, 0);
+
expect(cellData!.v).toEqual('$0');
expect(cellData!.t).toEqual(2);
@@ -110,6 +112,7 @@ describe('test editor', () => {
};
commandService.syncExecuteCommand(SetNumfmtMutation.id, params);
const editorBridgeService = testBed.get(IEditorBridgeService);
+ const cellData = worksheet.getCell(0, 0);
const location = {
workbook,
worksheet,
@@ -117,8 +120,9 @@ describe('test editor', () => {
subUnitId,
row: 0,
col: 0,
+ origin: cellData,
};
- const cellData = worksheet.getCell(0, 0);
+
const result = editorBridgeService.interceptor.fetchThroughInterceptors(
editorBridgeService.interceptor.getInterceptPoints().BEFORE_CELL_EDIT
)(cellData, location);
@@ -142,6 +146,7 @@ describe('test editor', () => {
};
commandService.syncExecuteCommand(SetNumfmtMutation.id, params);
const editorBridgeService = testBed.get(IEditorBridgeService);
+ const cellData = { v: '12:33:22', t: 2 };
const location = {
workbook,
worksheet,
@@ -149,8 +154,9 @@ describe('test editor', () => {
subUnitId,
row: 0,
col: 0,
+ origin: cellData,
};
- const cellData = { v: '12:33:22', t: 2 };
+
const result = editorBridgeService.interceptor.fetchThroughInterceptors(
editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT
)(cellData, location);
diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-popup.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-popup.controller.ts
new file mode 100644
index 0000000000..5927f6009a
--- /dev/null
+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-popup.controller.ts
@@ -0,0 +1,261 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable, Workbook } from '@univerjs/core';
+import { Disposable, ICommandService, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
+import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { RangeProtectionPermissionViewPoint, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookCommentPermission, WorksheetViewPermission } from '@univerjs/sheets';
+import { singleReferenceToGrid } from '@univerjs/engine-formula';
+import type { IDeleteCommentMutationParams } from '@univerjs/thread-comment';
+import { DeleteCommentMutation } from '@univerjs/thread-comment';
+import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation, SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment-base';
+import { debounceTime } from 'rxjs';
+import { SheetsThreadCommentPopupService } from '../services/sheets-thread-comment-popup.service';
+
+interface ISelectionShapeInfo {
+ shapeId: string;
+ unitId: string;
+ subUnitId: string;
+ commentId: string;
+}
+
+@OnLifecycle(LifecycleStages.Rendered, SheetsThreadCommentPopupController)
+export class SheetsThreadCommentPopupController extends Disposable {
+ private _isSwitchToCommenting = false;
+ private _selectionShapeInfo: Nullable<ISelectionShapeInfo> = null;
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(SheetsThreadCommentPopupService) private readonly _sheetsThreadCommentPopupService: SheetsThreadCommentPopupService,
+ @Inject(SheetsThreadCommentModel) private readonly _sheetsThreadCommentModel: SheetsThreadCommentModel,
+ @Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController,
+ @IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService,
+ @Inject(SheetsSelectionsService) private readonly _sheetSelectionService: SheetsSelectionsService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
+ ) {
+ super();
+
+ this._initCommandListener();
+ this._initPanelListener();
+ this._initMarkSelection();
+ this._initSelectionUpdateListener();
+ this._initEditorBridge();
+ }
+
+ private _handleSelectionChange(selections: ISelectionWithStyle[], unitId: string, subUnitId: string) {
+ const range = selections[0]?.range;
+ if (!range) {
+ return;
+ }
+ const rangeType = range.rangeType ?? RANGE_TYPE.NORMAL;
+ if (rangeType !== RANGE_TYPE.NORMAL || range.endColumn - range.startColumn > 0 || range.endRow - range.startRow > 0) {
+ if (this._threadCommentPanelService.activeCommentId) {
+ this._commandService.executeCommand(SetActiveCommentOperation.id);
+ }
+ return;
+ }
+
+ const row = range.startRow;
+ const col = range.startColumn;
+ if (!this._sheetsThreadCommentModel.showCommentMarker(unitId, subUnitId, row, col)) {
+ if (this._threadCommentPanelService.activeCommentId) {
+ this._commandService.executeCommand(SetActiveCommentOperation.id);
+ }
+ return;
+ }
+
+ const commentId = this._sheetsThreadCommentModel.getByLocation(unitId, subUnitId, row, col);
+ if (commentId) {
+ this._commandService.executeCommand(SetActiveCommentOperation.id, {
+ unitId,
+ subUnitId,
+ commentId,
+ });
+ }
+ }
+
+ private _initSelectionUpdateListener() {
+ this.disposeWithMe(
+ this._sheetSelectionService.selectionMoveEnd$.subscribe((selections) => {
+ if (this._isSwitchToCommenting) {
+ return;
+ }
+ const current = this._sheetSelectionService.currentSelectionParam;
+ if (!current) {
+ return;
+ }
+ this._handleSelectionChange(selections, current.unitId, current.sheetId);
+ })
+ );
+ }
+
+ private _initEditorBridge() {
+ this.disposeWithMe(
+ this._editorBridgeService.visible$.subscribe((visible) => {
+ if (visible.visible) {
+ this._sheetsThreadCommentPopupService.hidePopup();
+ }
+ })
+ );
+ }
+
+ private _initCommandListener() {
+ this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === DeleteCommentMutation.id) {
+ const params = commandInfo.params as IDeleteCommentMutationParams;
+ const active = this._sheetsThreadCommentPopupService.activePopup;
+ if (!active) {
+ return;
+ }
+ const { unitId, subUnitId, commentId } = active;
+ if (params.unitId === unitId && params.subUnitId === subUnitId && params.commentId === commentId) {
+ this._sheetsThreadCommentPopupService.hidePopup();
+ }
+ }
+ });
+ }
+
+ private _initPanelListener() {
+ this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.subscribe(async (commentInfo) => {
+ if (commentInfo) {
+ const { unitId, subUnitId, commentId, trigger } = commentInfo;
+ const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);
+ if (!comment || comment.resolved) {
+ return;
+ }
+
+ const currentUnit = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (!currentUnit) {
+ return;
+ }
+ const currentUnitId = currentUnit.getUnitId();
+ if (currentUnitId !== unitId) {
+ return;
+ }
+ this._isSwitchToCommenting = true;
+ const currentSheetId = currentUnit.getActiveSheet()?.getSheetId();
+ if (currentSheetId !== subUnitId) {
+ await this._commandService.executeCommand(SetWorksheetActiveOperation.id, {
+ unitId,
+ subUnitId,
+ });
+ }
+ this._isSwitchToCommenting = false;
+
+ const location = singleReferenceToGrid(comment.ref);
+
+ const { row, column: col } = location;
+ const commentPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
+ workbookTypes: [WorkbookCommentPermission],
+ worksheetTypes: [WorksheetViewPermission],
+ rangeTypes: [RangeProtectionPermissionViewPoint],
+ }, [{ startRow: row, startColumn: col, endRow: row, endColumn: col }]);
+
+ if (!commentPermission) {
+ return;
+ }
+
+ const GAP = 1;
+ await this._commandService.executeCommand(ScrollToRangeOperation.id, {
+ range: {
+ startRow: Math.max(location.row - GAP, 0),
+ endRow: location.row + GAP,
+ startColumn: Math.max(location.column - GAP, 0),
+ endColumn: location.column + GAP,
+ },
+ });
+ if (this._editorBridgeService.isVisible().visible) {
+ return;
+ }
+
+ this._sheetsThreadCommentPopupService.showPopup({
+ unitId,
+ subUnitId,
+ row: location.row,
+ col: location.column,
+ commentId: comment.id,
+ trigger,
+ });
+ } else {
+ this._sheetsThreadCommentPopupService.hidePopup();
+ }
+ }));
+ }
+
+ private _initMarkSelection() {
+ this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.pipe(debounceTime(100)).subscribe((activeComment) => {
+ if (!activeComment) {
+ if (this._selectionShapeInfo) {
+ this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
+ this._selectionShapeInfo = null;
+ }
+ return;
+ }
+
+ const { unitId, subUnitId, commentId } = activeComment;
+ if (this._selectionShapeInfo) {
+ this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
+ this._selectionShapeInfo = null;
+ }
+
+ const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);
+ if (!comment) {
+ return;
+ }
+
+ const location = singleReferenceToGrid(comment.ref);
+
+ const { row, column } = location;
+ if (Number.isNaN(row) || Number.isNaN(column)) {
+ return null;
+ }
+
+ // TODO: use evented: false to solve this problem later
+ const shapeId = this._markSelectionService.addShape(
+ {
+ range: {
+ startColumn: column,
+ endColumn: column,
+ startRow: row,
+ endRow: row,
+ },
+ style: {
+ hasAutoFill: false,
+ fill: 'rgb(255, 189, 55, 0.35)',
+ strokeWidth: 1,
+ stroke: '#FFBD37',
+ widgets: {},
+ },
+ primary: null,
+ },
+ [],
+ -1
+ );
+ if (!shapeId) {
+ return;
+ }
+
+ this._selectionShapeInfo = {
+ ...activeComment,
+ shapeId,
+ };
+ }));
+ }
+}
diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
index fde8066ad6..76b8756821 100644
--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
@@ -14,129 +14,33 @@
* limitations under the License.
*/
-import type { Nullable, Workbook } from '@univerjs/core';
-import { Disposable, ICommandService, Inject, Injector, IUniverInstanceService, LifecycleStages, OnLifecycle, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
+import { Disposable, Inject, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { ComponentManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';
import { CommentSingle } from '@univerjs/icons';
-import { SetActiveCommentOperation, THREAD_COMMENT_PANEL, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
-import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { RangeProtectionPermissionViewPoint, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookCommentPermission, WorksheetViewPermission } from '@univerjs/sheets';
-import { singleReferenceToGrid } from '@univerjs/engine-formula';
-import type { IDeleteCommentMutationParams } from '@univerjs/thread-comment';
-import { DeleteCommentMutation } from '@univerjs/thread-comment';
-import { IMarkSelectionService, ScrollToRangeOperation, SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
-import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment-base';
-import { debounceTime } from 'rxjs';
+import { THREAD_COMMENT_PANEL } from '@univerjs/thread-comment-ui';
import { SheetsThreadCommentCell } from '../views/sheets-thread-comment-cell';
import { COMMENT_SINGLE_ICON, SHEETS_THREAD_COMMENT_MODAL } from '../types/const';
import { SheetsThreadCommentPanel } from '../views/sheets-thread-comment-panel';
-import { SheetsThreadCommentPopupService } from '../services/sheets-thread-comment-popup.service';
import { AddCommentShortcut } from './menu';
import { menuSchema } from './menu.schema';
-interface ISelectionShapeInfo {
- shapeId: string;
- unitId: string;
- subUnitId: string;
- commentId: string;
-}
-
@OnLifecycle(LifecycleStages.Starting, SheetsThreadCommentController)
export class SheetsThreadCommentController extends Disposable {
- private _isSwitchToCommenting = false;
- private _selectionShapeInfo: Nullable<ISelectionShapeInfo> = null;
-
constructor(
@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
- @Inject(Injector) private readonly _injector: Injector,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
- @ICommandService private readonly _commandService: ICommandService,
- @Inject(SheetsThreadCommentPopupService) private readonly _sheetsThreadCommentPopupService: SheetsThreadCommentPopupService,
- @Inject(SheetsThreadCommentModel) private readonly _sheetsThreadCommentModel: SheetsThreadCommentModel,
- @Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService,
- @IShortcutService private readonly _shortcutService: IShortcutService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController,
- @IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService,
- @Inject(SheetsSelectionsService) private readonly _sheetSelectionService: SheetsSelectionsService
+ @IShortcutService private readonly _shortcutService: IShortcutService
) {
super();
this._initMenu();
this._initShortcut();
this._initComponent();
- this._initCommandListener();
- this._initPanelListener();
- this._initMarkSelection();
- this._initSelectionUpdateListener();
}
private _initShortcut() {
this._shortcutService.registerShortcut(AddCommentShortcut);
}
- private _handleSelectionChange(selections: ISelectionWithStyle[], unitId: string, subUnitId: string) {
- const range = selections[0]?.range;
- if (!range) {
- return;
- }
- const rangeType = range.rangeType ?? RANGE_TYPE.NORMAL;
- if (rangeType !== RANGE_TYPE.NORMAL || range.endColumn - range.startColumn > 0 || range.endRow - range.startRow > 0) {
- if (this._threadCommentPanelService.activeCommentId) {
- this._commandService.executeCommand(SetActiveCommentOperation.id);
- }
- return;
- }
-
- const row = range.startRow;
- const col = range.startColumn;
- if (!this._sheetsThreadCommentModel.showCommentMarker(unitId, subUnitId, row, col)) {
- if (this._threadCommentPanelService.activeCommentId) {
- this._commandService.executeCommand(SetActiveCommentOperation.id);
- }
- return;
- }
-
- const commentId = this._sheetsThreadCommentModel.getByLocation(unitId, subUnitId, row, col);
- if (commentId) {
- this._commandService.executeCommand(SetActiveCommentOperation.id, {
- unitId,
- subUnitId,
- commentId,
- });
- }
- }
-
- private _initSelectionUpdateListener() {
- this.disposeWithMe(
- this._sheetSelectionService.selectionMoveEnd$.subscribe((selections) => {
- if (this._isSwitchToCommenting) {
- return;
- }
- const current = this._sheetSelectionService.currentSelectionParam;
- if (!current) {
- return;
- }
- this._handleSelectionChange(selections, current.unitId, current.sheetId);
- })
- );
- }
-
- private _initCommandListener() {
- this._commandService.onCommandExecuted((commandInfo) => {
- if (commandInfo.id === DeleteCommentMutation.id) {
- const params = commandInfo.params as IDeleteCommentMutationParams;
- const active = this._sheetsThreadCommentPopupService.activePopup;
- if (!active) {
- return;
- }
- const { unitId, subUnitId, commentId } = active;
- if (params.unitId === unitId && params.subUnitId === subUnitId && params.commentId === commentId) {
- this._sheetsThreadCommentPopupService.hidePopup();
- }
- }
- });
- }
-
private _initMenu() {
this._menuManagerService.mergeMenu(menuSchema);
}
@@ -150,128 +54,4 @@ export class SheetsThreadCommentController extends Disposable {
this._componentManager.register(key, comp);
});
}
-
- private _initPanelListener() {
- this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.subscribe(async (commentInfo) => {
- if (commentInfo) {
- const { unitId, subUnitId, commentId, trigger } = commentInfo;
- const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);
- if (!comment || comment.resolved) {
- return;
- }
-
- const currentUnit = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!currentUnit) {
- return;
- }
- const currentUnitId = currentUnit.getUnitId();
- if (currentUnitId !== unitId) {
- return;
- }
- this._isSwitchToCommenting = true;
- const currentSheetId = currentUnit.getActiveSheet()?.getSheetId();
- if (currentSheetId !== subUnitId) {
- await this._commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId,
- subUnitId,
- });
- }
- this._isSwitchToCommenting = false;
-
- const location = singleReferenceToGrid(comment.ref);
-
- const { row, column: col } = location;
- const commentPermission = this._sheetPermissionInterceptorBaseController.permissionCheckWithRanges({
- workbookTypes: [WorkbookCommentPermission],
- worksheetTypes: [WorksheetViewPermission],
- rangeTypes: [RangeProtectionPermissionViewPoint],
- }, [{ startRow: row, startColumn: col, endRow: row, endColumn: col }]);
-
- if (!commentPermission) {
- return;
- }
-
- const GAP = 1;
- await this._commandService.executeCommand(ScrollToRangeOperation.id, {
- range: {
- startRow: Math.max(location.row - GAP, 0),
- endRow: location.row + GAP,
- startColumn: Math.max(location.column - GAP, 0),
- endColumn: location.column + GAP,
- },
- });
-
- this._sheetsThreadCommentPopupService.showPopup({
- unitId,
- subUnitId,
- row: location.row,
- col: location.column,
- commentId: comment.id,
- trigger,
- });
- } else {
- this._sheetsThreadCommentPopupService.hidePopup();
- }
- }));
- }
-
- private _initMarkSelection() {
- this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.pipe(debounceTime(100)).subscribe((activeComment) => {
- if (!activeComment) {
- if (this._selectionShapeInfo) {
- this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
- this._selectionShapeInfo = null;
- }
- return;
- }
-
- const { unitId, subUnitId, commentId } = activeComment;
- if (this._selectionShapeInfo) {
- this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
- this._selectionShapeInfo = null;
- }
-
- const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);
- if (!comment) {
- return;
- }
-
- const location = singleReferenceToGrid(comment.ref);
-
- const { row, column } = location;
- if (Number.isNaN(row) || Number.isNaN(column)) {
- return null;
- }
-
- // TODO: use evented: false to solve this problem later
- const shapeId = this._markSelectionService.addShape(
- {
- range: {
- startColumn: column,
- endColumn: column,
- startRow: row,
- endRow: row,
- },
- style: {
- hasAutoFill: false,
- fill: 'rgb(255, 189, 55, 0.35)',
- strokeWidth: 1,
- stroke: '#FFBD37',
- widgets: {},
- },
- primary: null,
- },
- [],
- -1
- );
- if (!shapeId) {
- return;
- }
-
- this._selectionShapeInfo = {
- ...activeComment,
- shapeId,
- };
- }));
- }
}
diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.ts
index 323a912598..693b143f29 100644
--- a/packages/sheets-ui/src/common/utils.ts
+++ b/packages/sheets-ui/src/common/utils.ts
@@ -217,6 +217,7 @@ export function transformPosition2Offset(x: number, y: number, scene: Scene, ske
};
}
+// eslint-disable-next-line max-lines-per-function
export function getHoverCellPosition(currentRender: IRender, workbook: Workbook, worksheet: Worksheet, skeletonParam: ISheetSkeletonManagerParam, offsetX: number, offsetY: number) {
const { scene } = currentRender;
@@ -229,27 +230,44 @@ export function getHoverCellPosition(currentRender: IRender, workbook: Workbook,
return null;
}
- const { row, col, mergeCell, actualCol, actualRow } = cellIndex;
+ let { actualCol, actualRow } = cellIndex;
+
+ skeleton.overflowCache.forValue((r, c, range) => {
+ if (range.startRow <= actualRow && range.endRow >= actualRow && range.startColumn <= actualCol && range.endColumn >= actualCol) {
+ actualCol = c;
+ actualRow = r;
+ }
+ });
+
+ const actualCell = skeleton.getCellByIndex(actualRow, actualCol);
+ const originCell = skeleton.getCellByIndex(cellIndex.row, cellIndex.col);
+ const originLocation = {
+ unitId,
+ subUnitId: sheetId,
+ workbook,
+ worksheet,
+ row: originCell.actualRow,
+ col: originCell.actualColumn,
+ };
const location: ISheetLocation = {
unitId,
subUnitId: sheetId,
workbook,
worksheet,
- row: actualRow,
- col: actualCol,
+ row: actualCell.actualRow,
+ col: actualCell.actualColumn,
};
let anchorCell: IRange;
-
- if (mergeCell) {
- anchorCell = mergeCell;
+ if (actualCell.mergeInfo) {
+ anchorCell = actualCell.mergeInfo;
} else {
anchorCell = {
- startRow: row,
- endRow: row,
- startColumn: col,
- endColumn: col,
+ startRow: location.row,
+ endRow: location.row,
+ startColumn: location.col,
+ endColumn: location.col,
};
}
@@ -277,6 +295,7 @@ export function getHoverCellPosition(currentRender: IRender, workbook: Workbook,
return {
position,
- location,
+ location: originLocation,
+ overflowLocation: location,
};
}
diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
index 4a48c1c225..e7fd5d2412 100644
--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
@@ -34,11 +34,14 @@ import {
LocaleService,
ObjectMatrix,
OnLifecycle,
- RxDisposable, UniverInstanceType,
+ RxDisposable,
+ Tools,
+ UniverInstanceType,
} from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+
import {
InsertColMutation,
InsertRowMutation,
@@ -551,7 +554,7 @@ export class SheetClipboardController extends RxDisposable {
private _onPastePlainText(pasteTo: ISheetDiscreteRangeLocation, text: string, payload: ICopyPastePayload) {
const { range, unitId, subUnitId } = pasteTo;
let cellValue: IObjectMatrixPrimitiveType<ICellData>;
- if (/\r|\n/.test(text)) {
+ if (/\r|\n/.test(text) || Tools.isLegalUrl(text)) {
const body = generateBody(text);
const p = this._generateDocumentDataModelSnapshot({ body });
cellValue = {
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 99c7513a7f..38f8cbd497 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IAccessor, ICellData, IDocumentBody, IMutationInfo, IParagraph, IRange, Nullable } from '@univerjs/core';
-import { cellToRange, DEFAULT_STYLES, IUniverInstanceService, numfmt, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
+import type { IAccessor, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, Nullable } from '@univerjs/core';
+import { cellToRange, CustomRangeType, DataStreamTreeTokenType, DEFAULT_STYLES, generateRandomId, IUniverInstanceService, numfmt, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
import type {
IAddWorksheetMergeMutationParams,
IMoveRangeMutationParams,
@@ -551,6 +551,25 @@ 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 range: ICustomRange = {
+ startIndex: 0,
+ endIndex: urlText.length - 1,
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: text,
+ },
+ };
+
+ return {
+ dataStream: `${urlText}\r\n`,
+ customRanges: [range],
+ };
+ }
+
// Convert all \n to \r, because we use \r to indicate paragraph break.
let dataStream = text.replace(/(\r\n|\n)/g, '\r');
if (!dataStream.endsWith('\r\n')) {
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
index b32cc2495a..5fdfca835e 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { CellValueType, IContextService, IResourceLoaderService, LocaleService, LocaleType, Tools, UNIVER_INTERNAL } from '@univerjs/core';
+import { CellValueType, IContextService, IResourceLoaderService, LocaleService, LocaleType, Tools } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -153,13 +153,6 @@ describe('Test EndEditController', () => {
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
});
it('Rich text cell', () => {
@@ -174,13 +167,6 @@ describe('Test EndEditController', () => {
const target = { v: null, f: null, si: null, p: richTextDemo };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
});
it('Formula cell', () => {
@@ -195,13 +181,7 @@ describe('Test EndEditController', () => {
const target = { v: null, f: '=SUM(1)', si: null, p: null, t: undefined };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
+
});
});
it('Clear formula cell', () => {
@@ -219,13 +199,6 @@ describe('Test EndEditController', () => {
const target = { v: '', f: null, si: null, p: null, t: undefined };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
});
@@ -244,13 +217,6 @@ describe('Test EndEditController', () => {
const target = { v: null, f: null, si: null, p: richTextDemo, t: undefined };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
});
@@ -263,39 +229,18 @@ describe('Test EndEditController', () => {
let target = { v: 'test', t: CellValueType.FORCE_STRING, f: null, si: null, p: null };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
cellData = getCellDataByInputCell(cell, { v: "'1" });
target = { v: '1', t: CellValueType.FORCE_STRING, f: null, si: null, p: null };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
cellData = getCellDataByInputCell(cell, { v: "'=SUM" });
target = { v: '=SUM', t: CellValueType.FORCE_STRING, f: null, si: null, p: null };
expect(cellData).toEqual({
...target,
- custom: {
- [UNIVER_INTERNAL]: {
- origin: {
- ...target,
- },
- },
- },
});
});
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 fe4623e620..d06650fb71 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -36,7 +36,6 @@ import {
numfmt,
toDisposable,
Tools,
- UNIVER_INTERNAL,
UniverInstanceType,
VerticalAlign,
WrapStrategy,
@@ -910,8 +909,8 @@ export class EditingRenderController extends Disposable implements IRenderModule
worksheet,
row,
col: column,
+ origin: Tools.deepClone(cellData),
};
-
const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT
)(cellData, context);
@@ -920,9 +919,6 @@ export class EditingRenderController extends Disposable implements IRenderModule
this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT_ASYNC
)(Promise.resolve(cell), context);
// remove temp value
- if (finalCell?.custom?.[UNIVER_INTERNAL]?.origin) {
- finalCell.custom[UNIVER_INTERNAL] = null;
- }
this._commandService.executeCommand(SetRangeValuesCommand.id, {
subUnitId: sheetId,
@@ -1129,12 +1125,6 @@ export function getCellDataByInput(
}
}
- cellData.custom = {
- [UNIVER_INTERNAL]: {
- origin: { ...cellData },
- },
- };
-
return cellData;
}
diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
index 75cd8db9fe..a576238867 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -43,7 +43,7 @@ import { DeviceInputEventType, IRenderManagerService, ScrollBar } from '@univerj
import { MoveRangeMutation, RangeProtectionRuleModel, SetRangeValuesMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import { SetEditorResizeOperation } from '@univerjs/ui';
import { takeUntil } from 'rxjs';
-import type { DocumentDataModel, ICommandInfo, IParagraph, ITextRun, JSONXActions, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, ICustomRange, IParagraph, ITextRun, JSONXActions, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentViewModel, RenderComponentType } from '@univerjs/engine-render';
@@ -281,8 +281,9 @@ export class FormulaEditorController extends RxDisposable {
let dataStream = body?.dataStream;
let paragraphs = body?.paragraphs;
let textRuns = body?.textRuns;
+ const customRanges = body?.customRanges;
- if (dataStream == null || paragraphs == null) {
+ if (dataStream == null || (!paragraphs && !customRanges)) {
return;
}
@@ -299,7 +300,7 @@ export class FormulaEditorController extends RxDisposable {
textRuns = [];
}
- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns);
+ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs ?? [], textRuns, customRanges);
// Also need to resize document and scene after sync content.
this._autoScroll();
@@ -323,6 +324,7 @@ export class FormulaEditorController extends RxDisposable {
const dataStream = editorDocDataModel?.getBody()?.dataStream;
const paragraphs = editorDocDataModel?.getBody()?.paragraphs;
const textRuns = editorDocDataModel?.getBody()?.textRuns;
+ const customRanges = editorDocDataModel?.getBody()?.customRanges;
const syncId =
unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
@@ -337,7 +339,7 @@ export class FormulaEditorController extends RxDisposable {
this._checkAndSetRenderStyleConfig(editorDocDataModel!);
this._syncActionsAndRender(syncId, actions);
} else {
- this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns);
+ this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns, customRanges);
}
// handle weather need to show scroll bar.
@@ -361,6 +363,7 @@ export class FormulaEditorController extends RxDisposable {
const dataStream = editorDocDataModel?.getBody()?.dataStream;
const paragraphs = editorDocDataModel?.getBody()?.paragraphs;
const textRuns = editorDocDataModel?.getBody()?.textRuns;
+ const customRanges = editorDocDataModel?.getBody()?.customRanges;
const syncId =
unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
@@ -371,7 +374,7 @@ export class FormulaEditorController extends RxDisposable {
return;
}
- this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns);
+ this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns, customRanges);
// handle weather need to show scroll bar.
this._autoScroll();
@@ -412,8 +415,8 @@ export class FormulaEditorController extends RxDisposable {
if (body == null) {
return;
}
- const { dataStream, paragraphs = [] } = body;
- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs);
+ const { dataStream, paragraphs = [], customRanges } = body;
+ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, undefined, customRanges);
// handle weather need to show scroll bar.
this._autoScroll();
}
@@ -459,7 +462,8 @@ export class FormulaEditorController extends RxDisposable {
unitId: string,
dataStream: string,
paragraphs: IParagraph[],
- textRuns: ITextRun[] = []
+ textRuns: ITextRun[] = [],
+ customRanges: ICustomRange[] | undefined
) {
const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
@@ -473,6 +477,7 @@ export class FormulaEditorController extends RxDisposable {
docDataModel.getBody()!.dataStream = dataStream;
docDataModel.getBody()!.paragraphs = this._clearParagraph(paragraphs);
+ docDataModel.getBody()!.customRanges = customRanges;
if (textRuns.length > 0) {
docDataModel.getBody()!.textRuns = textRuns;
diff --git a/packages/sheets-ui/src/controllers/hover-render.controller.ts b/packages/sheets-ui/src/controllers/hover-render.controller.ts
index cbe8d51779..22c62052e5 100644
--- a/packages/sheets-ui/src/controllers/hover-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/hover-render.controller.ts
@@ -15,14 +15,21 @@
*/
import type { Nullable, Workbook } from '@univerjs/core';
-import { Disposable, DisposableCollection, Inject } from '@univerjs/core';
+import { Disposable, DisposableCollection, fromEventSubject, Inject } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { throttleTime } from 'rxjs';
import { HoverManagerService } from '../services/hover-manager.service';
import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
import { SheetScrollManagerService } from '../services/scroll-manager.service';
export class HoverRenderController extends Disposable implements IRenderModule {
+ private _active = false;
+
+ get active() {
+ return this._active;
+ }
+
constructor(
private readonly _context: IRenderContext<Workbook>,
@Inject(HoverManagerService) private _hoverManagerService: HoverManagerService,
@@ -44,12 +51,28 @@ export class HoverRenderController extends Disposable implements IRenderModule {
return;
}
- const { mainComponent } = this._context;
- const subscription = mainComponent?.onPointerMove$.subscribeEvent((evt) => {
- this._hoverManagerService.onMouseMove(evt.offsetX, evt.offsetY);
- });
+ const { mainComponent, unitId } = this._context;
+ if (!mainComponent) {
+ return;
+ }
+
+ disposeSet.add(mainComponent.onPointerEnter$.subscribeEvent((evt) => {
+ this._active = true;
+ }));
+
+ disposeSet.add(fromEventSubject(mainComponent.onPointerMove$).pipe(throttleTime(30)).subscribe((evt) => {
+ this._active = true;
+ this._hoverManagerService.triggerMouseMove(unitId, evt.offsetX, evt.offsetY);
+ }));
+
+ disposeSet.add(mainComponent.onPointerUp$.subscribeEvent((evt) => {
+ this._hoverManagerService.triggerClick(unitId, evt.offsetX, evt.offsetY);
+ }));
- subscription && disposeSet.add(subscription);
+ disposeSet.add(mainComponent.onPointerLeave$.subscribeEvent(() => {
+ // this._hoverManagerService.triggerMouseLeave(unitId);
+ this._active = false;
+ }));
};
handleSkeletonChange(this._sheetSkeletonManagerService.getCurrent());
@@ -59,6 +82,6 @@ export class HoverRenderController extends Disposable implements IRenderModule {
}
private _initScrollEvent() {
- this.disposeWithMe(this._scrollManagerService.validViewportScrollInfo$.subscribe(() => this._hoverManagerService.onScroll()));
+ this.disposeWithMe(this._scrollManagerService.validViewportScrollInfo$.subscribe(() => this._hoverManagerService.triggerScroll()));
}
}
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts
index 048b006f2a..8e459c2cc8 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts
@@ -23,7 +23,6 @@ import { IDialogService } from '@univerjs/ui';
import { UnitAction, UnitObject } from '@univerjs/protocol';
-import type { ISheetFontRenderExtension } from '@univerjs/engine-render';
import type { IRangeProtectionRenderCellData } from '../../views/permission/extensions/range-protection.render';
@OnLifecycle(LifecycleStages.Rendered, SheetPermissionInitController)
@@ -388,7 +387,7 @@ export class SheetPermissionInitController extends Disposable {
[UnitAction.Edit]: this._permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value ?? false,
}];
const isSkipRender = !selectionProtection[0]?.[UnitAction.View];
- const _cellData: IWorksheetProtectionRenderCellData & ISheetFontRenderExtension = { ...cell, hasWorksheetRule: true, selectionProtection };
+ const _cellData: IWorksheetProtectionRenderCellData = { ...cell, hasWorksheetRule: true, selectionProtection };
if (isSkipRender) {
delete _cellData.s;
delete _cellData.v;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
index 18cd13bd87..96824b78ed 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
@@ -84,6 +84,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
private _updateEditorPosition(params: Nullable<ISelectionWithStyle[]>) {
if (this._editorBridgeService.isVisible().visible) return;
+ if (this._rangeSelectorService.selectorModalVisible) return;
const primary = params?.[params.length - 1]?.primary;
if (primary) {
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index cf1d0b2333..d4ba613208 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -20,7 +20,7 @@ export { getEditorObject } from './basics/editor/get-editor-object';
export { SheetsScrollRenderController } from './controllers/render-controllers/scroll.render-controller';
export { deriveStateFromActiveSheet$, getCurrentRangeDisable$, getObservableWithExclusiveRange$, getCurrentExclusiveRangeInterest$ } from './controllers/menu/menu-util';
export { SheetsRenderService } from './services/sheets-render.service';
-
+export { getCustomRangePosition, calculateDocSkeletonRects, getEditingCustomRangePosition } from './services/utils/doc-skeleton-util';
export { SHEET_VIEWPORT_KEY as VIEWPORT_KEY } from './common/keys';
export { AutoFillController } from './controllers/auto-fill.controller';
export { CellCustomRenderController } from './controllers/cell-custom-render.controller';
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index a32c4e0ff8..cde69a12a5 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDisposable, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { INeedCheckDisposable, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import type { BaseObject, IBoundRectNoAngle, IRender, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
@@ -29,7 +29,7 @@ import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.ope
import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';
import { ISheetSelectionRenderService } from './selection/base-selection-render.service';
-export interface ICanvasPopup extends Pick<IPopup, 'direction' | 'excludeOutside' | 'closeOnSelfTarget' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'> {
+export interface ICanvasPopup extends Pick<IPopup, 'direction' | 'excludeOutside' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible' | 'hiddenType' | 'onClick'> {
mask?: boolean;
extraProps?: Record<string, any>;
}
@@ -46,25 +46,15 @@ export class SheetCanvasPopManagerService extends Disposable {
}
// #region attach to object
-
- private _createObjectPositionObserver(
- targetObject: BaseObject,
+ private _createPositionObserver(
+ bound: IBoundRectNoAngle,
currentRender: IRender,
skeleton: SpreadsheetSkeleton,
worksheet: Worksheet
) {
const calc = () => {
const { scene } = currentRender;
- const { left, top, width, height } = targetObject;
-
- const bound: IBoundRectNoAngle = {
- left,
- right: left + width,
- top,
- bottom: top + height,
- };
const offsetBound = transformBound2OffsetBound(bound, scene, skeleton, worksheet);
-
const canvasElement = currentRender.engine.getCanvasElement();
const canvasClientRect = canvasElement.getBoundingClientRect();
@@ -78,6 +68,7 @@ export class SheetCanvasPopManagerService extends Disposable {
top: (offsetBound.top * scaleAdjust) + canvasClientRect.top,
bottom: (offsetBound.bottom * scaleAdjust) + canvasClientRect.top,
};
+
return position;
};
@@ -104,7 +95,7 @@ export class SheetCanvasPopManagerService extends Disposable {
* @param popup popup item
* @returns disposable
*/
- attachPopupToObject(targetObject: BaseObject, popup: ICanvasPopup): IDisposable {
+ attachPopupToObject(targetObject: BaseObject, popup: ICanvasPopup): INeedCheckDisposable {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
@@ -112,6 +103,7 @@ export class SheetCanvasPopManagerService extends Disposable {
dispose: () => {
// empty
},
+ canDispose: () => true,
};
}
@@ -127,10 +119,19 @@ export class SheetCanvasPopManagerService extends Disposable {
dispose: () => {
// empty
},
+ canDispose: () => true,
};
}
+ const { left, top, width, height } = targetObject;
- const { position, position$, disposable } = this._createObjectPositionObserver(targetObject, currentRender, skeleton, worksheet);
+ const bound: IBoundRectNoAngle = {
+ left,
+ right: left + width,
+ top,
+ bottom: top + height,
+ };
+
+ const { position, position$, disposable } = this._createPositionObserver(bound, currentRender, skeleton, worksheet);
const id = this._globalPopupManagerService.addPopup({
...popup,
@@ -147,22 +148,112 @@ export class SheetCanvasPopManagerService extends Disposable {
position$.complete();
disposable.dispose();
},
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
};
}
+ // #endregion
+
+ // #region attach to position
+ attachPopupByPosition(bound: IBoundRectNoAngle, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string): Nullable<INeedCheckDisposable> {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ return null;
+ }
+
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ if ((_unitId && unitId !== _unitId) || (_subUnitId && _subUnitId !== subUnitId)) {
+ return null;
+ }
+
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({
+ sheetId: subUnitId,
+ });
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (!currentRender || !skeleton) {
+ return null;
+ }
+
+ const { position, position$, disposable } = this._createPositionObserver(bound, currentRender, skeleton, worksheet);
+ const id = this._globalPopupManagerService.addPopup({
+ ...popup,
+ unitId,
+ subUnitId,
+ anchorRect: position,
+ anchorRect$: position$,
+ canvasElement: currentRender.engine.getCanvasElement(),
+ });
+ return {
+ dispose: () => {
+ this._globalPopupManagerService.removePopup(id);
+ position$.complete();
+ disposable.dispose();
+ },
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
+ };
+ }
+ // #endregion
+
+ // #region attach to absolute position
+ attachPopupToAbsolutePosition(bound: IBoundRectNoAngle, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string) {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ return null;
+ }
+
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ if ((_unitId && unitId !== _unitId) || (_subUnitId && _subUnitId !== subUnitId)) {
+ return null;
+ }
+
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({
+ sheetId: subUnitId,
+ });
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (!currentRender || !skeleton) {
+ return null;
+ }
+
+ const position$ = new BehaviorSubject(bound);
+ const id = this._globalPopupManagerService.addPopup({
+ ...popup,
+ unitId,
+ subUnitId,
+ anchorRect: bound,
+ anchorRect$: position$.asObservable(),
+ canvasElement: currentRender.engine.getCanvasElement(),
+ });
+
+ return {
+ dispose: () => {
+ this._globalPopupManagerService.removePopup(id);
+ position$.complete();
+ },
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
+ };
+ }
// #endregion
// #region attach to cell
/**
- * attach a popup to given cell
- * @param row cell row index
- * @param col cell column index
- * @param popup popup item
- * @param viewport target viewport
- * @returns disposable
+ *
+ * @param row
+ * @param col
+ * @param popup
+ * @param _unitId
+ * @param _subUnitId
+ * @param viewport
+ * @param showOnSelectionMoving
+ * @returns
*/
- attachPopupToCell(row: number, col: number, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string, viewport?: Viewport, showOnSelectionMoving = false): Nullable<IDisposable> {
+ attachPopupToCell(row: number, col: number, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string, viewport?: Viewport, showOnSelectionMoving = false): Nullable<INeedCheckDisposable> {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
@@ -220,7 +311,12 @@ export class SheetCanvasPopManagerService extends Disposable {
}
}));
- return disposableCollection;
+ return {
+ dispose() {
+ disposableCollection.dispose();
+ },
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
+ };
}
private _createCellPositionObserver(
diff --git a/packages/sheets-ui/src/services/cell-alert-manager.service.ts b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
index d7f22e0a9c..49cb3ae784 100644
--- a/packages/sheets-ui/src/services/cell-alert-manager.service.ts
+++ b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
+import { Disposable, Inject } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { Subject } from 'rxjs';
import type { IDisposable } from '@univerjs/core';
-import { Disposable, Inject } from '@univerjs/core';
import type { ISheetLocation } from '@univerjs/sheets';
-import { IRenderManagerService } from '@univerjs/engine-render';
import { CELL_ALERT_KEY } from '../views/cell-alert';
import { SheetCanvasPopManagerService } from './canvas-pop-manager.service';
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 80e34daa0b..829ebdf070 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -14,12 +14,6 @@
* limitations under the License.
*/
-import type {
- ICellData, IDisposable,
- IMutationInfo,
- IRange,
- Nullable, Workbook, Worksheet,
-} from '@univerjs/core';
import {
createIdentifier, Disposable, ErrorService, extractPureTextFromCell, ICommandService,
ILogService,
@@ -34,7 +28,7 @@ import {
Tools,
UniverInstanceType,
} from '@univerjs/core';
-import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { IRenderManagerService } from '@univerjs/engine-render';
import {
getPrimaryForRange,
SetSelectionsOperation,
@@ -42,16 +36,28 @@ import {
} from '@univerjs/sheets';
import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, INotificationService, IPlatformService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
+import type {
+ ICellData, IDisposable,
+ IMutationInfo,
+ IRange,
+ Nullable, Workbook, Worksheet,
+} from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { rangeToDiscreteRange, virtualizeDiscreteRanges } from '../../controllers/utils/range-tools';
import { IMarkSelectionService } from '../mark-selection/mark-selection.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
-import { rangeToDiscreteRange, virtualizeDiscreteRanges } from '../../controllers/utils/range-tools';
import { createCopyPasteSelectionStyle } from '../utils/selection-util';
import { CopyContentCache, extractId, genId } from './copy-content-cache';
import { HtmlToUSMService } from './html-to-usm/converter';
+import { LarkPastePlugin } from './html-to-usm/paste-plugins/plugin-lark';
+import { UniverPastePlugin } from './html-to-usm/paste-plugins/plugin-univer';
+import { WordPastePlugin } from './html-to-usm/paste-plugins/plugin-word';
+import { COPY_TYPE } from './type';
+import { USMToHtmlService } from './usm-to-html/convertor';
+import { clipboardItemIsFromExcel, convertTextToTable, discreteRangeContainsRange, mergeSetRangeValues, rangeIntersectWithDiscreteRange } from './utils';
+import type { IDiscreteRange } from '../../controllers/utils/range-tools';
import type {
ICellDataWithSpanInfo,
IClipboardPropertyItem,
@@ -60,12 +66,6 @@ import type {
ISheetDiscreteRangeLocation,
IUniverSheetCopyDataModel,
} from './type';
-import { COPY_TYPE } from './type';
-import { USMToHtmlService } from './usm-to-html/convertor';
-import { clipboardItemIsFromExcel, convertTextToTable, discreteRangeContainsRange, mergeSetRangeValues, rangeIntersectWithDiscreteRange } from './utils';
-import { WordPastePlugin } from './html-to-usm/paste-plugins/plugin-word';
-import { LarkPastePlugin } from './html-to-usm/paste-plugins/plugin-lark';
-import { UniverPastePlugin } from './html-to-usm/paste-plugins/plugin-univer';
export const PREDEFINED_HOOK_NAME = {
DEFAULT_COPY: 'default-copy',
@@ -409,7 +409,6 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
if (copyId && this._copyContentCache.get(copyId)) {
return this._pasteInternal(copyId, pasteType);
}
-
return this._pasteExternal(html, pasteType);
}
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 6953640449..5acab6feef 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,11 +14,13 @@
* limitations under the License.
*/
-import type { IDocumentBody, IDocumentData, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
-import { DEFAULT_WORKSHEET_ROW_HEIGHT, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
+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,
@@ -26,9 +28,7 @@ import type {
IParsedCellValueByClipboard,
IUniverSheetCopyDataModel,
} from '../type';
-import { extractNodeStyle } from './parse-node-style';
import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';
-import parseToDom, { generateParagraphs } from './utils';
export interface IStyleRule {
filter: string | string[] | ((node: HTMLElement) => boolean);
@@ -107,7 +107,7 @@ export class HtmlToUSMService {
this._getCurrentSkeleton = props.getCurrentSkeleton;
}
- // eslint-disable-next-line max-lines-per-function
+ // eslint-disable-next-line max-lines-per-function, complexity
convert(html: string): IUniverSheetCopyDataModel {
const pastePlugin = HtmlToUSMService._pluginList.find((plugin) => plugin.checkPasteType(html));
if (pastePlugin) {
@@ -143,8 +143,7 @@ export class HtmlToUSMService {
const tableStrings = html.match(/<table\b[^>]*>([\s\S]*?)<\/table>/gi);
const tables: IParsedTablesInfo[] = [];
this.process(null, this._dom.childNodes!, newDocBody, tables);
- const { paragraphs, dataStream, textRuns, payloads } = newDocBody;
-
+ const { paragraphs, dataStream, textRuns, payloads, customRanges } = newDocBody;
// use paragraph to split rows
if (paragraphs) {
const starts = paragraphs.map((p) => p.startIndex + 1);
@@ -169,12 +168,23 @@ export class HtmlToUSMService {
});
}
});
+ const cellCustomRanges: ICustomRange[] = [];
+ customRanges?.forEach((c) => {
+ if (c.startIndex >= starts[i] && c.endIndex <= starts[i + 1]) {
+ cellCustomRanges.push({
+ ...c,
+ startIndex: c.startIndex - starts[i],
+ endIndex: c.endIndex - starts[i],
+ });
+ }
+ });
// set rich format
const p = this._generateDocumentDataModelSnapshot({
body: {
dataStream: cellDataStream,
textRuns: cellTextRuns,
paragraphs: generateParagraphs(cellDataStream),
+ customRanges: cellCustomRanges,
},
});
const isEmptyMatrix = Object.keys(valueMatrix.getMatrix()).length === 0;
@@ -192,11 +202,12 @@ export class HtmlToUSMService {
textRuns,
paragraphs: generateParagraphs(singleDataStream),
payloads,
+ customRanges,
};
const dataStreamLength = dataStream.length;
const textRunsLength = textRuns?.length ?? 0;
- if (!textRunsLength || (textRunsLength === 1 && textRuns![0].st === 0 && textRuns![0].ed === dataStreamLength)) {
+ if (!customRanges?.length && (!textRunsLength || (textRunsLength === 1 && textRuns![0].st === 0 && textRuns![0].ed === dataStreamLength))) {
valueMatrix.setValue(0, 0, {
v: dataStream,
});
@@ -570,6 +581,8 @@ export class HtmlToUSMService {
if (node.nodeName === 'STYLE') {
continue;
}
+ const element = node as HTMLElement;
+ const linkStart = this._processBeforeLink(element, { body: doc });
const parentStyles = parent ? this._styleCache.get(parent) : {};
const styleRule = this._styleRules.find(({ filter }) => matchFilter(node as HTMLElement, filter));
const nodeStyles = styleRule
@@ -589,10 +602,39 @@ export class HtmlToUSMService {
if (afterProcessRule) {
afterProcessRule.handler(doc, node as HTMLElement);
}
+ this._processAfterLink(element, { body: doc }, linkStart);
}
}
}
+ 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;
+ }
+
+ private _processAfterLink(node: HTMLElement, doc: Partial<IDocumentData>, start: number) {
+ const body = doc.body!;
+ 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,
+ endIndex: body.dataStream.length - 1,
+ rangeId: element.dataset.rangeid ?? generateRandomId(),
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: (element as HTMLAnchorElement).href },
+ });
+ }
+ }
+
dispose() {
this._dom = null;
this._styleCache.clear();
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 046753a41c..c6d495d523 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -37,7 +37,7 @@ import { convertTextRotation, DeviceInputEventType, IRenderManagerService } from
import { IRefSelectionsService } from '@univerjs/sheets';
import { IEditorService } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
-import type { ICellDataForSheetInterceptor, IDisposable, IPosition, ISelectionCell, Nullable, Workbook } from '@univerjs/core';
+import type { ICellData, ICellDataForSheetInterceptor, IDisposable, IPosition, ISelectionCell, Nullable, Workbook } from '@univerjs/core';
import type { Engine, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';
import type { ISheetLocation, SheetsSelectionsService } from '@univerjs/sheets';
import type { KeyCode } from '@univerjs/ui';
@@ -76,9 +76,13 @@ export interface IEditorBridgeServiceParam {
isInArrayFormulaRange?: Nullable<boolean>;
}
-const BEFORE_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation>('BEFORE_CELL_EDIT');
-const AFTER_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation>('AFTER_CELL_EDIT');
-const AFTER_CELL_EDIT_ASYNC = createInterceptorKey<Promise<Nullable<ICellDataForSheetInterceptor>>, ISheetLocation>('AFTER_CELL_EDIT_ASYNC');
+interface ISheetLocationForEditor extends ISheetLocation {
+ origin: Nullable<ICellData>;
+}
+
+const BEFORE_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocationForEditor>('BEFORE_CELL_EDIT');
+const AFTER_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocationForEditor>('AFTER_CELL_EDIT');
+const AFTER_CELL_EDIT_ASYNC = createInterceptorKey<Promise<Nullable<ICellDataForSheetInterceptor>>, ISheetLocationForEditor>('AFTER_CELL_EDIT_ASYNC');
export interface IEditorBridgeService {
currentEditCellState$: Observable<Nullable<IEditorBridgeServiceParam>>;
@@ -255,6 +259,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
subUnitId: worksheet.getSheetId(),
row: startRow,
col: startColumn,
+ origin: worksheet.getCellRaw(startRow, startColumn),
};
const cell = this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().BEFORE_CELL_EDIT)(
diff --git a/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts
index 5d0db2260d..b500c9bc51 100644
--- a/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts
+++ b/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { IDisposable, IPosition, Nullable } from '@univerjs/core';
import { createIdentifier } from '@univerjs/core';
-import type { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
+import type { IDisposable, IPosition, Nullable } from '@univerjs/core';
+import type { Observable } from 'rxjs';
export interface ICellEditorManagerParam extends Partial<IPosition> {
show: boolean;
diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts
index e126f3260a..a55f111456 100644
--- a/packages/sheets-ui/src/services/hover-manager.service.ts
+++ b/packages/sheets-ui/src/services/hover-manager.service.ts
@@ -14,37 +14,121 @@
* limitations under the License.
*/
-import type { IPosition, Nullable, Workbook } from '@univerjs/core';
-import { Disposable, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import type { ICustomRange, IParagraph, IPosition, ISelectionCellWithMergeInfo, Nullable, Workbook } from '@univerjs/core';
+import { Disposable, HorizontalAlign, IUniverInstanceService, UniverInstanceType, VerticalAlign } from '@univerjs/core';
import type { ISheetLocation } from '@univerjs/sheets';
-import { distinctUntilChanged, Subject } from 'rxjs';
+import { BehaviorSubject, distinctUntilChanged, map, Subject } from 'rxjs';
+import type { IBoundRectNoAngle, IFontCacheItem } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import { getHoverCellPosition } from '../common/utils';
import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';
import { SheetScrollManagerService } from './scroll-manager.service';
+import { calculateDocSkeletonRects } from './utils/doc-skeleton-util';
export interface IHoverCellPosition {
position: IPosition;
+ /**
+ * location of cell
+ */
location: ISheetLocation;
}
+export interface IHoverRichTextPosition extends IHoverCellPosition {
+ /**
+ * active custom range in cell, if cell is rich-text
+ */
+ customRange?: Nullable<ICustomRange>;
+ /**
+ * active bullet in cell, if cell is rich-text
+ */
+ bullet?: Nullable<IParagraph>;
+ /**
+ * rect of custom-range or bullet
+ */
+ rect?: Nullable<IBoundRectNoAngle>;
+}
+
+function calcPadding(cell: ISelectionCellWithMergeInfo, font: IFontCacheItem) {
+ const height = font.documentSkeleton.getSkeletonData()?.pages[0].height ?? 0;
+ const width = font.documentSkeleton.getSkeletonData()?.pages[0].width ?? 0;
+ const vt = font.verticalAlign;
+ const ht = font.horizontalAlign;
+
+ let paddingTop = 0;
+ switch (vt) {
+ case VerticalAlign.UNSPECIFIED:
+ case VerticalAlign.BOTTOM:
+ paddingTop = cell.mergeInfo.endY - cell.mergeInfo.startY - height;
+ break;
+ case VerticalAlign.MIDDLE:
+ paddingTop = (cell.mergeInfo.endY - cell.mergeInfo.startY - height) / 2;
+ break;
+ default:
+ break;
+ }
+
+ let paddingLeft = 0;
+ switch (ht) {
+ case HorizontalAlign.RIGHT:
+ paddingLeft = cell.mergeInfo.endX - cell.mergeInfo.startX - width;
+ break;
+ case HorizontalAlign.CENTER:
+ paddingLeft = (cell.mergeInfo.endX - cell.mergeInfo.startX - width) / 2;
+ break;
+ default:
+ break;
+ }
+
+ return {
+ paddingLeft,
+ paddingTop,
+ };
+}
+
export class HoverManagerService extends Disposable {
- private _currentCell$ = new Subject<Nullable<IHoverCellPosition>>();
+ private _currentCell$ = new BehaviorSubject<Nullable<IHoverCellPosition>>(null);
+ private _currentRichText$ = new BehaviorSubject<Nullable<IHoverRichTextPosition>>(null);
+ private _currentClickedCell$ = new Subject<IHoverCellPosition>();
// Notify when hovering over different cells
- currentCell$ = this._currentCell$.asObservable().pipe(distinctUntilChanged((
- (pre, aft) => (
- pre?.location?.unitId === aft?.location?.unitId
- && pre?.location?.subUnitId === aft?.location?.subUnitId
- && pre?.location?.row === aft?.location?.row
- && pre?.location?.col === aft?.location?.col
+ currentCell$ = this._currentCell$.asObservable().pipe(
+ distinctUntilChanged(
+ (pre, aft) => (
+ pre?.location?.unitId === aft?.location?.unitId
+ && pre?.location?.subUnitId === aft?.location?.subUnitId
+ && pre?.location?.row === aft?.location?.row
+ && pre?.location?.col === aft?.location?.col
+ )
)
- )));
+ );
+
+ // Notify when hovering over different cells and different custom range or bullet
+ currentRichText$ = this._currentRichText$.pipe(
+ distinctUntilChanged(
+ // eslint-disable-next-line complexity
+ (pre, aft) => (
+ pre?.location?.unitId === aft?.location?.unitId
+ && pre?.location?.subUnitId === aft?.location?.subUnitId
+ && pre?.location?.row === aft?.location?.row
+ && pre?.location?.col === aft?.location?.col
+ && pre?.customRange?.rangeId === aft?.customRange?.rangeId
+ && pre?.bullet?.startIndex === aft?.bullet?.startIndex
+ )
+ ),
+ map((cell) => cell && {
+ unitId: cell.location.unitId,
+ subUnitId: cell.location.subUnitId,
+ row: cell.location.row,
+ col: cell.location.col,
+ customRange: cell.customRange,
+ bullet: cell.bullet,
+ rect: cell.rect,
+ })
+ );
// Notify when mouse position changes
currentPosition$ = this._currentCell$.asObservable();
-
- private _lastPosition: Nullable<{ offsetX: number; offsetY: number }> = null;
+ currentClickedCell$ = this._currentClickedCell$.asObservable();
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@@ -59,6 +143,7 @@ export class HoverManagerService extends Disposable {
override dispose(): void {
super.dispose();
this._currentCell$.complete();
+ this._currentClickedCell$.complete();
}
private _initCellDisposableListener(): void {
@@ -67,53 +152,95 @@ export class HoverManagerService extends Disposable {
}));
}
- private _calcActiveCell() {
- if (!this._lastPosition) return;
-
- const { offsetX, offsetY } = this._lastPosition;
- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ // eslint-disable-next-line complexity
+ private _calcActiveCell(unitId: string, offsetX: number, offsetY: number) {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
if (!workbook) {
- this._currentCell$.next(null);
- return;
+ return null;
}
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
- this._currentCell$.next(null);
- return;
+ return null;
}
const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());
const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getWorksheetSkeleton(worksheet.getSheetId());
const scrollManagerService = currentRender?.with(SheetScrollManagerService);
const scrollInfo = scrollManagerService?.getCurrentScrollState();
+ const skeleton = skeletonParam?.skeleton;
- if (!skeletonParam || !scrollInfo || !currentRender) return;
+ if (!skeleton || !scrollInfo || !currentRender) return;
const hoverPosition = getHoverCellPosition(currentRender, workbook, worksheet, skeletonParam, offsetX, offsetY);
if (!hoverPosition) {
- this._currentCell$.next(null);
- return;
+ return null;
}
- const { location, position } = hoverPosition;
+ const { position, overflowLocation, location } = hoverPosition;
+
+ const font = skeleton.getFont(overflowLocation.row, overflowLocation.col);
+ let customRange: Nullable<{
+ rects: IBoundRectNoAngle[];
+ range: ICustomRange<Record<string, any>>;
+ }> = null;
+ let bullet: Nullable<{
+ rect: IBoundRectNoAngle;
+ paragraph: IParagraph;
+ }> = null;
+
+ const cell = skeleton.getCellByIndex(overflowLocation.row, overflowLocation.col);
+ const cellData = worksheet.getCell(overflowLocation.row, overflowLocation.col);
+ const { topOffset = 0, leftOffset = 0 } = cellData?.fontRenderExtension ?? {};
+
+ if (font) {
+ const { paddingLeft, paddingTop } = calcPadding(cell, font);
+ const rects = calculateDocSkeletonRects(font.documentSkeleton, paddingLeft, paddingTop);
+ const innerX = offsetX - position.startX - leftOffset;
+ const innerY = offsetY - position.startY - topOffset;
+ customRange = rects.links.find((link) => link.rects.some((rect) => rect.left <= innerX && innerX <= rect.right && (rect.top) <= innerY && innerY <= (rect.bottom)));
+ bullet = rects.checkLists.find((list) => list.rect.left <= innerX && innerX <= list.rect.right && (list.rect.top) <= innerY && innerY <= (list.rect.bottom));
+ }
+
+ const rect = customRange?.rects.pop() ?? bullet?.rect;
- this._currentCell$.next({
+ return {
location,
position,
+ overflowLocation,
+ customRange: customRange?.range,
+ bullet: bullet?.paragraph,
+ rect: rect && {
+ top: rect.top + cell.mergeInfo.startY + topOffset,
+ bottom: rect.bottom + cell.mergeInfo.startY + topOffset,
+ left: rect.left + cell.mergeInfo.startX + leftOffset,
+ right: rect.right + cell.mergeInfo.startX + leftOffset,
+ },
+ };
+ }
+
+ triggerMouseMove(unitId: string, offsetX: number, offsetY: number) {
+ const activeCell = this._calcActiveCell(unitId, offsetX, offsetY);
+ this._currentCell$.next(activeCell && {
+ location: activeCell.location,
+ position: activeCell.position,
+ });
+
+ this._currentRichText$.next(activeCell && {
+ ...activeCell,
+ location: activeCell.overflowLocation,
});
}
- onMouseMove(offsetX: number, offsetY: number) {
- this._lastPosition = {
- offsetX,
- offsetY,
- };
- this._calcActiveCell();
+ triggerClick(unitId: string, offsetX: number, offsetY: number) {
+ const activeCell = this._calcActiveCell(unitId, offsetX, offsetY);
+ if (activeCell) {
+ this._currentClickedCell$.next(activeCell);
+ }
}
- onScroll() {
+ triggerScroll() {
this._currentCell$.next(null);
}
}
diff --git a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
new file mode 100644
index 0000000000..70d6f3da13
--- /dev/null
+++ b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
@@ -0,0 +1,241 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICustomRange, Injector, IParagraph, ITextRangeParam, Workbook } from '@univerjs/core';
+import { CustomRangeType, IUniverInstanceService, PresetListType, UniverInstanceType } from '@univerjs/core';
+import type { DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DOC_VERTICAL_PADDING, getLineBounding, NodePositionConvertToCursor } from '@univerjs/docs-ui';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { IEditorBridgeService } from '../editor-bridge.service';
+
+const calcDocRangePositions = (range: ITextRangeParam, skeleton: DocumentSkeleton): IBoundRectNoAngle[] | undefined => {
+ const pageIndex = -1;
+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, pageIndex);
+ const skeletonData = skeleton.getSkeletonData();
+ let end = range.endOffset;
+ if (range.segmentId) {
+ const root = Array.from(skeletonData?.skeFooters.get(range.segmentId)?.values() ?? [])[0] ?? Array.from(skeletonData?.skeHeaders.get(range.segmentId)?.values() ?? [])[0];
+ if (root) {
+ end = Math.min(root.ed, end);
+ }
+ }
+ const endPosition = skeleton.findNodePositionByCharIndex(end, false, range.segmentId, pageIndex);
+ if (!endPosition || !startPosition) {
+ return;
+ }
+
+ const documentOffsetConfig = {
+ docsLeft: 0,
+ docsTop: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ };
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig as any, skeleton);
+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);
+ const bounds = getLineBounding(borderBoxPointGroup);
+
+ return bounds.map((rect) => ({
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left,
+ right: rect.right,
+ }));
+};
+
+const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, skeleton: DocumentSkeleton, pageIndex = -1): IBoundRectNoAngle | undefined => {
+ const start = skeleton.findPositionByGlyph(glyph, pageIndex);
+ if (!start) {
+ return;
+ }
+
+ const startPosition = { ...start, isBack: true };
+ const documentOffsetConfig = {
+ docsLeft: 0,
+ docsTop: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ };
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig as any, skeleton);
+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, startPosition);
+ const bounds = getLineBounding(borderBoxPointGroup);
+ const rect = bounds[0];
+
+ return {
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left,
+ right: rect.left,
+ };
+};
+
+const calcLinkPosition = (skeleton: DocumentSkeleton, range: ICustomRange, paddingLeft = 0, paddingTop = 0) => {
+ const rects = calcDocRangePositions({ startOffset: range.startIndex, endOffset: range.endIndex + 1, collapsed: false }, skeleton);
+ if (rects) {
+ return {
+ rects: rects.map((rect) => ({
+ top: rect.top + paddingTop,
+ bottom: rect.bottom + paddingTop,
+ left: rect.left + paddingLeft,
+ right: rect.right + paddingLeft,
+ })),
+ range,
+ };
+ }
+};
+
+const calcBulletPosition = (skeleton: DocumentSkeleton, paragraph: IParagraph, paddingLeft = 0, paddingTop = 0) => {
+ const node = skeleton.findNodeByCharIndex(paragraph.startIndex);
+ const divide = node?.parent;
+ const line = divide?.parent;
+ const column = line?.parent;
+ const targetLine = column?.lines.find((l) => l.paragraphStart && l.paragraphIndex === paragraph.startIndex);
+ const bulletNode = targetLine?.divides?.[0]?.glyphGroup?.[0];
+
+ if (!bulletNode) {
+ return;
+ }
+
+ if (!bulletNode) {
+ return;
+ }
+
+ const rect = calcDocGlyphPosition(bulletNode, skeleton);
+
+ if (!rect) {
+ return;
+ }
+
+ return {
+ rect: {
+ top: rect.top + paddingTop,
+ bottom: rect.bottom + paddingTop,
+ left: rect.left + paddingLeft,
+ right: rect.right + paddingLeft,
+ },
+ segmentId: undefined,
+ segmentPageIndex: -1,
+ paragraph,
+ };
+};
+
+export const calculateDocSkeletonRects = (docSkeleton: DocumentSkeleton, paddingLeft = 0, paddingTop = 0) => {
+ const docModel = docSkeleton.getViewModel().getDataModel();
+ const hyperLinks = docModel.getBody()?.customRanges?.filter((range) => range.rangeType === CustomRangeType.HYPERLINK) ?? [];
+ const checkLists = docModel.getBody()?.paragraphs?.filter((p) => p.bullet?.listType.indexOf(PresetListType.CHECK_LIST) === 0) ?? [];
+
+ return {
+ links: hyperLinks.map((link) => calcLinkPosition(docSkeleton, link, paddingLeft, paddingTop)!).filter(Boolean),
+ checkLists: checkLists.map((list) => calcBulletPosition(docSkeleton, list, paddingLeft, paddingTop)!).filter(Boolean),
+ };
+};
+
+export const getCustomRangePosition = (injector: Injector, unitId: string, subUnitId: string, row: number, col: number, rangeId: string) => {
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ const renderManagerService = injector.get(IRenderManagerService);
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) {
+ return null;
+ }
+
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
+ if (!worksheet) {
+ return null;
+ }
+
+ const currentRender = renderManagerService.getRenderById(workbook.getUnitId());
+ const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getWorksheetSkeleton(worksheet.getSheetId());
+
+ const skeleton = skeletonParam?.skeleton;
+
+ if (!skeleton || !currentRender) return;
+
+ const font = skeleton.getFont(row, col)?.documentSkeleton;
+
+ if (!font) {
+ return null;
+ }
+ const customRange = font.getViewModel().getBody()?.customRanges?.find((range) => range.rangeId === rangeId);
+ if (!customRange) {
+ return null;
+ }
+
+ const PADDING = DOC_VERTICAL_PADDING;
+ const rects = calcDocRangePositions({ startOffset: customRange.startIndex, endOffset: customRange.endIndex, collapsed: false }, font);
+ const cell = skeleton.getCellByIndex(row, col);
+ return {
+ rects: rects?.map((rect) => ({
+ top: rect.top + cell.startY - PADDING,
+ bottom: rect.bottom + cell.startY + PADDING,
+ left: rect.left + cell.startX,
+ right: rect.right + cell.startX,
+ })),
+ customRange,
+ label: font.getViewModel().getBody()!.dataStream.slice(customRange.startIndex + 1, customRange.endIndex),
+ };
+};
+
+export const getEditingCustomRangePosition = (injector: Injector, unitId: string, subUnitId: string, row: number, col: number, rangeId: string) => {
+ const editorBridgeService = injector.get(IEditorBridgeService);
+
+ const state = editorBridgeService.getEditCellState();
+ if (!state) {
+ return null;
+ }
+ const visible = editorBridgeService.isVisible();
+ if (!visible.visible) {
+ return null;
+ }
+ const { editorUnitId, unitId: editingUnitId, sheetId, row: editRow, column: editCol } = state;
+ if (unitId !== editingUnitId || subUnitId !== sheetId || editRow !== row || editCol !== col) {
+ return null;
+ }
+
+ const renderManagerService = injector.get(IRenderManagerService);
+ const renderer = renderManagerService.getRenderById(editorUnitId);
+ const sheetRenderer = renderManagerService.getRenderById(unitId);
+ if (!renderer || !sheetRenderer) {
+ return null;
+ }
+
+ const docSkeleton = renderer.with(DocSkeletonManagerService).getSkeleton();
+ const sheetSkeleton = sheetRenderer.with(SheetSkeletonManagerService).getWorksheetSkeleton(sheetId)?.skeleton;
+
+ if (!docSkeleton || !sheetSkeleton) {
+ return null;
+ }
+
+ const customRange = docSkeleton.getViewModel().getBody()?.customRanges?.find((range) => range.rangeId === rangeId);
+ if (!customRange) {
+ return null;
+ }
+
+ const PADDING = 4;
+ const rects = calcDocRangePositions({ startOffset: customRange.startIndex, endOffset: customRange.endIndex, collapsed: false }, docSkeleton);
+ const canvasClientRect = renderer.engine.getCanvasElement().getBoundingClientRect();
+
+ return {
+ rects: rects?.map((rect) => ({
+ top: rect.top + canvasClientRect.top - PADDING,
+ bottom: rect.bottom + canvasClientRect.top + PADDING,
+ left: rect.left + canvasClientRect.left,
+ right: rect.right + canvasClientRect.left,
+ })),
+ customRange,
+ label: docSkeleton.getViewModel().getBody()!.dataStream.slice(customRange.startIndex + 1, customRange.endIndex),
+ };
+};
diff --git a/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts b/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts
index 428e26feff..1d83b8f8f7 100644
--- a/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts
+++ b/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, ITextRange, Workbook } from '@univerjs/core';
import { CommandType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocBackScrollRenderController } from '@univerjs/docs-ui';
import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { IZenZoneService, KeyCode } from '@univerjs/ui';
+import type { IAccessor, ICommand, ITextRange, Workbook } from '@univerjs/core';
function scrollToTop(accessor: IAccessor) {
const renderManagerService = accessor.get(IRenderManagerService);
diff --git a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
index 334d51d6b8..3996d40f8a 100644
--- a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
+++ b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
@@ -196,9 +196,14 @@ export class ZenEditorController extends RxDisposable {
const body = param.documentLayoutObject.documentModel?.getBody();
const dataStream = body?.dataStream;
const paragraphs = body?.paragraphs;
+ const customBlocks = body?.customBlocks;
+ const drawings = param.documentLayoutObject.documentModel?.getDrawings();
+ const drawingsOrder = param.documentLayoutObject.documentModel?.getDrawingsOrder();
+ const customRanges = body?.customRanges;
+
let textRuns: ITextRun[] = [];
- if (dataStream == null || paragraphs == null) {
+ if (dataStream == null || (!paragraphs && !customRanges)) {
return;
}
@@ -206,7 +211,7 @@ export class ZenEditorController extends RxDisposable {
textRuns = body?.textRuns;
}
- this._syncContentAndRender(DOCS_ZEN_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns);
+ this._syncContentAndRender(DOCS_ZEN_EDITOR_UNIT_ID_KEY, dataStream, paragraphs ?? [], textRuns, customBlocks, drawings, drawingsOrder, customRanges);
// Also need to resize document and scene after sync content.
// this._autoScroll();
@@ -244,19 +249,15 @@ export class ZenEditorController extends RxDisposable {
docBody.paragraphs = paragraphs;
docBody.customBlocks = customBlocks;
docBody.customRanges = customRanges;
-
snapshot.drawings = drawings;
snapshot.drawingsOrder = drawingsOrder;
+ docBody.textRuns = textRuns;
// Need to empty textRuns(previous formula highlight) every time when sync content(change selection or edit cell or edit formula bar).
if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
docBody.textRuns = [];
}
- if (textRuns.length > 0) {
- docBody.textRuns = textRuns;
- }
-
docViewModel.reset(docDataModel);
const currentRender = this._getDocObject();
diff --git a/packages/slides-ui/src/services/slide-popup-manager.service.ts b/packages/slides-ui/src/services/slide-popup-manager.service.ts
index fd29708241..6197d0e67f 100644
--- a/packages/slides-ui/src/services/slide-popup-manager.service.ts
+++ b/packages/slides-ui/src/services/slide-popup-manager.service.ts
@@ -24,7 +24,7 @@ import type { BaseObject, IBoundRectNoAngle, IRender, Scene } from '@univerjs/en
import type { IPopup } from '@univerjs/ui';
export interface ISlideCanvasPopup extends Pick<IPopup,
- 'direction' | 'excludeOutside' | 'closeOnSelfTarget' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'
+ 'direction' | 'excludeOutside' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'
> {
mask?: boolean;
extraProps?: Record<string, any>;
diff --git a/packages/ui/src/common/menu-hidden-observable.ts b/packages/ui/src/common/menu-hidden-observable.ts
index d82f0ceceb..2d045e8fb7 100644
--- a/packages/ui/src/common/menu-hidden-observable.ts
+++ b/packages/ui/src/common/menu-hidden-observable.ts
@@ -20,7 +20,8 @@ import { Observable } from 'rxjs';
export function getMenuHiddenObservable(
accessor: IAccessor,
- targetUniverType: UniverInstanceType
+ targetUniverType: UniverInstanceType,
+ matchUnitId?: string
): Observable<boolean> {
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -29,6 +30,9 @@ export function getMenuHiddenObservable(
if (unitId == null) {
return subscriber.next(true);
}
+ if (matchUnitId && matchUnitId !== unitId) {
+ return subscriber.next(true);
+ }
const univerType = univerInstanceService.getUnitType(unitId);
subscriber.next(univerType !== targetUniverType);
diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsx
index ebc6a9033c..d934f192e0 100644
--- a/packages/ui/src/components/editor/TextEditor.tsx
+++ b/packages/ui/src/components/editor/TextEditor.tsx
@@ -82,6 +82,7 @@ export interface ITextEditorProps {
placeholder?: string; // Placeholder text.
isValueValid?: boolean; // Whether the value is valid.
+ disbaled?: boolean;
}
/**
diff --git a/packages/ui/src/components/hooks/event.ts b/packages/ui/src/components/hooks/event.ts
index 13de094d08..da9b0be965 100644
--- a/packages/ui/src/components/hooks/event.ts
+++ b/packages/ui/src/components/hooks/event.ts
@@ -16,13 +16,13 @@
import { useCallback, useRef } from 'react';
-export function useEvent<T extends (...params: any[]) => any>(func: T) {
+export function useEvent<T extends (...params: any[]) => any>(func: T | undefined) {
const funcRef = useRef(func);
funcRef.current = func;
return useCallback<T>(
((...params) => {
- return funcRef.current(...params);
+ return funcRef.current?.(...params);
}) as T,
[]
);
diff --git a/packages/ui/src/components/range-selector/RangeSelector.tsx b/packages/ui/src/components/range-selector/RangeSelector.tsx
index c4a96538e2..d71f70e427 100644
--- a/packages/ui/src/components/range-selector/RangeSelector.tsx
+++ b/packages/ui/src/components/range-selector/RangeSelector.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { IUniverInstanceService, LocaleService, ThemeService, UniverInstanceType, useDependency } from '@univerjs/core';
import { Button, Dialog, Input, Tooltip } from '@univerjs/design';
import { getRangeWithRefsString, isReferenceStringWithEffectiveColumn, serializeRange, serializeRangeWithSheet, serializeRangeWithSpreadsheet } from '@univerjs/engine-formula';
import { CloseSingle, DeleteSingle, IncreaseSingle, SelectRangeSingle } from '@univerjs/icons';
@@ -25,6 +25,7 @@ import type { IUnitRangeWithName, Nullable, Workbook } from '@univerjs/core';
import { IEditorService } from '../../services/editor/editor.service';
import { IRangeSelectorService } from '../../services/range-selector/range-selector.service';
import { TextEditor } from '../editor/TextEditor';
+import { useEvent } from '../hooks/event';
import styles from './index.module.less';
export interface IRangeSelectorProps {
@@ -42,11 +43,19 @@ export interface IRangeSelectorProps {
placeholder?: string; // Placeholder text.
className?: string;
textEditorClassName?: string;
+ onSelectorVisibleChange?: (visible: boolean) => void;
+ disableInput?: boolean;
}
-export function RangeSelector(props: IRangeSelectorProps) {
- const { onChange, id, value = '', width = 220, placeholder = '', size = 'middle', onActive, onValid, isSingleChoice = false, openForSheetUnitId, openForSheetSubUnitId, isReadonly = false, className, textEditorClassName } = props;
+const disableInputStyle: React.CSSProperties = {
+ pointerEvents: 'none',
+ cursor: 'not-allowed',
+ opacity: 0.5,
+};
+export function RangeSelector(props: IRangeSelectorProps) {
+ const { onChange, id, value = '', width = 220, placeholder = '', size = 'middle', onActive, onValid, isSingleChoice = false, openForSheetUnitId, openForSheetSubUnitId, isReadonly = false, className, textEditorClassName, onSelectorVisibleChange: _onSelectorVisibleChange, disableInput } = props;
+ const onSelectorVisibleChange = useEvent(_onSelectorVisibleChange);
const [rangeDataList, setRangeDataList] = useState<string[]>(['']);
const addNewItem = (newValue: string) => {
@@ -106,6 +115,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
const isSingleChoiceRef = useRef<Nullable<boolean>>(isSingleChoice);
const isReadonlyRef = useRef<Nullable<boolean>>(isReadonly);
+ const themeService = useDependency(ThemeService);
useEffect(() => {
const selector = selectorRef.current;
@@ -169,6 +179,16 @@ export function RangeSelector(props: IRangeSelectorProps) {
};
}, []);
+ useEffect(() => {
+ rangeSelectorService.triggerModalVisibleChange(selectorVisible);
+ }, [onSelectorVisibleChange, rangeSelectorService, selectorVisible]);
+
+ useEffect(() => {
+ return () => {
+ rangeSelectorService.triggerModalVisibleChange(false);
+ };
+ }, [rangeSelectorService]);
+
useEffect(() => {
openForSheetUnitIdRef.current = openForSheetUnitId;
openForSheetSubUnitIdRef.current = openForSheetSubUnitId;
@@ -182,6 +202,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
function handleCloseModal() {
setSelectorVisible(false);
+ onSelectorVisibleChange(false);
rangeSelectorService.setCurrentSelectorId(null);
}
@@ -195,6 +216,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
rangeSelectorService.setCurrentSelectorId(id);
setSelectorVisible(true);
+ onSelectorVisibleChange(true);
if (rangeValue.length > 0) {
if (valid) {
@@ -287,14 +309,14 @@ export function RangeSelector(props: IRangeSelectorProps) {
} else if (size === 'large') {
height = 32;
}
-
+ const theme = themeService.getCurrentTheme();
return (
<>
<div className={sClassName} ref={selectorRef} style={{ width, height }}>
- <TextEditor placeholder={placeholder} value={value} isReadonly={isReadonly} isSingleChoice={isSingleChoice} openForSheetUnitId={openForSheetUnitId} openForSheetSubUnitId={openForSheetSubUnitId} onValid={onEditorValid} onActive={onEditorActive} onChange={handleTextValueChange} id={id} onlyInputRange={true} canvasStyle={{ fontSize: 10 }} className={styles.rangeSelectorEditor} />
+ <TextEditor style={disableInput ? disableInputStyle : undefined} placeholder={placeholder} value={value} isReadonly={isReadonly} isSingleChoice={isSingleChoice} openForSheetUnitId={openForSheetUnitId} openForSheetSubUnitId={openForSheetSubUnitId} onValid={onEditorValid} onActive={onEditorActive} onChange={handleTextValueChange} id={id} onlyInputRange={true} canvasStyle={{ fontSize: 10 }} className={styles.rangeSelectorEditor} />
<Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
<button className={styles.rangeSelectorIcon} onClick={handleOpenModal}>
- <SelectRangeSingle />
+ <SelectRangeSingle style={disableInput ? { color: theme.primaryColor } : undefined} />
</button>
</Tooltip>
</div>
@@ -312,7 +334,6 @@ export function RangeSelector(props: IRangeSelectorProps) {
</footer>
)}
onClose={handleCloseModal}
-
>
<div className={clsx(styles.rangeSelectorModal, className)}>
{rangeDataList.map((item, index) => (
diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.ts
index b794f2888b..1d9f8e879f 100644
--- a/packages/ui/src/services/popup/canvas-popup.service.ts
+++ b/packages/ui/src/services/popup/canvas-popup.service.ts
@@ -21,7 +21,7 @@ import type { IBoundRectNoAngle } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
-export interface IPopup extends Pick<IRectPopupProps, 'closeOnSelfTarget' | 'direction' | 'excludeOutside' | 'onClickOutside' > {
+export interface IPopup extends Pick<IRectPopupProps, 'direction' | 'excludeOutside' | 'onClickOutside' > {
anchorRect: Nullable<IBoundRectNoAngle>;
anchorRect$: Observable<IBoundRectNoAngle>;
excludeRects?: IBoundRectNoAngle[];
@@ -34,6 +34,10 @@ export interface IPopup extends Pick<IRectPopupProps, 'closeOnSelfTarget' | 'dir
offset?: [number, number];
canvasElement: HTMLCanvasElement;
hideOnInvisible?: boolean;
+ hiddenType?: 'hide' | 'destroy';
+ onPointerEnter?: () => void;
+ onPointerLeave?: () => void;
+ onClick?: () => void;
}
export interface ICanvasPopupService {
@@ -43,6 +47,11 @@ export interface ICanvasPopupService {
popups$: Observable<[string, IPopup][]>;
get popups(): [string, IPopup][];
+
+ /**
+ * which popup is under hovering now
+ */
+ get activePopupId(): Nullable<string>;
}
export const ICanvasPopupService = createIdentifier<ICanvasPopupService>('ui.popup.service');
@@ -53,6 +62,12 @@ export class CanvasPopupService extends Disposable implements ICanvasPopupServic
readonly popups$ = this._popups$.asObservable();
get popups() { return Array.from(this._popupMap.entries()); }
+ private _activePopupId: Nullable<string> = null;
+
+ get activePopupId() {
+ return this._activePopupId;
+ }
+
private _update() {
this._popups$.next(Array.from(this._popupMap.entries()));
}
@@ -67,7 +82,17 @@ export class CanvasPopupService extends Disposable implements ICanvasPopupServic
addPopup(item: IPopup): string {
const id = Tools.generateRandomId();
- this._popupMap.set(id, item);
+ this._popupMap.set(id, {
+ ...item,
+ onPointerEnter: () => {
+ this._activePopupId = id;
+ },
+ onPointerLeave: () => {
+ if (this._activePopupId === id) {
+ this._activePopupId = null;
+ }
+ },
+ });
this._update();
return id;
}
diff --git a/packages/ui/src/services/range-selector/range-selector.service.ts b/packages/ui/src/services/range-selector/range-selector.service.ts
index a6940c9f41..5d2d2f35b1 100644
--- a/packages/ui/src/services/range-selector/range-selector.service.ts
+++ b/packages/ui/src/services/range-selector/range-selector.service.ts
@@ -17,7 +17,7 @@
import type { IDisposable, IUnitRange, Nullable } from '@univerjs/core';
import { createIdentifier, Disposable } from '@univerjs/core';
import type { Observable } from 'rxjs';
-import { Subject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
export interface IRangeSelectorRange extends IUnitRange {
sheetName: string;
@@ -32,6 +32,10 @@ export interface IRangeSelectorService {
openSelector$: Observable<unknown>;
openSelector(): void;
+
+ selectorModalVisible$: Observable<boolean>;
+ get selectorModalVisible(): boolean;
+ triggerModalVisibleChange(visible: boolean): void;
}
export class RangeSelectorService extends Disposable implements IRangeSelectorService, IDisposable {
@@ -43,6 +47,13 @@ export class RangeSelectorService extends Disposable implements IRangeSelectorSe
private readonly _openSelector$ = new Subject();
readonly openSelector$ = this._openSelector$.asObservable();
+ private readonly _selectorModalVisible$ = new BehaviorSubject(false);
+ readonly selectorModalVisible$ = this._selectorModalVisible$.asObservable();
+
+ get selectorModalVisible() {
+ return this._selectorModalVisible$.getValue();
+ }
+
setCurrentSelectorId(id: Nullable<string>) {
this._currentSelectorId = id;
}
@@ -61,6 +72,10 @@ export class RangeSelectorService extends Disposable implements IRangeSelectorSe
openSelector() {
this._openSelector$.next(null);
}
+
+ triggerModalVisibleChange(visible: boolean) {
+ this._selectorModalVisible$.next(visible);
+ }
}
export const IRangeSelectorService = createIdentifier<IRangeSelectorService>(
diff --git a/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts b/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts
index c104053a74..16ea8ea5f7 100644
--- a/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts
+++ b/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts
@@ -17,7 +17,7 @@
import { toDisposable } from '@univerjs/core';
import { type IDisposable, Inject } from '@univerjs/core';
import type { ForwardRefExoticComponent } from 'react';
-import { Subject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import { ComponentManager } from '../../common/component-manager';
import type { IZenZoneService } from './zen-zone.service';
@@ -25,8 +25,11 @@ import type { IZenZoneService } from './zen-zone.service';
export class DesktopZenZoneService implements IZenZoneService {
readonly visible$ = new Subject<boolean>();
readonly componentKey$ = new Subject<string>();
- private _visible = false;
+ private readonly _temporaryHidden$ = new BehaviorSubject<boolean>(false);
+ readonly temporaryHidden$ = this._temporaryHidden$.asObservable();
+
+ private _visible = false;
get visible() {
return this._visible;
}
@@ -35,6 +38,14 @@ export class DesktopZenZoneService implements IZenZoneService {
// super
}
+ hide(): void {
+ this._temporaryHidden$.next(true);
+ }
+
+ show(): void {
+ this._temporaryHidden$.next(false);
+ }
+
set(key: string, component: ForwardRefExoticComponent<any>): IDisposable {
this._componentManager.register(key, component);
this.componentKey$.next(key);
diff --git a/packages/ui/src/services/zen-zone/zen-zone.service.ts b/packages/ui/src/services/zen-zone/zen-zone.service.ts
index 550c0d57af..46457622c3 100644
--- a/packages/ui/src/services/zen-zone/zen-zone.service.ts
+++ b/packages/ui/src/services/zen-zone/zen-zone.service.ts
@@ -16,13 +16,14 @@
import type { IDisposable } from '@univerjs/core';
import { createIdentifier } from '@univerjs/core';
-import type { Subject } from 'rxjs';
+import type { Observable, Subject } from 'rxjs';
export const IZenZoneService = createIdentifier<IZenZoneService>('univer.zen-zone-service');
export interface IZenZoneService {
readonly visible$: Subject<boolean>;
readonly componentKey$: Subject<string>;
+ readonly temporaryHidden$: Observable<boolean>;
readonly visible: boolean;
@@ -31,4 +32,13 @@ export interface IZenZoneService {
open(): void;
close(): void;
+
+ /**
+ * temporarily hide the zen zone, often
+ */
+ hide(): void;
+ /**
+ * show the zen zone
+ */
+ show(): void;
}
diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsx
index fdcee4991d..30917be45c 100644
--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx
+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx
@@ -34,7 +34,7 @@ const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {
const excludeRects$ = useMemo(() => popup.excludeRects$?.pipe(throttleTime(0, animationFrameScheduler)), [popup.excludeRects$]);
const anchorRect = useObservable(anchorRect$, popup.anchorRect);
const excludeRects = useObservable(excludeRects$, popup.excludeRects);
- const { offset, canvasElement, hideOnInvisible = true } = popup;
+ const { offset, canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;
// We add an offset to the anchor rect to make the popup offset with the anchor.
const rectWithOffset = useMemo(() => {
@@ -65,18 +65,21 @@ const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {
}
}, [rectWithOffset, canvasElement, hideOnInvisible]);
- if (hidden || !rectWithOffset) {
+ if ((hidden && hiddenType === 'destroy') || !rectWithOffset) {
return null;
}
return (
<RectPopup
+ hidden={hidden}
anchorRect={rectWithOffset}
direction={popup.direction}
onClickOutside={popup.onClickOutside}
excludeOutside={popup.excludeOutside}
excludeRects={excludeRects}
- closeOnSelfTarget={popup.closeOnSelfTarget}
+ onPinterEnter={popup.onPointerEnter}
+ onPointerLeave={popup.onPointerLeave}
+ onClick={popup.onClick}
>
{children}
</RectPopup>
diff --git a/packages/ui/src/views/components/zen-zone/ZenZone.tsx b/packages/ui/src/views/components/zen-zone/ZenZone.tsx
index d9c317ebf3..821ba86c97 100644
--- a/packages/ui/src/views/components/zen-zone/ZenZone.tsx
+++ b/packages/ui/src/views/components/zen-zone/ZenZone.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { useDependency } from '@univerjs/core';
+import { useDependency, useObservable } from '@univerjs/core';
import clsx from 'clsx';
import React, { useEffect, useMemo, useState } from 'react';
@@ -27,7 +27,7 @@ export function ZenZone() {
const [visible, setVisible] = useState(false);
const [componentKey, setComponentKey] = useState<string>();
-
+ const hidden = useObservable(zenZoneService.temporaryHidden$);
const componentManager = useDependency(ComponentManager);
useEffect(() => {
@@ -56,5 +56,5 @@ export function ZenZone() {
}
}, [componentKey]);
- return <section className={_className}>{Component && <Component />}</section>;
+ return <section style={hidden ? { display: 'none' } : undefined} className={_className}>{Component && <Component />}</section>;
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6558e23bd8..aa052b9d66 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1552,6 +1552,12 @@ importers:
'@univerjs/sheets-formula':
specifier: workspace:*
version: link:../sheets-formula
+ '@univerjs/sheets-hyper-link':
+ specifier: workspace:*
+ version: link:../sheets-hyper-link
+ '@univerjs/sheets-hyper-link-ui':
+ specifier: workspace:*
+ version: link:../sheets-hyper-link-ui
'@univerjs/sheets-numfmt':
specifier: workspace:*
version: link:../sheets-numfmt