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(docs-ui): hyper-link support for doc (#2681)

zhangw2e80ef018d8b
diff --git a/examples/package.json b/examples/package.json
index 8edb7efa1d..50d804aaf6 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -19,6 +19,7 @@
"@univerjs/docs": "workspace:*",
"@univerjs/docs-drawing": "workspace:*",
"@univerjs/docs-drawing-ui": "workspace:*",
+ "@univerjs/docs-hyper-link-ui": "workspace:*",
"@univerjs/docs-thread-comment-ui": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
"@univerjs/drawing": "workspace:*",
diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.ts
index c21215f20b..68032fe117 100644
--- a/examples/src/docs/main.ts
+++ b/examples/src/docs/main.ts
@@ -24,7 +24,8 @@ import { UniverUIPlugin } from '@univerjs/ui';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverDebuggerPlugin } from '@univerjs/debugger';
import { UniverDocsDrawingUIPlugin } from '@univerjs/docs-drawing-ui';
-import { UniverDocsCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
+import { UniverDocsThreadCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
+import { UniverDocHyperLinkUIPlugin } from '@univerjs/docs-hyper-link-ui';
import { DEFAULT_DOCUMENT_DATA_CN } from '../data';
import { enUS, ruRU, zhCN } from '../locales';
@@ -69,7 +70,8 @@ univer.registerPlugin(UniverDocsUIPlugin, {
});
univer.registerPlugin(UniverDocsDrawingUIPlugin);
-univer.registerPlugin(UniverDocsCommentUIPlugin);
+univer.registerPlugin(UniverDocsThreadCommentUIPlugin);
+univer.registerPlugin(UniverDocHyperLinkUIPlugin);
univer.createUnit(UniverInstanceType.UNIVER_DOC, DEFAULT_DOCUMENT_DATA_CN);
diff --git a/packages/core/src/common/url.ts b/packages/core/src/common/url.ts
new file mode 100644
index 0000000000..c345c8750a
--- /dev/null
+++ b/packages/core/src/common/url.ts
@@ -0,0 +1,30 @@
+/**
+ * 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.
+ */
+
+const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
+const regex = new RegExp(expression);
+
+export function isLegalUrl(url: string) {
+ // skip number 0.1
+ if (!Number.isNaN(+url)) {
+ return false;
+ }
+
+ if (url.startsWith('http://localhost:3002') || url.startsWith('localhost:3002')) {
+ return true;
+ }
+ return Boolean(url.match(regex));
+}
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index 289b6c14d6..c5646239f7 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -388,17 +388,34 @@ export function insertCustomRanges(
for (let i = 0, len = insertBody.customRanges.length; i < len; i++) {
const customRange = insertBody.customRanges[i];
const oldCustomRange = customRangeMap[customRange.rangeId];
+
+ customRange.startIndex += currentIndex;
+ customRange.endIndex += currentIndex;
if (oldCustomRange) {
- if (insertBody.dataStream === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- oldCustomRange.endIndex = customRange.endIndex + currentIndex;
- } else if (insertBody.dataStream === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- oldCustomRange.startIndex = customRange.startIndex + currentIndex;
+ if (oldCustomRange.startIndex <= customRange.startIndex &&
+ oldCustomRange.endIndex >= customRange.endIndex) {
+ continue;
+ }
+
+ const isClosed =
+ body.dataStream[oldCustomRange.startIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_START &&
+ body.dataStream[oldCustomRange.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END;
+
+ if (isClosed) {
+ insertCustomRanges.push(customRange);
+ continue;
+ }
+ // old is start
+ if (body.dataStream[oldCustomRange.startIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
+ oldCustomRange.endIndex = customRange.endIndex;
+ continue;
+ }
+ if (body.dataStream[oldCustomRange.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
+ oldCustomRange.startIndex = customRange.startIndex;
+ continue;
}
- } else {
- insertCustomRanges.push(customRange);
- customRange.startIndex += currentIndex;
- customRange.endIndex += currentIndex;
}
+ insertCustomRanges.push(customRange);
}
customRanges.push(...insertCustomRanges);
@@ -764,7 +781,6 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
continue;
} else if (st <= startIndex && ed >= endIndex) {
const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
-
customRange.startIndex = segments[0];
customRange.endIndex = segments[1];
} else if (endIndex < st) {
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index dbfb951405..d31addbbcb 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -156,7 +156,7 @@ export class TextX {
for (const action of actions) {
if (action.t === TextXActionType.DELETE && action.body == null) {
const body = getBodySlice(doc, index, index + action.len, false);
-
+ action.len = body.dataStream.length;
action.body = body;
}
@@ -167,6 +167,7 @@ export class TextX {
...body,
dataStream: '',
};
+ action.len = body.dataStream.length;
}
invertibleActions.push(action);
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index c9f9b0535d..eaf8745b9b 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -16,7 +16,8 @@
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
-import type { ICustomDecoration, ICustomRange, IDocumentBody, IParagraph, ITextRun } from '../../../types/interfaces/i-document-data';
+import type { ICustomDecoration, IDocumentBody, IParagraph, ITextRun } from '../../../types/interfaces/i-document-data';
+import { DataStreamTreeTokenType } from '../types';
import type { IRetainAction } from './action-types';
import { coverTextRuns } from './apply-utils/update-apply';
@@ -93,44 +94,111 @@ export function getBodySlice(
}));
}
- docBody.customRanges = getDeleteCustomRange(body, startOffset, endOffset);
docBody.customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);
+ const { customRanges } = getCustomRangeSlice(body, startOffset, endOffset);
+ docBody.customRanges = customRanges;
return docBody;
}
-export function getDeleteCustomRange(body: IDocumentBody, startOffset: number, endOffset: number) {
- const { customRanges = [] } = body;
+export function normalizeBody(body: IDocumentBody): IDocumentBody {
+ const { dataStream, textRuns, paragraphs, customRanges, customDecorations } = body;
+ let leftOffset = 0;
+ let rightOffset = 0;
- const deletedCustomRange: ICustomRange[] = [];
- customRanges.forEach((range) => {
- // custom-range contain slice-range
- if (startOffset <= range.startIndex && endOffset > range.endIndex) {
- const copy = Tools.deepClone(range);
- deletedCustomRange.push({
- ...copy,
- startIndex: copy.startIndex - startOffset,
- endIndex: copy.endIndex - startOffset,
- });
- // delete custom-range start tag, only happened in cancel custom-range
- } else if (startOffset <= range.startIndex && endOffset > range.startIndex) {
- const copy = Tools.deepClone(range);
- deletedCustomRange.push({
- ...copy,
- startIndex: copy.startIndex - startOffset,
- endIndex: copy.startIndex - startOffset,
- });
- // slice-range contain custom-range
- } else if (endOffset > range.endIndex && range.endIndex >= startOffset) {
- const copy = Tools.deepClone(range);
- deletedCustomRange.push({
- ...copy,
- startIndex: copy.endIndex - startOffset,
- endIndex: copy.endIndex - startOffset,
- });
+ customRanges?.forEach((range) => {
+ if (range.startIndex < 0) {
+ leftOffset = Math.max(leftOffset, -range.startIndex);
}
+
+ if (range.endIndex > dataStream.length - 1) {
+ rightOffset = Math.max(rightOffset, range.endIndex - dataStream.length + 1);
+ }
+ });
+
+ const newData = `${DataStreamTreeTokenType.CUSTOM_RANGE_START.repeat(leftOffset)}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END.repeat(rightOffset)}`;
+
+ if (textRuns) {
+ if (textRuns[0]) {
+ textRuns[0].st = textRuns[0].st - leftOffset;
+ }
+
+ if (textRuns[textRuns.length - 1]) {
+ textRuns[textRuns.length - 1].ed = textRuns[textRuns.length - 1].ed + rightOffset;
+ }
+ }
+
+ textRuns?.forEach((textRun) => {
+ textRun.st += leftOffset;
+ textRun.ed += leftOffset;
});
- return deletedCustomRange;
+ paragraphs?.forEach((p) => {
+ p.startIndex += leftOffset;
+ });
+ customRanges?.forEach((range) => {
+ range.startIndex += leftOffset;
+ range.endIndex += leftOffset;
+ });
+
+ customDecorations?.forEach((d) => {
+ d.startIndex += leftOffset;
+ d.endIndex += rightOffset;
+ });
+
+ return {
+ ...body,
+ dataStream: newData,
+ textRuns,
+ paragraphs,
+ customRanges,
+ customDecorations,
+ };
+}
+
+export function getCustomRangeSlice(body: IDocumentBody, startOffset: number, endOffset: number) {
+ const { customRanges = [] } = body;
+ let leftOffset = 0;
+ let rightOffset = 0;
+ const relativeCustomRanges = customRanges
+ .filter((customRange) => Math.max(customRange.startIndex, startOffset) <= Math.min(customRange.endIndex, endOffset - 1))
+ .map((range) => ({
+ ...range,
+ startIndex: range.startIndex,
+ endIndex: range.endIndex,
+ }));
+
+ if (relativeCustomRanges.length) {
+ relativeCustomRanges.forEach((customRange) => {
+ if (customRange.startIndex < startOffset) {
+ leftOffset += 1;
+ }
+ if (customRange.endIndex > (endOffset - 1)) {
+ rightOffset += 1;
+ }
+ });
+
+ for (let i = 0; i < leftOffset; i++) {
+ const range = relativeCustomRanges[i];
+ range.startIndex = startOffset - leftOffset + i;
+ }
+ if (rightOffset) {
+ const sorted = [...relativeCustomRanges].sort((pre, aft) => aft.endIndex - pre.endIndex);
+ for (let i = 0; i < rightOffset; i++) {
+ const range = sorted[i];
+ range.endIndex = endOffset + rightOffset - i - 1;
+ }
+ }
+ }
+
+ return {
+ customRanges: relativeCustomRanges.map((range) => ({
+ ...range,
+ startIndex: range.startIndex - startOffset,
+ endIndex: range.endIndex - startOffset,
+ })),
+ leftOffset,
+ rightOffset,
+ };
}
export function getCustomDecorationSlice(body: IDocumentBody, startOffset: number, endOffset: number) {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1979f06f3b..4a0dee713e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -179,11 +179,12 @@ export { DataValidationType } from './types/enum/data-validation-type';
export { DataValidationStatus } from './types/enum/data-validation-status';
export type { IPermissionTypes, WorkbookPermissionPointConstructor } from './services/permission/type';
export { PermissionService } from './services/permission/permission.service';
-
export { AuthzIoLocalService } from './services/authz-io/authz-io-local.service';
export { IAuthzIoService } from './services/authz-io/type';
export { createDefaultUser } from './services/user-manager/const';
export { skipParseTagNames } from './types/const/clipboard';
+export { normalizeBody, getCustomRangeSlice, getCustomDecorationSlice } from './docs/data-model/text-x/utils';
+export { updateAttributeByDelete } from './docs/data-model/text-x/apply-utils/delete-apply';
+export { updateAttributeByInsert } from './docs/data-model/text-x/apply-utils/insert-apply';
export { nameCharacterCheck } from './shared/name';
installShims();
-
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index 6388e41a52..eb4044f7be 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -16,6 +16,7 @@
import { customAlphabet, nanoid } from 'nanoid';
+import { isLegalUrl } from '../common/url';
import type { Class, IKeyValue } from './types';
const rmsPrefix = /^-ms-/;
@@ -442,6 +443,10 @@ export class Tools {
return /iPhone/i.test(navigator.userAgent);
}
+ static isLegalUrl(url: string): boolean {
+ return isLegalUrl(url);
+ }
+
static itCount(count: number): Function {
return (callback: Function) => {
for (let i = 0; i < count; i++) {
diff --git a/packages/design/src/components/popup/RectPopup.tsx b/packages/design/src/components/popup/RectPopup.tsx
index 71da37b5ef..1ff0edc410 100644
--- a/packages/design/src/components/popup/RectPopup.tsx
+++ b/packages/design/src/components/popup/RectPopup.tsx
@@ -34,7 +34,7 @@ export interface IRectPopupProps {
* the anchor element bounding rect
*/
anchorRect: IAbsolutePosition;
-
+ excludeRects?: IAbsolutePosition[];
direction?: 'vertical' | 'horizontal' | 'left' | 'top' | 'right' | 'left' | 'bottom';
// #region closing behavior
@@ -92,13 +92,15 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbe
};
function RectPopup(props: IRectPopupProps) {
- const { children, anchorRect, direction = 'vertical', onClickOutside, excludeOutside } = props;
+ const { children, anchorRect, direction = 'vertical', onClickOutside, excludeOutside, excludeRects } = props;
const nodeRef = useRef<HTMLElement>(null);
const clickOtherFn = useEvent(onClickOutside ?? (() => { /* empty */ }));
const [position, setPosition] = useState<Partial<IAbsolutePosition>>({
top: -9999,
left: -9999,
});
+ const excludeRectsRef = useRef(excludeRects);
+ excludeRectsRef.current = excludeRects;
const style = useMemo(() => ({ ...position }), [position]);
useEffect(() => {
@@ -145,9 +147,13 @@ function RectPopup(props: IRectPopupProps) {
}
const x = e.offsetX;
const y = e.offsetY;
- if (x <= anchorRect.right && x >= anchorRect.left && y <= anchorRect.bottom && y >= anchorRect.top) {
- return;
+ const rects = [anchorRect, ...excludeRectsRef.current ?? []];
+ for (const rect of rects) {
+ if (x <= rect.right && x >= rect.left && y <= rect.bottom && y >= rect.top) {
+ return;
+ }
}
+
clickOtherFn(e);
};
diff --git a/packages/docs-hyper-link-ui/README-zh.md b/packages/docs-hyper-link-ui/README-zh.md
new file mode 100644
index 0000000000..0754153448
--- /dev/null
+++ b/packages/docs-hyper-link-ui/README-zh.md
@@ -0,0 +1,28 @@
+# @univerjs/docs-hyper-link-ui
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/docs-hyper-link-ui)](https://npmjs.org/packages/@univerjs/docs-hyper-link-ui)
+[![license](https://img.shields.io/npm/l/@univerjs/docs-hyper-link-ui)](https://img.shields.io/npm/l/@univerjs/docs-hyper-link-ui)
+
+## 简介
+
+`@univerjs/docs-hyper-link-ui` 提供了 Univer Docs 的链接功能。
+
+
+## 使用指南
+
+### 安装
+
+```shell
+# 使用 npm
+npm install @univerjs/docs-hyper-link-ui
+
+# 使用 pnpm
+pnpm add @univerjs/docs-hyper-link-ui
+```
+
+### 使用
+```js
+import { UniverDocHyperLinkUIPlugin} from '@univerjs/docs-hyper-link-ui';
+
+univer.registerPlugin(UniverDocHyperLinkUIPlugin);
+```
diff --git a/packages/docs-hyper-link-ui/README.md b/packages/docs-hyper-link-ui/README.md
new file mode 100644
index 0000000000..e8028d848b
--- /dev/null
+++ b/packages/docs-hyper-link-ui/README.md
@@ -0,0 +1,28 @@
+# @univerjs/docs-hyper-link-ui
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/docs-hyper-link-ui)](https://npmjs.org/packages/@univerjs/docs-hyper-link-ui )
+[![license](https://img.shields.io/npm/l/@univerjs/docs-hyper-link-ui)](https://img.shields.io/npm/l/@univerjs/sheets- thread-comment)
+
+## Introduction
+
+`@univerjs/docs-hyper-link-ui` provides the link function of Univer Docs.
+
+
+## Usage
+
+### Install
+
+```shell
+# Use npm
+npm install @univerjs/docs-hyper-link-ui
+
+# Use pnpm
+pnpm add @univerjs/docs-hyper-link-ui
+```
+
+### use
+```js
+import { UniverDocHyperLinkUIPlugin} from '@univerjs/docs-hyper-link-ui';
+
+univer.registerPlugin(UniverDocHyperLinkUIPlugin);
+```
diff --git a/packages/docs-hyper-link-ui/package.json b/packages/docs-hyper-link-ui/package.json
new file mode 100644
index 0000000000..1536f8d8e2
--- /dev/null
+++ b/packages/docs-hyper-link-ui/package.json
@@ -0,0 +1,107 @@
+{
+ "name": "@univerjs/docs-hyper-link-ui",
+ "version": "0.1.14",
+ "private": false,
+ "description": "Univer thread comment plugin",
+ "author": "DreamNum <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*",
+ "./locale/*": "./src/locale/*.ts"
+ },
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "lint:types": "tsc --noEmit",
+ "build": "tsc && vite build"
+ },
+ "peerDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-hyper-link": "workspace:*",
+ "@univerjs/docs-ui": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/icons": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.5",
+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/icons": "^0.1.58",
+ "@univerjs/thread-comment": "workspace:*",
+ "@univerjs/thread-comment-ui": "workspace:*"
+ },
+ "devDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/docs-hyper-link": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/icons": "workspace:*",
+ "@univerjs/shared": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.5",
+ "clsx": "^2.1.1",
+ "react": "18.3.1",
+ "rxjs": "^7.8.1",
+ "typescript": "^5.4.5",
+ "vite": "^5.2.12",
+ "vitest": "^1.6.0"
+ },
+ "univerSpace": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+}
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
new file mode 100644
index 0000000000..1268a94ff8
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
@@ -0,0 +1,60 @@
+/**
+ * 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 { CommandType, CustomRangeType, type ICommand, ICommandService, sequenceExecuteAsync, Tools } from '@univerjs/core';
+import { addCustomRangeBySelectionFactory } from '@univerjs/docs';
+import { AddDocHyperLinkMutation } from '@univerjs/docs-hyper-link';
+
+export interface IAddDocHyperLinkCommandParams {
+ payload: string;
+ unitId: string;
+}
+
+export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'docs.command.add-hyper-link',
+ async handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+ const { payload, unitId } = params;
+ const commandService = accessor.get(ICommandService);
+ const id = Tools.generateRandomId();
+ const doMutation = addCustomRangeBySelectionFactory(
+ accessor,
+ {
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ }
+ );
+ if (doMutation) {
+ const commentMutation = {
+ id: AddDocHyperLinkMutation.id,
+ params: {
+ unitId,
+ link: {
+ payload,
+ id,
+ },
+ },
+ };
+
+ return (await sequenceExecuteAsync([commentMutation, doMutation], commandService)).result;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts
new file mode 100644
index 0000000000..286f8c0f83
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts
@@ -0,0 +1,49 @@
+/**
+ * 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 { ICommand } from '@univerjs/core';
+import { CommandType, ICommandService } from '@univerjs/core';
+import { deleteCustomRangeFactory } from '@univerjs/docs';
+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';
+
+export interface IDeleteDocHyperLinkMutationParams {
+ unitId: string;
+ linkId: string;
+}
+
+export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationParams> = {
+ type: CommandType.COMMAND,
+ id: 'docs.command.delete-hyper-link',
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+ const { unitId, linkId } = params;
+ const commandService = accessor.get(ICommandService);
+ const hyperLinkModel = accessor.get(DocHyperLinkModel);
+ const link = hyperLinkModel.getLink(unitId, linkId);
+ if (!link) {
+ return false;
+ }
+
+ const doMutation = deleteCustomRangeFactory(accessor, { unitId, rangeId: linkId });
+ if (!doMutation) {
+ return false;
+ }
+
+ return commandService.executeCommand(doMutation.id, doMutation.params);
+ },
+};
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
new file mode 100644
index 0000000000..e0ea2eb9e4
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType, type ICommand, ICommandService } from '@univerjs/core';
+import { UpdateDocHyperLinkMutation } from '@univerjs/docs-hyper-link';
+
+export interface IUpdateDocHyperLinkCommandParams {
+ unitId: string;
+ linkId: string;
+ payload: string;
+}
+
+export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParams> = {
+ id: 'docs.command.update-hyper-link',
+ type: CommandType.COMMAND,
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ return commandService.executeCommand(UpdateDocHyperLinkMutation.id, params);
+ },
+};
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
new file mode 100644
index 0000000000..fbf7a39c9c
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 { DocumentDataModel, ICommand } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { TextSelectionManagerService } from '@univerjs/docs';
+import type { IAccessor } from '@wendellhu/redi';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+
+export const shouldDisableAddLink = (accessor: IAccessor) => {
+ const textSelectionService = accessor.get(TextSelectionManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const activeRange = textSelectionService.getActiveRange();
+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!doc || !activeRange || activeRange.collapsed) {
+ return (true);
+ return;
+ }
+
+ const paragraphs = doc.getBody()?.paragraphs;
+ if (!paragraphs) {
+ return (true);
+ return;
+ }
+
+ 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);
+ return;
+ }
+
+ if (p.startIndex > activeRange.endOffset) {
+ break;
+ }
+ }
+
+ return (false);
+};
+
+export interface IShowDocHyperLinkEditPopupOperationParams {
+ link?: {
+ unitId: string;
+ linkId: string;
+ rangeIndex: number;
+ };
+}
+
+export const ShowDocHyperLinkEditPopupOperation: ICommand<IShowDocHyperLinkEditPopupOperationParams> = {
+ type: CommandType.OPERATION,
+ id: 'docs.operation.show-hyper-link-edit-popup',
+ handler(accessor, params) {
+ const linkInfo = params?.link;
+ if (shouldDisableAddLink(accessor) && !linkInfo) {
+ return false;
+ }
+ const hyperLinkService = accessor.get(DocHyperLinkPopupService);
+ hyperLinkService.showEditPopup(linkInfo);
+ return true;
+ },
+};
diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts
new file mode 100644
index 0000000000..344a767139
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts
@@ -0,0 +1,90 @@
+/**
+ * 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 { DocumentDataModel } from '@univerjs/core';
+import { CustomRangeType, Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, Tools, UniverInstanceType, updateAttributeByDelete } from '@univerjs/core';
+import { TextSelectionManagerService } from '@univerjs/docs';
+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';
+import { IDocClipboardService } from '@univerjs/docs-ui';
+import { Inject } from '@wendellhu/redi';
+
+@OnLifecycle(LifecycleStages.Ready, DocHyperLinkClipboardController)
+export class DocHyperLinkClipboardController extends Disposable {
+ constructor(
+ @Inject(IDocClipboardService) private readonly _docClipboardService: IDocClipboardService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(DocHyperLinkModel) private readonly _hyperLinkModel: DocHyperLinkModel,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ ) {
+ super();
+
+ this._initClipboard();
+ }
+
+ private _initClipboard() {
+ this.disposeWithMe(this._docClipboardService.addClipboardHook({
+ onBeforePaste: (body) => {
+ const doc = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!doc) {
+ return body;
+ }
+ const activeRange = this._textSelectionManagerService.getActiveRange();
+ const customRanges = doc.getBody()?.customRanges;
+ if (!customRanges?.length) {
+ return body;
+ }
+ const matchedRange = activeRange ?
+ customRanges.find(
+ (range) =>
+ range.rangeType === CustomRangeType.HYPERLINK &&
+ range.startIndex <= activeRange.startOffset &&
+ range.endIndex >= activeRange.endOffset - 1
+ )
+ : null;
+ // insert into current link inside
+ if (matchedRange) {
+ const { customRanges = [], ...extBody } = body;
+ const deleteRanges = customRanges.filter((range) => range.rangeType === CustomRangeType.HYPERLINK);
+ const deleteIndexes = deleteRanges.map((i) => [i.startIndex, i.endIndex]).flat().sort((pre, aft) => pre - aft);
+ const bodyWithoutLink = {
+ ...extBody,
+ customRanges: customRanges.filter((range) => range.rangeType !== CustomRangeType.HYPERLINK),
+ };
+ for (let i = 0; i < deleteIndexes.length; i++) {
+ updateAttributeByDelete(bodyWithoutLink, 1, deleteIndexes[i] - i);
+ }
+ return bodyWithoutLink;
+ } else {
+ const customRangeIds = new Set(customRanges.map((i) => i.rangeType === CustomRangeType.HYPERLINK && i.rangeId));
+ body.customRanges?.forEach((range) => {
+ if (range.rangeType === CustomRangeType.HYPERLINK && customRangeIds.has(range.rangeId)) {
+ const link = this._hyperLinkModel.getLink(doc.getUnitId(), range.rangeId);
+ if (link) {
+ const newId = Tools.generateRandomId();
+ this._hyperLinkModel.addLink(doc.getUnitId(), {
+ payload: link.payload,
+ id: newId,
+ });
+ range.rangeId = newId;
+ }
+ }
+ });
+ }
+ return body;
+ },
+ }));
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
new file mode 100644
index 0000000000..4cd02461d2
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
@@ -0,0 +1,67 @@
+/**
+ * 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 { DocumentDataModel } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import { SetTextSelectionsOperation } from '@univerjs/docs';
+import { Inject } from '@wendellhu/redi';
+import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
+
+@OnLifecycle(LifecycleStages.Ready, DocHyperLinkSelectionController)
+export class DocHyperLinkSelectionController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(DocHyperLinkPopupService) private readonly _docHyperLinkService: DocHyperLinkPopupService
+ ) {
+ super();
+
+ this._initSelectionChange();
+ }
+
+ private _initSelectionChange() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetTextSelectionsOperation.id) {
+ const params = commandInfo.params as ISetTextSelectionsOperationParams;
+ const { unitId, ranges } = params;
+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ const primary = ranges[0];
+ if (primary && doc) {
+ const { startOffset, endOffset, collapsed } = primary;
+ const customRanges = doc.getBody()?.customRanges;
+ if (collapsed) { // cursor
+ const index = customRanges?.findIndex((value) => (value.startIndex) < startOffset && value.endIndex > endOffset - 1) ?? -1;
+ if (index > -1) {
+ const customRange = customRanges![index];
+ this._docHyperLinkService.showInfoPopup({ unitId, linkId: customRange.rangeId, rangeIndex: index });
+ return;
+ }
+ } else { // range
+ if (customRanges?.find((value) => value.startIndex <= startOffset && value.endIndex >= (endOffset - 1))) {
+ return;
+ }
+ }
+ }
+
+ this._docHyperLinkService.hideInfoPopup();
+ this._docHyperLinkService.hideEditPopup();
+ }
+ })
+ );
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/controllers/menu.ts b/packages/docs-hyper-link-ui/src/controllers/menu.ts
new file mode 100644
index 0000000000..a928a6efee
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/menu.ts
@@ -0,0 +1,56 @@
+/**
+ * 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 { UniverInstanceType } from '@univerjs/core';
+import type { IMenuButtonItem, IShortcutItem } from '@univerjs/ui';
+import { getMenuHiddenObservable, KeyCode, MenuGroup, MenuItemType, MenuPosition, MetaKeys } from '@univerjs/ui';
+import { debounceTime, Observable } from 'rxjs';
+import { TextSelectionManagerService } from '@univerjs/docs';
+import { whenDocAndEditorFocused } from '@univerjs/docs-ui';
+import { shouldDisableAddLink, ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
+
+export const DOC_LINK_ICON = 'doc-hyper-link-icon';
+
+export function AddHyperLinkMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: ShowDocHyperLinkEditPopupOperation.id,
+ group: MenuGroup.TOOLBAR_LAYOUT,
+ type: MenuItemType.BUTTON,
+ icon: DOC_LINK_ICON,
+ title: 'docLink.menu.tooltip',
+ tooltip: 'docLink.menu.tooltip',
+ positions: [MenuPosition.TOOLBAR_START, MenuPosition.CONTEXT_MENU],
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ disabled$: new Observable(function (subscribe) {
+ const textSelectionService = accessor.get(TextSelectionManagerService);
+ const observer = textSelectionService.textSelection$.pipe(debounceTime(16)).subscribe(() => {
+ subscribe.next(shouldDisableAddLink(accessor));
+ });
+
+ return () => {
+ observer.unsubscribe();
+ };
+ }),
+ };
+}
+
+export const addLinkShortcut: IShortcutItem = {
+ id: ShowDocHyperLinkEditPopupOperation.id,
+ binding: MetaKeys.CTRL_COMMAND | KeyCode.K,
+ description: 'docLink.menu.tooltip',
+ preconditions: whenDocAndEditorFocused,
+};
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
new file mode 100644
index 0000000000..258a1b8ea9
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
@@ -0,0 +1,53 @@
+/**
+ * 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 { DocumentDataModel } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { DOC_INTERCEPTOR_POINT, DocInterceptorService } from '@univerjs/docs';
+import { Inject } from '@wendellhu/redi';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+
+export class DocHyperLinkRenderController extends Disposable implements IRenderModule {
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @Inject(DocInterceptorService) private readonly _docInterceptorService: DocInterceptorService,
+ @Inject(DocHyperLinkPopupService) private readonly _hyperLinkService: DocHyperLinkPopupService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init() {
+ this._docInterceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {
+ handler: (data, pos, next) => {
+ if (!data) {
+ return next(data);
+ }
+ const { unitId } = pos;
+ const activeLink = this._hyperLinkService.editing;
+ const { linkId, unitId: linkUnitId } = activeLink || {};
+
+ const isActive = linkUnitId === unitId && data.rangeId === linkId;
+ return next({
+ ...data,
+ active: isActive,
+ });
+ },
+ });
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts b/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts
new file mode 100644
index 0000000000..9be86e868e
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts
@@ -0,0 +1,84 @@
+/**
+ * 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 { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { MenuConfig } from '@univerjs/ui';
+import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';
+import { Inject, Injector } from '@wendellhu/redi';
+import { LinkSingle } from '@univerjs/icons';
+import { DocHyperLinkEdit } from '../views/hyper-link-edit';
+import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';
+import { UpdateDocHyperLinkCommand } from '../commands/commands/update-link.command';
+import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
+import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
+import { DocLinkPopup } from '../views/hyper-link-popup';
+import { AddHyperLinkMenuItemFactory, addLinkShortcut, DOC_LINK_ICON } from './menu';
+
+export interface IDocHyperLinkUIConfig {
+ menu: MenuConfig;
+}
+
+@OnLifecycle(LifecycleStages.Starting, DocHyperLinkUIController)
+export class DocHyperLinkUIController extends Disposable {
+ constructor(
+ protected _config: IDocHyperLinkUIConfig,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IMenuService private readonly _menuService: IMenuService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @IShortcutService private readonly _shortcutService: IShortcutService
+ ) {
+ super();
+
+ this._initComponents();
+ this._initCommands();
+ this._initMenus();
+ this._initShortcut();
+ }
+
+ private _initComponents() {
+ ([
+ [DocHyperLinkEdit, DocHyperLinkEdit.componentKey],
+ [DocLinkPopup, DocLinkPopup.componentKey],
+ [LinkSingle, DOC_LINK_ICON],
+ ] as const).forEach(([comp, key]) => {
+ this._componentManager.register(key, comp);
+ });
+ }
+
+ private _initCommands() {
+ [
+ AddDocHyperLinkCommand,
+ UpdateDocHyperLinkCommand,
+ DeleteDocHyperLinkCommand,
+ ShowDocHyperLinkEditPopupOperation,
+ ].forEach((command) => {
+ this._commandService.registerCommand(command);
+ });
+ }
+
+ private _initShortcut() {
+ [addLinkShortcut].forEach((shortcut) => {
+ this._shortcutService.registerShortcut(shortcut);
+ });
+ }
+
+ private _initMenus() {
+ [AddHyperLinkMenuItemFactory].forEach((menuFactory) => {
+ this.disposeWithMe(this._menuService.addMenuItem(menuFactory(this._injector), {}));
+ });
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/index.ts b/packages/docs-hyper-link-ui/src/index.ts
new file mode 100644
index 0000000000..f9fe061104
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/index.ts
@@ -0,0 +1,19 @@
+/**
+ * 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 { UniverDocHyperLinkUIPlugin } from './plugin';
+
+// export {} from './'
diff --git a/packages/docs-hyper-link-ui/src/locale/en-US.ts b/packages/docs-hyper-link-ui/src/locale/en-US.ts
new file mode 100644
index 0000000000..4ce664e6e4
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/locale/en-US.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 zhCN from './zh-CN';
+
+const enUS: typeof zhCN = {
+ docLink: {
+ edit: {
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ title: 'Link',
+ address: 'Link address',
+ placeholder: 'Please input a link url',
+ addressError: 'Url is illegal!',
+ },
+ info: {
+ copy: 'Copy',
+ edit: 'Edit',
+ cancel: 'Cancel link',
+ coped: 'Link copied to clipboard',
+ },
+ menu: {
+ tooltip: 'Add link',
+ },
+ },
+};
+
+export default enUS;
diff --git a/packages/docs-hyper-link-ui/src/locale/ru-RU.ts b/packages/docs-hyper-link-ui/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..02858dc350
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/locale/ru-RU.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 zhCN from './zh-CN';
+
+const ruRU: typeof zhCN = {
+ docLink: {
+ edit: {
+ confirm: 'Подтвердить',
+ cancel: 'Отменить',
+ title: 'Ссылка',
+ address: 'Адрес ссылки',
+ placeholder: 'Пожалуйста, введите URL ссылки',
+ addressError: 'URL некорректен!',
+ },
+ info: {
+ copy: 'Копировать',
+ edit: 'Редактировать',
+ cancel: 'Отменить ссылку',
+ coped: 'Link copied to clipboard',
+ },
+ menu: {
+ tooltip: 'Добавить ссылку',
+ },
+ },
+};
+
+export default ruRU;
diff --git a/packages/docs-hyper-link-ui/src/locale/zh-CN.ts b/packages/docs-hyper-link-ui/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..8c3742c7f2
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/locale/zh-CN.ts
@@ -0,0 +1,39 @@
+/**
+ * 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.
+ */
+
+const zhCN = {
+ docLink: {
+ edit: {
+ confirm: '确认',
+ cancel: '取消',
+ title: '链接',
+ address: '链接地址',
+ placeholder: '请输入合法的链接',
+ addressError: '请输入合法的链接',
+ },
+ info: {
+ copy: '复制',
+ edit: '编辑',
+ cancel: '取消链接',
+ coped: '链接已被复制到剪贴板',
+ },
+ menu: {
+ tooltip: '添加链接',
+ },
+ },
+};
+
+export default zhCN;
diff --git a/packages/docs-hyper-link-ui/src/plugin.ts b/packages/docs-hyper-link-ui/src/plugin.ts
new file mode 100644
index 0000000000..40885a5315
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/plugin.ts
@@ -0,0 +1,69 @@
+/**
+ * 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 { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { UniverDocHyperLinkPlugin } from '@univerjs/docs-hyper-link';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { DOC_HYPER_LINK_UI_PLUGIN } from './types/const';
+import type { IDocHyperLinkUIConfig } from './controllers/ui.controller';
+import { DocHyperLinkUIController } from './controllers/ui.controller';
+import { DocHyperLinkPopupService } from './services/hyper-link-popup.service';
+import { DocHyperLinkSelectionController } from './controllers/doc-hyper-link-selection.controller';
+import { DocHyperLinkRenderController } from './controllers/render-controllers/render.controller';
+import { DocHyperLinkClipboardController } from './controllers/doc-hyper-link-clipboard.controller';
+
+@DependentOn(UniverDocHyperLinkPlugin)
+export class UniverDocHyperLinkUIPlugin extends Plugin {
+ static override pluginName = DOC_HYPER_LINK_UI_PLUGIN;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private _config: IDocHyperLinkUIConfig = { menu: {} },
+ @Inject(Injector) protected override _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService
+ ) {
+ super();
+ }
+
+ override onStarting(injector: Injector): void {
+ const deps: Dependency[] = [
+ [DocHyperLinkPopupService],
+ [DocHyperLinkUIController,
+ {
+ useFactory: () => this._injector.createInstance(DocHyperLinkUIController, this._config),
+ },
+ ],
+ [DocHyperLinkSelectionController],
+ [DocHyperLinkClipboardController],
+ ];
+
+ deps.forEach((dep) => {
+ injector.add(dep);
+ });
+ }
+
+ override onRendered(): void {
+ this._initRenderModule();
+ }
+
+ private _initRenderModule() {
+ [DocHyperLinkRenderController].forEach((dep) => {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);
+ });
+ }
+}
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
new file mode 100644
index 0000000000..08c610264e
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -0,0 +1,147 @@
+/**
+ * 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 { DocumentDataModel, ITextRange, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { TextSelectionManagerService } from '@univerjs/docs';
+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import type { IDisposable } from '@wendellhu/redi';
+import { Inject } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';
+import { DocHyperLinkEdit } from '../views/hyper-link-edit';
+import { DocLinkPopup } from '../views/hyper-link-popup';
+
+export interface ILinkInfo {
+ unitId: string; linkId: string; rangeIndex: number;
+}
+
+export class DocHyperLinkPopupService extends Disposable {
+ private readonly _editingLink$ = new BehaviorSubject<Nullable<ILinkInfo>>(null);
+ private readonly _showingLink$ = new BehaviorSubject<Nullable<ILinkInfo>>(null);
+ readonly editingLink$ = this._editingLink$.asObservable();
+ readonly showingLink$ = this._showingLink$.asObservable();
+
+ private _editPopup: Nullable<IDisposable> = null;
+ private _infoPopup: Nullable<IDisposable> = null;
+
+ constructor(
+ @Inject(DocCanvasPopManagerService) private readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @Inject(DocHyperLinkModel) private readonly _docHyperLinkModel: DocHyperLinkModel,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+ }
+
+ get editing() {
+ return this._editingLink$.value;
+ }
+
+ get showing() {
+ return this._showingLink$.value;
+ }
+
+ showEditPopup(linkInfo: Nullable<ILinkInfo>): Nullable<IDisposable> {
+ if (this._editPopup) {
+ this._editPopup.dispose();
+ }
+ this._editingLink$.next(linkInfo);
+ let activeRange: Nullable<ITextRange> = this._textSelectionManagerService.getActiveRange();
+ if (linkInfo) {
+ const { unitId, rangeIndex } = linkInfo;
+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ const range = doc?.getBody()?.customRanges?.[rangeIndex];
+ if (range) {
+ activeRange = {
+ collapsed: false,
+ startOffset: range.startIndex,
+ endOffset: range.endIndex + 1,
+ };
+ this._textSelectionManagerService.replaceTextRanges([{
+ startOffset: range.startIndex,
+ endOffset: range.endIndex + 1,
+ }]);
+ }
+ }
+
+ if (activeRange) {
+ this._editPopup = this._docCanvasPopupManagerService.attachPopupToRange(
+ activeRange,
+ {
+ componentKey: DocHyperLinkEdit.componentKey,
+ direction: 'bottom',
+ }
+ );
+ return this._editPopup;
+ }
+
+ return null;
+ }
+
+ hideEditPopup() {
+ this._editingLink$.next(null);
+ this._editPopup?.dispose();
+ }
+
+ showInfoPopup(info: ILinkInfo): Nullable<IDisposable> {
+ const { linkId, unitId, rangeIndex } = info;
+ if (
+ this.showing?.linkId === linkId &&
+ this.showing?.unitId === unitId &&
+ this.showing.rangeIndex === rangeIndex
+ ) {
+ return;
+ }
+
+ if (this._infoPopup) {
+ this._infoPopup.dispose();
+ }
+ const link = this._docHyperLinkModel.getLink(unitId, linkId);
+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ if (!doc || !link) {
+ return;
+ }
+ const range = doc.getBody()?.customRanges?.[rangeIndex];
+ this._showingLink$.next({ unitId, linkId, rangeIndex });
+ if (!range) {
+ return;
+ }
+
+ this._infoPopup = this._docCanvasPopupManagerService.attachPopupToRange(
+ {
+ collapsed: false,
+ startOffset: range.startIndex,
+ endOffset: range.endIndex + 1,
+ },
+ {
+ componentKey: DocLinkPopup.componentKey,
+ direction: 'top',
+ closeOnSelfTarget: true,
+ onClickOutside: () => {
+ this.hideInfoPopup();
+ },
+ }
+ );
+ return this._infoPopup;
+ }
+
+ hideInfoPopup() {
+ this._showingLink$.next(null);
+ this._infoPopup?.dispose();
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/types/const/index.ts b/packages/docs-hyper-link-ui/src/types/const/index.ts
new file mode 100644
index 0000000000..298ca7cce5
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/types/const/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 const DOC_HYPER_LINK_UI_PLUGIN = 'DOC_HYPER_LINK_UI_PLUGIN';
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less
new file mode 100644
index 0000000000..73a7218600
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less
@@ -0,0 +1,41 @@
+.docs-link-edit {
+ border-radius: 12px;
+ border: 1px solid rgb(var(--grey-200));
+ background: rgb(var(--color-white));
+ box-shadow: var(--box-shadow-base);
+ padding: 20px 24px;
+ width: 328px;
+
+ &-title {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ height: 24px;
+
+ font-size: 16px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 24px;
+ margin-bottom: 16px;
+ color: rgb(var(--color-black));
+ }
+
+ &-close {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+ color: rgb(var(--grey-600));
+ cursor: pointer;
+ }
+
+ &-buttons {
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ }
+
+ &-button {
+ margin-left: 12px;
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx
new file mode 100644
index 0000000000..e92d82eff5
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx
@@ -0,0 +1,149 @@
+/**
+ * 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 { Button, FormLayout, Input } from '@univerjs/design';
+import React, { useEffect, useState } from 'react';
+import { CloseSingle } from '@univerjs/icons';
+import { useDependency, useObservable } from '@wendellhu/redi/react-bindings';
+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';
+import type { DocumentDataModel } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType } from '@univerjs/core';
+import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { TextSelectionManagerService } from '@univerjs/docs';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';
+import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';
+import styles from './index.module.less';
+
+function hasProtocol(urlString: string) {
+ const pattern = /^[a-zA-Z]+:\/\//;
+ return pattern.test(urlString);
+}
+
+function isEmail(url: string) {
+ const pattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
+ return pattern.test(url);
+}
+
+function transformUrl(urlStr: string) {
+ return hasProtocol(urlStr) ? urlStr : isEmail(urlStr) ? `mailto://${urlStr}` : `https://${urlStr}`;
+}
+
+export const DocHyperLinkEdit = () => {
+ const hyperLinkService = useDependency(DocHyperLinkPopupService);
+ const localeService = useDependency(LocaleService);
+ const hyperLinkModel = useDependency(DocHyperLinkModel);
+ const editingId = useObservable(hyperLinkService.editingLink$);
+ const commandService = useDependency(ICommandService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const textSelectionRenderManager = useDependency(ITextSelectionRenderManager);
+ const textSelectionManagerService = useDependency(TextSelectionManagerService);
+ const [link, setLink] = useState('');
+ const [showError, setShowError] = useState(false);
+ const isLegal = Tools.isLegalUrl(link);
+ const doc = editingId
+ ? univerInstanceService.getUnit<DocumentDataModel>(editingId.unitId, UniverInstanceType.UNIVER_DOC) :
+ univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+
+ useEffect(() => {
+ if (editingId) {
+ const linkDetail = editingId ? hyperLinkModel.getLink(editingId.unitId, editingId.linkId) : null;
+ setLink(linkDetail?.payload ?? '');
+ return;
+ }
+ const activeRange = textSelectionManagerService.getActiveRange();
+ if (!activeRange) {
+ return;
+ }
+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const matchedRange = doc?.getBody()?.customRanges?.find((i) => Math.max(activeRange.startOffset, i.startIndex) <= Math.min(activeRange.endOffset - 1, i.endIndex));
+ if (doc && matchedRange) {
+ const linkDetail = hyperLinkModel.getLink(doc.getUnitId(), matchedRange.rangeId);
+ setLink(linkDetail?.payload ?? '');
+ }
+ }, [editingId, hyperLinkModel, textSelectionManagerService, univerInstanceService]);
+
+ useEffect(() => {
+ textSelectionRenderManager.blur();
+ return () => {
+ textSelectionRenderManager.focus();
+ };
+ }, [textSelectionRenderManager]);
+
+ const handleCancel = () => {
+ hyperLinkService.hideEditPopup();
+ };
+ const handleConfirm = () => {
+ setShowError(true);
+ if (!isLegal || !doc) {
+ return;
+ }
+ const linkFinal = transformUrl(link);
+
+ if (!editingId) {
+ commandService.executeCommand(AddDocHyperLinkCommand.id, {
+ unitId: doc.getUnitId(),
+ payload: linkFinal,
+ });
+ } else {
+ commandService.executeCommand(UpdateDocHyperLinkCommand.id, {
+ unitId: doc.getUnitId(),
+ payload: linkFinal,
+ linkId: editingId.linkId,
+ });
+ }
+ hyperLinkService.hideEditPopup();
+ };
+
+ if (!doc) {
+ return;
+ }
+
+ return (
+ <div className={styles.docsLinkEdit}>
+ <div className={styles.docsLinkEditTitle}>
+ <span>{localeService.t('docLink.edit.title')}</span>
+ <CloseSingle className={styles.docsLinkEditClose} onClick={handleCancel} />
+ </div>
+ <div>
+ <FormLayout
+ label={localeService.t('docLink.edit.address')}
+ error={showError && !isLegal ? localeService.t('docLink.edit.addressError') : ''}
+ >
+ <Input value={link} onChange={setLink} autoFocus />
+ </FormLayout>
+ </div>
+ <div className={styles.docsLinkEditButtons}>
+ <Button
+ className={styles.docsLinkEditButton}
+ onClick={handleCancel}
+ >
+ {localeService.t('docLink.edit.cancel')}
+ </Button>
+ <Button
+ disabled={!link}
+ className={styles.docsLinkEditButton}
+ type="primary"
+ onClick={handleConfirm}
+ >
+ {localeService.t('docLink.edit.confirm')}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+DocHyperLinkEdit.componentKey = 'docs-hyper-link-edit';
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less
new file mode 100644
index 0000000000..eeda3405e5
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less
@@ -0,0 +1,83 @@
+.doc-link {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px;
+ box-shadow: var(--box-shadow-base);
+ border-radius: 8px;
+ border: 1px solid rgb(var(--grey-200));
+ background: rgb(var(--color-white));
+ max-width: 328px;
+ overflow: hidden;
+}
+
+.doc-link-type {
+ height: 20px;
+ width: 20px;
+ font-size: 16px;
+ margin-right: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ color: rgb(var(--color-black));
+}
+
+.doc-link-content {
+ height: 24px;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ font-size: 13px;
+ line-height: 20px;
+ color: rgb(var(--blue-500));
+ cursor: pointer;
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.doc-link-content-error {
+ color: rgb(var(--grey-500));
+}
+
+.doc-link-url {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.doc-link-operations {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: center;
+ height: 24px;
+ flex-basis: auto;
+ flex-grow: 0;
+ flex-shrink: 0;
+}
+
+.doc-link-operation {
+ width: 24px;
+ height: 24px;
+ border-radius: 4px;
+ margin-left: 8px;
+ font-size: 16px;
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: center;
+ cursor: pointer;
+ border-radius: 4px;
+}
+
+.doc-link-operation-error {
+ color: rgb(var(--grey-500));
+}
+
+.doc-link-operation:hover {
+ background: #ccc;
+}
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx
new file mode 100644
index 0000000000..73270395ba
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx
@@ -0,0 +1,108 @@
+/**
+ * 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 { useDependency } from '@wendellhu/redi/react-bindings';
+import React from 'react';
+import { CopySingle, LinkSingle, UnlinkSingle, WriteSingle } from '@univerjs/icons';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import cs from 'clsx';
+import { MessageType, Tooltip } from '@univerjs/design';
+import { IMessageService, useObservable } from '@univerjs/ui';
+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+import { DeleteDocHyperLinkCommand } from '../../commands/commands/delete-link.command';
+import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';
+import styles from './index.module.less';
+
+export const DocLinkPopup = () => {
+ const hyperLinkService = useDependency(DocHyperLinkPopupService);
+ const hyperLinkModel = useDependency(DocHyperLinkModel);
+ const commandService = useDependency(ICommandService);
+ const messageService = useDependency(IMessageService);
+ const localeService = useDependency(LocaleService);
+ const currentPopup = useObservable(hyperLinkService.showingLink$);
+ if (!currentPopup) {
+ return null;
+ }
+
+ const { unitId, linkId } = currentPopup;
+ const link = hyperLinkModel.getLink(unitId, linkId);
+ if (!link) {
+ return null;
+ }
+
+ return (
+ <div
+ className={styles.docLink}
+ onClick={() => {
+ hyperLinkService.hideInfoPopup();
+ }}
+ >
+ <div className={cs(styles.docLinkContent)} onClick={() => window.open(link.payload)}>
+ <div className={styles.docLinkType}>
+ <LinkSingle />
+ </div>
+ <Tooltip showIfEllipsis title={link.payload}>
+ <span className={styles.docLinkUrl}>{link.payload}</span>
+ </Tooltip>
+ </div>
+ <div className={styles.docLinkOperations}>
+ <div
+ className={cs(styles.docLinkOperation)}
+ onClick={() => {
+ navigator.clipboard.writeText(link.payload);
+ messageService.show({
+ content: localeService.t('docLink.info.coped'),
+ type: MessageType.Info,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t('docLink.info.copy')}>
+ <CopySingle />
+ </Tooltip>
+
+ </div>
+ <div
+ className={styles.docLinkOperation}
+ onClick={() => {
+ commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id, {
+ link: currentPopup,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t('docLink.info.edit')}>
+ <WriteSingle />
+ </Tooltip>
+ </div>
+ <div
+ className={styles.docLinkOperation}
+ onClick={() => {
+ commandService.executeCommand(DeleteDocHyperLinkCommand.id, {
+ unitId,
+ linkId: link.id,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t('docLink.info.cancel')}>
+ <UnlinkSingle />
+ </Tooltip>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+DocLinkPopup.componentKey = 'univer.doc.link-info-popup';
diff --git a/packages/docs-hyper-link-ui/src/vite-env.d.ts b/packages/docs-hyper-link-ui/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/packages/docs-hyper-link-ui/tsconfig.json b/packages/docs-hyper-link-ui/tsconfig.json
new file mode 100644
index 0000000000..d676ad2a20
--- /dev/null
+++ b/packages/docs-hyper-link-ui/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "references": [{ "path": "./tsconfig.node.json" }],
+ "include": ["src"]
+}
diff --git a/packages/docs-hyper-link-ui/tsconfig.node.json b/packages/docs-hyper-link-ui/tsconfig.node.json
new file mode 100644
index 0000000000..e53dac8868
--- /dev/null
+++ b/packages/docs-hyper-link-ui/tsconfig.node.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/node",
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/docs-hyper-link-ui/vite.config.ts b/packages/docs-hyper-link-ui/vite.config.ts
new file mode 100644
index 0000000000..925b530b4d
--- /dev/null
+++ b/packages/docs-hyper-link-ui/vite.config.ts
@@ -0,0 +1,12 @@
+import createViteConfig from '@univerjs/shared/vite';
+import pkg from './package.json';
+
+export default ({ mode }) => createViteConfig({}, {
+ mode,
+ pkg,
+ features: {
+ react: false,
+ css: true,
+ dom: true,
+ },
+});
diff --git a/packages/docs-hyper-link/README-zh.md b/packages/docs-hyper-link/README-zh.md
new file mode 100644
index 0000000000..bff725faf2
--- /dev/null
+++ b/packages/docs-hyper-link/README-zh.md
@@ -0,0 +1,22 @@
+# @univerjs/docs-hyper-link
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/docs-hyper-link)](https://npmjs.org/packages/@univerjs/docs-hyper-link )
+[![license](https://img.shields.io/npm/l/@univerjs/docs-hyper-link)](https://img.shields.io/npm/l/@univerjs/sheets- thread-comment)
+
+## Introduction
+
+`@univerjs/docs-hyper-link` provides the base link function of Univer Docs.
+
+
+## Usage
+
+### Install
+
+```shell
+# Use npm
+npm install @univerjs/docs-hyper-link
+
+# Use pnpm
+pnpm add @univerjs/docs-hyper-link
+```
+
diff --git a/packages/docs-hyper-link/README.md b/packages/docs-hyper-link/README.md
new file mode 100644
index 0000000000..bff725faf2
--- /dev/null
+++ b/packages/docs-hyper-link/README.md
@@ -0,0 +1,22 @@
+# @univerjs/docs-hyper-link
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/docs-hyper-link)](https://npmjs.org/packages/@univerjs/docs-hyper-link )
+[![license](https://img.shields.io/npm/l/@univerjs/docs-hyper-link)](https://img.shields.io/npm/l/@univerjs/sheets- thread-comment)
+
+## Introduction
+
+`@univerjs/docs-hyper-link` provides the base link function of Univer Docs.
+
+
+## Usage
+
+### Install
+
+```shell
+# Use npm
+npm install @univerjs/docs-hyper-link
+
+# Use pnpm
+pnpm add @univerjs/docs-hyper-link
+```
+
diff --git a/packages/docs-hyper-link/package.json b/packages/docs-hyper-link/package.json
new file mode 100644
index 0000000000..ecc821de05
--- /dev/null
+++ b/packages/docs-hyper-link/package.json
@@ -0,0 +1,97 @@
+{
+ "name": "@univerjs/docs-hyper-link",
+ "version": "0.1.14",
+ "private": false,
+ "description": "Univer thread comment plugin",
+ "author": "DreamNum <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*"
+ },
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "lint:types": "tsc --noEmit",
+ "build": "tsc && vite build"
+ },
+ "peerDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-ui": "workspace:*",
+ "@wendellhu/redi": "0.15.5",
+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/icons": "^0.1.58",
+ "@univerjs/thread-comment": "workspace:*",
+ "@univerjs/thread-comment-ui": "workspace:*"
+ },
+ "devDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/shared": "workspace:*",
+ "@wendellhu/redi": "0.15.5",
+ "clsx": "^2.1.1",
+ "react": "18.3.1",
+ "rxjs": "^7.8.1",
+ "typescript": "^5.4.5",
+ "vite": "^5.2.12",
+ "vitest": "^1.6.0"
+ },
+ "univerSpace": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+}
diff --git a/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts b/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts
new file mode 100644
index 0000000000..25cceeed2b
--- /dev/null
+++ b/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts
@@ -0,0 +1,36 @@
+/**
+ * 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 { CommandType, type ICommand } from '@univerjs/core';
+import type { IDocHyperLink } from '../../types/interfaces/i-doc-hyper-link';
+import { DocHyperLinkModel } from '../../models/hyper-link.model';
+
+export interface IAddDocHyperLinkMutationParams {
+ unitId: string;
+ link: IDocHyperLink;
+}
+
+export const AddDocHyperLinkMutation: ICommand<IAddDocHyperLinkMutationParams> = {
+ type: CommandType.MUTATION,
+ id: 'docs.mutation.add-hyper-link',
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+ const docHyperLinkModel = accessor.get(DocHyperLinkModel);
+ return docHyperLinkModel.addLink(params.unitId, params.link);
+ },
+};
diff --git a/packages/docs-hyper-link/src/commands/mutations/delete-link.mutation.ts b/packages/docs-hyper-link/src/commands/mutations/delete-link.mutation.ts
new file mode 100644
index 0000000000..15a6c9ebec
--- /dev/null
+++ b/packages/docs-hyper-link/src/commands/mutations/delete-link.mutation.ts
@@ -0,0 +1,35 @@
+/**
+ * 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 { CommandType, type ICommand } from '@univerjs/core';
+import { DocHyperLinkModel } from '../../models/hyper-link.model';
+
+export interface IDeleteDocHyperLinkMutationParams {
+ unitId: string;
+ linkId: string;
+}
+
+export const DeleteDocHyperLinkMutation: ICommand<IDeleteDocHyperLinkMutationParams> = {
+ type: CommandType.MUTATION,
+ id: 'docs.mutation.delete-hyper-link',
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+ const docHyperLinkModel = accessor.get(DocHyperLinkModel);
+ return docHyperLinkModel.deleteLink(params.unitId, params.linkId);
+ },
+};
diff --git a/packages/docs-hyper-link/src/commands/mutations/update-link.mutation.ts b/packages/docs-hyper-link/src/commands/mutations/update-link.mutation.ts
new file mode 100644
index 0000000000..349cf1f24e
--- /dev/null
+++ b/packages/docs-hyper-link/src/commands/mutations/update-link.mutation.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType, type ICommand } from '@univerjs/core';
+import { DocHyperLinkModel } from '../../models/hyper-link.model';
+
+export interface IUpdateDocHyperLinkMutationParams {
+ unitId: string;
+ linkId: string;
+ payload: string;
+}
+
+export const UpdateDocHyperLinkMutation: ICommand<IUpdateDocHyperLinkMutationParams> = {
+ type: CommandType.MUTATION,
+ id: 'docs.mutation.update-hyper-link',
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+
+ const docHyperLinkModel = accessor.get(DocHyperLinkModel);
+ return docHyperLinkModel.updateLink(params.unitId, params.linkId, params.payload);
+ },
+};
diff --git a/packages/docs-hyper-link/src/controllers/hyper-link.controller.ts b/packages/docs-hyper-link/src/controllers/hyper-link.controller.ts
new file mode 100644
index 0000000000..20525ef9d8
--- /dev/null
+++ b/packages/docs-hyper-link/src/controllers/hyper-link.controller.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { AddDocHyperLinkMutation } from '../commands/mutations/add-link.mutation';
+import { UpdateDocHyperLinkMutation } from '../commands/mutations/update-link.mutation';
+import { DeleteDocHyperLinkMutation } from '../commands/mutations/delete-link.mutation';
+
+@OnLifecycle(LifecycleStages.Starting, DocHyperLinkController)
+export class DocHyperLinkController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initCommands();
+ }
+
+ private _initCommands() {
+ [
+ AddDocHyperLinkMutation,
+ UpdateDocHyperLinkMutation,
+ DeleteDocHyperLinkMutation,
+ ].forEach((command) => {
+ this.disposeWithMe(this._commandService.registerCommand(command));
+ });
+ }
+}
diff --git a/packages/docs-hyper-link/src/controllers/resource.controller.ts b/packages/docs-hyper-link/src/controllers/resource.controller.ts
new file mode 100644
index 0000000000..3258e6a41d
--- /dev/null
+++ b/packages/docs-hyper-link/src/controllers/resource.controller.ts
@@ -0,0 +1,67 @@
+/**
+ * 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 { DocumentDataModel } from '@univerjs/core';
+import { CustomRangeType, Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, ResourceManagerService, UniverInstanceType } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { DOC_HYPER_LINK_PLUGIN } from '../types/const';
+import { DocHyperLinkModel } from '../models/hyper-link.model';
+import type { IDocHyperLink } from '../types/interfaces/i-doc-hyper-link';
+import { DocHyperLinkController } from './hyper-link.controller';
+
+interface IDocHyperLinkJSON {
+ links: IDocHyperLink[];
+}
+
+@OnLifecycle(LifecycleStages.Starting, DocHyperLinkController)
+export class DocHyperLinkResourceController extends Disposable {
+ constructor(
+ @Inject(ResourceManagerService) private readonly _resourceManagerService: ResourceManagerService,
+ @Inject(DocHyperLinkModel) private readonly _docHyperLinkModel: DocHyperLinkModel,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ this._init();
+ }
+
+ private _init() {
+ this._resourceManagerService.registerPluginResource({
+ pluginName: DOC_HYPER_LINK_PLUGIN,
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ onLoad: (unitID: string, resource: IDocHyperLinkJSON) => {
+ resource.links.forEach((link) => {
+ this._docHyperLinkModel.addLink(unitID, link);
+ });
+ },
+ onUnLoad: (unitID: string) => {
+ this._docHyperLinkModel.deleteUnit(unitID);
+ },
+ toJson: (unitID: string) => {
+ const links = this._docHyperLinkModel.getUnit(unitID);
+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitID, UniverInstanceType.UNIVER_DOC);
+ const customRanges = doc?.getBody()?.customRanges;
+ const set = new Set(customRanges?.filter((i) => i.rangeType === CustomRangeType.HYPERLINK).map((i) => i.rangeId));
+
+ return JSON.stringify({
+ links: links.filter((link) => set.has(link.id)),
+ });
+ },
+ parseJson(bytes: string): IDocHyperLinkJSON {
+ return JSON.parse(bytes);
+ },
+ });
+ }
+}
diff --git a/packages/docs-hyper-link/src/index.ts b/packages/docs-hyper-link/src/index.ts
new file mode 100644
index 0000000000..f0b0d44540
--- /dev/null
+++ b/packages/docs-hyper-link/src/index.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { DOC_HYPER_LINK_PLUGIN } from './types/const';
+export { DocHyperLinkModel } from './models/hyper-link.model';
+export type { IDocHyperLink } from './types/interfaces/i-doc-hyper-link';
+export { DocHyperLinkType } from './types/enums/doc-hyper-link-type';
+export { UniverDocHyperLinkPlugin } from './plugin';
+// #region - all commands
+
+export { AddDocHyperLinkMutation, type IAddDocHyperLinkMutationParams } from './commands/mutations/add-link.mutation';
+export { UpdateDocHyperLinkMutation, type IUpdateDocHyperLinkMutationParams } from './commands/mutations/update-link.mutation';
+export { DeleteDocHyperLinkMutation, type IDeleteDocHyperLinkMutationParams } from './commands/mutations/delete-link.mutation';
+
+// #endregion
diff --git a/packages/docs-hyper-link/src/models/hyper-link.model.ts b/packages/docs-hyper-link/src/models/hyper-link.model.ts
new file mode 100644
index 0000000000..482b719149
--- /dev/null
+++ b/packages/docs-hyper-link/src/models/hyper-link.model.ts
@@ -0,0 +1,129 @@
+/**
+ * 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 { Disposable } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import type { IDocHyperLink } from '../types/interfaces/i-doc-hyper-link';
+
+export type DocLinkUpdate = {
+ type: 'add';
+ link: IDocHyperLink;
+ unitId: string;
+} | {
+ type: 'update';
+ oldPayload: string;
+ link: IDocHyperLink;
+ unitId: string;
+} | {
+ type: 'delete';
+ link: IDocHyperLink;
+ unitId: string;
+} | {
+ type: 'delete-unit';
+ unitId: string;
+};
+
+export class DocHyperLinkModel extends Disposable {
+ private readonly _links = new Map<string, Map<string, IDocHyperLink>>();
+ private readonly _linkUpdate$ = new Subject<DocLinkUpdate>();
+
+ readonly linkUpdate$ = this._linkUpdate$.asObservable();
+
+ constructor() {
+ super();
+
+ this.disposeWithMe(() => {
+ this._linkUpdate$.complete();
+ });
+ }
+
+ private _ensureMap(unitId: string) {
+ let map = this._links.get(unitId);
+
+ if (!map) {
+ map = new Map();
+ this._links.set(unitId, map);
+ }
+ return map;
+ }
+
+ addLink(unitId: string, link: IDocHyperLink) {
+ const map = this._ensureMap(unitId);
+ map.set(link.id, link);
+
+ this._linkUpdate$.next({
+ type: 'add',
+ link,
+ unitId,
+ });
+
+ return true;
+ }
+
+ updateLink(unitId: string, id: string, payload: string) {
+ const map = this._ensureMap(unitId);
+ const link = map.get(id);
+ if (!link) {
+ return false;
+ }
+ const oldPayload = link.payload;
+ link.payload = payload;
+ this._linkUpdate$.next({
+ type: 'update',
+ link,
+ oldPayload,
+ unitId,
+ });
+ return true;
+ }
+
+ deleteLink(unitId: string, id: string) {
+ const map = this._ensureMap(unitId);
+ const link = map.get(id);
+
+ if (!link) {
+ return true;
+ }
+
+ map.delete(id);
+ this._linkUpdate$.next({
+ type: 'delete',
+ link,
+ unitId,
+ });
+ return false;
+ }
+
+ getLink(unitId: string, linkId: string) {
+ const map = this._ensureMap(unitId);
+ return map.get(linkId);
+ }
+
+ getUnit(unitId: string) {
+ const map = this._ensureMap(unitId);
+
+ return Array.from(map.values());
+ }
+
+ deleteUnit(unitId: string) {
+ this._links.delete(unitId);
+ this._linkUpdate$.next({
+ unitId,
+ type: 'delete-unit',
+ });
+ }
+}
+
diff --git a/packages/docs-hyper-link/src/plugin.ts b/packages/docs-hyper-link/src/plugin.ts
new file mode 100644
index 0000000000..06b298fa95
--- /dev/null
+++ b/packages/docs-hyper-link/src/plugin.ts
@@ -0,0 +1,46 @@
+/**
+ * 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 { Plugin, UniverInstanceType } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { DOC_HYPER_LINK_PLUGIN } from './types/const';
+import { DocHyperLinkModel } from './models/hyper-link.model';
+import { DocHyperLinkController } from './controllers/hyper-link.controller';
+import { DocHyperLinkResourceController } from './controllers/resource.controller';
+
+export class UniverDocHyperLinkPlugin extends Plugin {
+ static override pluginName = DOC_HYPER_LINK_PLUGIN;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ @Inject(Injector) protected override _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(injector: Injector): void {
+ const deps: Dependency[] = [
+ [DocHyperLinkModel],
+ [DocHyperLinkController],
+ [DocHyperLinkResourceController],
+ ];
+
+ deps.forEach((dep) => {
+ injector.add(dep);
+ });
+ }
+}
diff --git a/packages/docs-hyper-link/src/types/const/index.ts b/packages/docs-hyper-link/src/types/const/index.ts
new file mode 100644
index 0000000000..8a76180850
--- /dev/null
+++ b/packages/docs-hyper-link/src/types/const/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 const DOC_HYPER_LINK_PLUGIN = 'DOC_HYPER_LINK_PLUGIN';
diff --git a/packages/docs-hyper-link/src/types/enums/doc-hyper-link-type.ts b/packages/docs-hyper-link/src/types/enums/doc-hyper-link-type.ts
new file mode 100644
index 0000000000..c34640c7fc
--- /dev/null
+++ b/packages/docs-hyper-link/src/types/enums/doc-hyper-link-type.ts
@@ -0,0 +1,19 @@
+/**
+ * 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 DocHyperLinkType {
+ URL,
+}
diff --git a/packages/docs-hyper-link/src/types/interfaces/i-doc-hyper-link.ts b/packages/docs-hyper-link/src/types/interfaces/i-doc-hyper-link.ts
new file mode 100644
index 0000000000..fac5d27e4d
--- /dev/null
+++ b/packages/docs-hyper-link/src/types/interfaces/i-doc-hyper-link.ts
@@ -0,0 +1,20 @@
+/**
+ * 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 IDocHyperLink {
+ payload: string;
+ id: string;
+}
diff --git a/packages/docs-hyper-link/tsconfig.json b/packages/docs-hyper-link/tsconfig.json
new file mode 100644
index 0000000000..d676ad2a20
--- /dev/null
+++ b/packages/docs-hyper-link/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "references": [{ "path": "./tsconfig.node.json" }],
+ "include": ["src"]
+}
diff --git a/packages/docs-hyper-link/tsconfig.node.json b/packages/docs-hyper-link/tsconfig.node.json
new file mode 100644
index 0000000000..e53dac8868
--- /dev/null
+++ b/packages/docs-hyper-link/tsconfig.node.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/node",
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/docs-hyper-link/vite.config.ts b/packages/docs-hyper-link/vite.config.ts
new file mode 100644
index 0000000000..925b530b4d
--- /dev/null
+++ b/packages/docs-hyper-link/vite.config.ts
@@ -0,0 +1,12 @@
+import createViteConfig from '@univerjs/shared/vite';
+import pkg from './package.json';
+
+export default ({ mode }) => createViteConfig({}, {
+ mode,
+ pkg,
+ features: {
+ react: false,
+ css: true,
+ dom: true,
+ },
+});
diff --git a/packages/docs-thread-comment-ui/README-zh.md b/packages/docs-thread-comment-ui/README-zh.md
index 8e078a2bf3..0418eeaf58 100644
--- a/packages/docs-thread-comment-ui/README-zh.md
+++ b/packages/docs-thread-comment-ui/README-zh.md
@@ -22,39 +22,7 @@ pnpm add @univerjs/docs-thread-comment-ui
### 使用
```js
-import { UniverSheetsThreadCommentPlugin, IThreadCommentMentionDataService } from '@univerjs/docs-thread-comment-ui';
-
-const mockUser = {
- userID: 'mockId',
- name: 'MockUser',
- avatar: 'avatar-icon-url',
- anonymous: false,
- canBindAnonymous: false,
-};
-
-class CustomMentionDataService implements IThreadCommentMentionDataService {
- trigger: string = '@';
-
- // 获取提及用户的通用接口实现
- async getMentions(search: string) {
- return [
- {
- id: mockUser.userID,
- label: mockUser.name,
- type: 'user',
- icon: mockUser.avatar,
- },
- {
- id: '2',
- label: 'User2',
- type: 'user',
- icon: mockUser.avatar,
- },
- ];
- }
-}
-
-univer.registerPlugin(UniverSheetsThreadCommentPlugin, {
- overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],
-});
+import { UniverDocsThreadCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
+
+univer.registerPlugin(UniverDocsThreadCommentUIPlugin);
```
diff --git a/packages/docs-thread-comment-ui/README.md b/packages/docs-thread-comment-ui/README.md
index 6af55ce216..1bc3043cfb 100644
--- a/packages/docs-thread-comment-ui/README.md
+++ b/packages/docs-thread-comment-ui/README.md
@@ -22,39 +22,7 @@ pnpm add @univerjs/sheets-thread-comment
### use
```js
-import { UniverSheetsThreadCommentPlugin, IThreadCommentMentionDataService} from '@univerjs/sheets-thread-comment';
-
-const mockUser = {
- userID: 'mockId',
- name: 'MockUser',
- avatar: 'icon-url',
- anonymous: false,
- canBindAnonymous: false,
-};
-
-class CustomMentionDataService implements IThreadCommentMentionDataService {
- trigger: string = '@';
-
- // Get the common interface implementation of the mentioned user
- async getMentions(search: string) {
- return [
- {
- id: mockUser.userID,
- label: mockUser.name,
- type: 'user',
- icon: mockUser.avatar,
- },
- {
- id: '2',
- label: 'User2',
- type: 'user',
- icon: mockUser.avatar,
- },
- ];
- }
-}
-
-univer.registerPlugin(UniverSheetsThreadCommentPlugin, {
- overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],
-});
+import { UniverDocsThreadCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
+
+univer.registerPlugin(UniverDocsThreadCommentUIPlugin);
```
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
index 4715a6ce06..f0fb38ecb8 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
@@ -61,33 +61,6 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
}
private _interceptorViewModel() {
- this._docInterceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {
- handler: (data, pos, next) => {
- if (!data) {
- return next(data);
- }
- const { unitId, index, customRanges } = pos;
- const activeComment = this._threadCommentPanelService.activeCommentId;
- const { commentId, unitId: commentUnitID } = activeComment || {};
- const activeCustomRange = customRanges.find((i) => i.rangeId === commentId);
- const comment = this._threadCommentModel.getComment(unitId, DEFAULT_DOC_SUBUNIT_ID, data.rangeId);
- if (!comment) {
- return next({
- ...data,
- show: false,
- });
- }
-
- const isActiveIndex = activeCustomRange && index >= activeCustomRange.startIndex && index <= activeCustomRange.endIndex;
- const isActive = commentUnitID === unitId && data.rangeId === commentId;
- return next({
- ...data,
- active: isActive || isActiveIndex,
- show: !comment.resolved,
- });
- },
- });
-
this._docInterceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_DECORATION, {
handler: (data, pos, next) => {
if (!data) {
diff --git a/packages/docs-thread-comment-ui/src/index.ts b/packages/docs-thread-comment-ui/src/index.ts
index aadd7d044a..29568cc22d 100644
--- a/packages/docs-thread-comment-ui/src/index.ts
+++ b/packages/docs-thread-comment-ui/src/index.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-export { UniverDocsCommentUIPlugin } from './plugin';
+export { UniverDocsThreadCommentUIPlugin } from './plugin';
// #region - all commands
export { AddDocCommentComment } from './commands/commands/add-doc-comment.command';
diff --git a/packages/docs-thread-comment-ui/src/plugin.ts b/packages/docs-thread-comment-ui/src/plugin.ts
index 71c9d1ebbd..02ae4b065e 100644
--- a/packages/docs-thread-comment-ui/src/plugin.ts
+++ b/packages/docs-thread-comment-ui/src/plugin.ts
@@ -27,7 +27,7 @@ import { DocThreadCommentSelectionController } from './controllers/doc-thread-co
import { DocThreadCommentRenderController } from './controllers/render-controllers/render.controller';
@DependentOn(UniverThreadCommentUIPlugin)
-export class UniverDocsCommentUIPlugin extends Plugin {
+export class UniverDocsThreadCommentUIPlugin extends Plugin {
static override pluginName = PLUGIN_NAME;
static override type = UniverInstanceType.UNIVER_DOC;
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 846db4e6ab..4b19d9975b 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+export { whenDocAndEditorFocused } from './shortcuts/utils';
+export { IDocClipboardService } from './services/clipboard/clipboard.service';
export { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
export * from './basics';
export * from './docs-ui-plugin';
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 387471990a..29a5822cb2 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -15,7 +15,7 @@
*/
import type { ICustomRange, IDocumentBody, IParagraph } from '@univerjs/core';
-import { Disposable, ICommandService, ILogService, IUniverInstanceService, toDisposable } from '@univerjs/core';
+import { Disposable, ICommandService, ILogService, IUniverInstanceService, normalizeBody, toDisposable } from '@univerjs/core';
import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
@@ -54,6 +54,7 @@ export interface IClipboardPropertyItem { }
export interface IDocClipboardHook {
onCopyProperty?(start: number, end: number): IClipboardPropertyItem;
onCopyContent?(start: number, end: number): string;
+ onBeforePaste?: (body: IDocumentBody) => IDocumentBody;
}
export interface IDocClipboardService {
@@ -166,8 +167,16 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
}
- private async _paste(body: IDocumentBody): Promise<boolean> {
- const { segmentId, endOffset: activeEndOffset, style } = this._textSelectionManagerService.getActiveRange() ?? {};
+ private async _paste(_body: IDocumentBody): Promise<boolean> {
+ let body = normalizeBody(_body);
+
+ this._clipboardHooks.forEach((hook) => {
+ if (hook.onBeforePaste) {
+ body = hook.onBeforePaste(body);
+ }
+ });
+ const activeRange = this._textSelectionManagerService.getActiveRange();
+ const { segmentId, endOffset: activeEndOffset, style } = activeRange || {};
const ranges = this._textSelectionManagerService.getSelections();
if (segmentId == null) {
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 546c36be7b..05bb3cbac9 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -14,15 +14,16 @@
* limitations under the License.
*/
+import type { ITextRange } from '@univerjs/core';
import { Disposable, DisposableCollection, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import type { BaseObject, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
+import { getLineBounding, IRenderManagerService, NodePositionConvertToCursor } from '@univerjs/engine-render';
+import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
import type { IPopup } from '@univerjs/ui';
import { ICanvasPopupService } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
import { Inject } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
-import { SetDocZoomRatioOperation, VIEWPORT_KEY } from '@univerjs/docs';
+import { BehaviorSubject, map } from 'rxjs';
+import { DocSkeletonManagerService, SetDocZoomRatioOperation, VIEWPORT_KEY } from '@univerjs/docs';
export function transformBound2OffsetBound(originBound: IBoundRectNoAngle, scene: Scene): IBoundRectNoAngle {
const topLeft = transformPosition2Offset(originBound.left, originBound.top, scene);
@@ -127,6 +128,63 @@ export class DocCanvasPopManagerService extends Disposable {
};
}
+ private _createRangePositionObserver(range: ITextRange, currentRender: IRender) {
+ const calc = (): IBoundRectNoAngle[] | undefined => {
+ const { scene, mainComponent } = currentRender;
+ const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset);
+ const endPosition = skeleton.findNodePositionByCharIndex(range.endOffset);
+ const document = mainComponent as Documents;
+
+ if (!endPosition || !startPosition) {
+ return;
+ }
+
+ const documentOffsetConfig = document.getOffsetConfig();
+ const { docsLeft, docsTop } = documentOffsetConfig;
+
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);
+ const bounds = getLineBounding(borderBoxPointGroup);
+ const res = bounds.map((bound) => transformBound2OffsetBound(bound, scene)).map((i) => ({
+ left: i.left + docsLeft,
+ right: i.right + docsLeft,
+ top: i.top + docsTop,
+ bottom: i.bottom + docsTop,
+ }));
+ return res;
+ };
+
+ const positions = calc() ?? [];
+ const positions$ = new BehaviorSubject(positions);
+ const disposable = new DisposableCollection();
+
+ disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetDocZoomRatioOperation.id) {
+ const position = calc();
+ if (position) {
+ positions$.next(position);
+ }
+ }
+ }));
+
+ const viewMain = currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (viewMain) {
+ disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => {
+ const position = calc();
+ if (position) {
+ positions$.next(position);
+ }
+ }));
+ }
+
+ return {
+ positions,
+ positions$,
+ disposable,
+ };
+ }
+
/**
* attach a popup to canvas object
* @param targetObject target canvas object
@@ -165,4 +223,39 @@ export class DocCanvasPopManagerService extends Disposable {
},
};
}
+
+ attachPopupToRange(range: ITextRange, popup: IDocCanvasPopup): IDisposable {
+ const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)!;
+ const unitId = workbook.getUnitId();
+ const { direction = 'top' } = popup;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (!currentRender) {
+ return {
+ dispose: () => {
+ // empty
+ },
+ };
+ }
+
+ const { positions: bounds, positions$: bounds$, disposable } = this._createRangePositionObserver(range, currentRender);
+ const position$ = bounds$.pipe(map((bounds) => direction === 'top' ? bounds[0] : bounds[bounds.length - 1]));
+ const id = this._globalPopupManagerService.addPopup({
+ ...popup,
+ unitId,
+ subUnitId: 'default',
+ anchorRect: direction === 'top' ? bounds[0] : bounds[bounds.length - 1],
+ anchorRect$: position$,
+ excludeRects: bounds,
+ excludeRects$: bounds$,
+ direction: direction === 'top' ? 'top' : 'bottom',
+ });
+ return {
+ dispose: () => {
+ this._globalPopupManagerService.removePopup(id);
+ bounds$.complete();
+ disposable.dispose();
+ },
+ };
+ }
}
diff --git a/packages/docs/src/basics/custom-range-factory.ts b/packages/docs/src/basics/custom-range-factory.ts
index 024751396f..f4974faa9d 100644
--- a/packages/docs/src/basics/custom-range-factory.ts
+++ b/packages/docs/src/basics/custom-range-factory.ts
@@ -20,7 +20,7 @@ import type { IAccessor } from '@wendellhu/redi';
import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
import { TextSelectionManagerService } from '../services/text-selection-manager.service';
-import { getSelectionForAddCustomRange } from './selection';
+import { getSelectionForAddCustomRange, normalizeSelection } from './selection';
interface IAddCustomRangeParam {
unitId: string;
@@ -30,25 +30,16 @@ interface IAddCustomRangeParam {
rangeType: CustomRangeType;
}
-export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocumentBody) {
- const { unitId, range, rangeId, rangeType, segmentId } = param;
+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 doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
- id: RichTextEditingMutation.id,
- params: {
- unitId,
- actions: [],
- textRanges: undefined,
- },
- };
const textX = new TextX();
- const jsonX = JSONX.getInstance();
if (start > 0) {
textX.push({
@@ -62,14 +53,6 @@ export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocume
t: TextXActionType.INSERT,
body: {
dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,
- customRanges: [
- {
- rangeId,
- rangeType,
- startIndex: 0,
- endIndex: 0,
- },
- ],
},
len: 1,
line: 0,
@@ -92,7 +75,7 @@ export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocume
{
rangeId,
rangeType,
- startIndex: 0,
+ startIndex: -(end - start) - 1,
endIndex: 0,
},
],
@@ -101,6 +84,23 @@ export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocume
line: 0,
});
+ return textX;
+}
+
+export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocumentBody) {
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: param.unitId,
+ actions: [],
+ textRanges: undefined,
+ },
+ };
+ const jsonX = JSONX.getInstance();
+ const textX = addCustomRangeTextX(param, body);
+ if (!textX) {
+ return false;
+ }
doMutation.params.actions = jsonX.editOp(textX.serialize());
return doMutation;
}
@@ -111,6 +111,7 @@ interface IAddCustomRangeFactoryParam {
rangeType: CustomRangeType;
}
+// eslint-disable-next-line max-lines-per-function
export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAddCustomRangeFactoryParam) {
const { segmentId, rangeId, rangeType } = param;
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
@@ -130,22 +131,107 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAd
if (!body) {
return false;
}
+ const { startOffset, endOffset } = normalizeSelection(selection);
- const doMutation = addCustomRangeFactory(
- {
- unitId,
- range: {
- startOffset: selection.startOffset,
- endOffset: selection.endOffset,
- collapsed: true,
- },
- rangeId,
- rangeType,
+ 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;
+
+ 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,
},
- body
- );
+ len: 1,
+ line: 0,
+ segmentId,
+ });
+ 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;
+ }
+
+ textX.push({
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_END,
+ customRanges: [
+ {
+ rangeId,
+ rangeType,
+ startIndex: -(range.endOffset - range.startOffset - deletes.length + 1),
+ endIndex: 0,
+ },
+ ],
+ },
+ len: 1,
+ line: 0,
+ segmentId,
+ });
+ const jsonX = JSONX.getInstance();
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId,
+ actions: [],
+ textRanges: undefined,
+ },
+ };
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
return doMutation;
}
@@ -155,7 +241,7 @@ export interface IDeleteCustomRangeParam {
segmentId?: string;
}
-export function deleteCustomRange(accessor: IAccessor, params: IDeleteCustomRangeParam) {
+function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangeParam) {
const { unitId, rangeId, segmentId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -168,18 +254,10 @@ export function deleteCustomRange(accessor: IAccessor, params: IDeleteCustomRang
if (!range) {
return false;
}
- const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
- id: RichTextEditingMutation.id,
- params: {
- unitId,
- actions: [],
- textRanges: undefined,
- },
- };
const { startIndex, endIndex } = range;
const textX = new TextX();
- const jsonX = JSONX.getInstance();
+
const len = endIndex - startIndex + 1;
if (startIndex > 0) {
@@ -212,6 +290,25 @@ export function deleteCustomRange(accessor: IAccessor, params: IDeleteCustomRang
line: 0,
});
+ return textX;
+}
+
+export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeParam) {
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: params.unitId,
+ actions: [],
+ textRanges: undefined,
+ },
+ };
+
+ const jsonX = JSONX.getInstance();
+ const textX = deleteCustomRangeTextX(accessor, params);
+ if (!textX) {
+ return false;
+ }
+
doMutation.params.actions = jsonX.editOp(textX.serialize());
return doMutation;
}
diff --git a/packages/docs/src/basics/retain-delete-params.ts b/packages/docs/src/basics/retain-delete-params.ts
index 2ffb1befe9..980f3d9a21 100644
--- a/packages/docs/src/basics/retain-delete-params.ts
+++ b/packages/docs/src/basics/retain-delete-params.ts
@@ -57,7 +57,7 @@ export function getRetainAndDeleteFromReplace(
});
}
- const sortedRetains = [...retainPoints].sort();
+ const sortedRetains = [...retainPoints].sort((pre, aft) => pre - aft);
let cursor = textStart;
sortedRetains.forEach((pos) => {
const len = pos - cursor;
diff --git a/packages/docs/src/basics/selection.ts b/packages/docs/src/basics/selection.ts
index d53e6c812c..35e2ceb063 100644
--- a/packages/docs/src/basics/selection.ts
+++ b/packages/docs/src/basics/selection.ts
@@ -98,16 +98,6 @@ export function getInsertSelection(selection: ITextRange, body: IDocumentBody):
startOffset -= 1;
}
- // while (body.dataStream[endOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
- // endOffset -= 1;
- // startOffset -= 1;
- // }
-
- // while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
- // endOffset += 1;
- // startOffset += 1;
- // }
-
return {
startOffset,
endOffset,
diff --git a/packages/docs/src/commands/commands/break-line.command.ts b/packages/docs/src/commands/commands/break-line.command.ts
index 28689d2609..d0cedf01c2 100644
--- a/packages/docs/src/commands/commands/break-line.command.ts
+++ b/packages/docs/src/commands/commands/break-line.command.ts
@@ -15,8 +15,10 @@
*/
import type { ICommand, IParagraph } from '@univerjs/core';
-import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, Tools } from '@univerjs/core';
+import { CommandType, DataStreamTreeTokenType, getBodySlice, ICommandService, IUniverInstanceService, normalizeBody, Tools, updateAttributeByInsert } from '@univerjs/core';
+
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+import { getInsertSelection } from '../../basics/selection';
import { InsertCommand } from './core-editing.command';
function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {
@@ -51,9 +53,7 @@ function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IPa
export const BreakLineCommand: ICommand = {
id: 'doc.command.break-line',
-
type: CommandType.COMMAND,
-
handler: async (accessor) => {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -65,27 +65,57 @@ export const BreakLineCommand: ICommand = {
}
const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- if (docDataModel == null) {
+ const body = docDataModel?.getBody();
+ if (!docDataModel || !body) {
return false;
}
const unitId = docDataModel.getUnitId();
- const { startOffset, segmentId } = activeRange;
+ const { startOffset, endOffset } = getInsertSelection(activeRange, body);
+ const { segmentId } = activeRange;
const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
-
- // split paragraph into two.
- const result = await commandService.executeCommand(InsertCommand.id, {
- unitId,
- body: {
- dataStream: DataStreamTreeTokenType.PARAGRAPH,
- paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),
- },
- range: activeRange,
- segmentId,
- });
-
- return result;
+ // line breaks to 2
+ if (prevParagraph && prevParagraph.startIndex > endOffset) {
+ const bodyAfter = normalizeBody(getBodySlice(body, endOffset, prevParagraph.startIndex));
+ const deleteRange = {
+ startOffset,
+ endOffset: prevParagraph.startIndex,
+ collapsed: false,
+ };
+ updateAttributeByInsert(
+ bodyAfter,
+ {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),
+ },
+ 1,
+ 0
+ );
+ const result = await commandService.executeCommand(InsertCommand.id, {
+ unitId,
+ body: bodyAfter,
+ range: deleteRange,
+ segmentId,
+ cursorOffset: 1,
+ });
+
+ return result;
+ } else {
+ // split paragraph into two.
+ const result = await commandService.executeCommand(InsertCommand.id, {
+ unitId,
+ body: {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),
+ },
+ range: activeRange,
+ segmentId,
+ });
+
+ return result;
+ }
},
};
+
diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.ts
index 363e507512..61d1dd3ef6 100644
--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts
@@ -50,11 +50,11 @@ export interface IInnerPasteCommandParams {
// Actually, the command is to handle paste event.
export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
id: 'doc.command.inner-paste',
-
type: CommandType.COMMAND,
handler: async (accessor, params: IInnerPasteCommandParams) => {
- const { segmentId, body, textRanges } = params;
+ const { segmentId, textRanges } = params;
+ const body = params.body;
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -101,11 +101,6 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
} else {
const { dos } = getRetainAndDeleteFromReplace(selection, segmentId, memoryCursor.cursor, originBody);
textX.push(...dos);
- // doMutation.params.textRanges = [{
- // startOffset: cursor + body.dataStream.length,
- // endOffset: cursor + body.dataStream.length,
- // collapsed,
- // }];
}
textX.push({
@@ -267,7 +262,7 @@ function getRetainAndDeleteAndExcludeLineBreak(
retainPoints.add(paragraphIndex);
}
- const sortedRetains = [...retainPoints].sort();
+ const sortedRetains = [...retainPoints].sort((pre, aft) => pre - aft);
let cursor = textStart;
sortedRetains.forEach((pos) => {
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index c631354c9c..2fdeeabbaf 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -39,6 +39,7 @@ export interface IInsertCommandParams {
range: ITextRange;
textRanges?: ITextRangeWithStyle[];
segmentId?: string;
+ cursorOffset?: number;
}
export const EditorInsertTextCommandId = 'doc.command.insert-text';
@@ -50,19 +51,20 @@ 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, textRanges: propTextRanges, cursorOffset } = params;
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const { range, segmentId, body, unitId, textRanges: propTextRanges } = params;
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
- const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const activeRange = textSelectionManagerService.getActiveRange();
-
const originBody = docDataModel.getSelfOrHeaderFooterModel(activeRange?.segmentId ?? '').getBody();
if (!originBody) {
@@ -70,10 +72,11 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
}
const actualRange = getInsertSelection(range, originBody);
const { startOffset, collapsed } = actualRange;
+ const cursorMove = cursorOffset ?? body.dataStream.length;
const textRanges = [
{
- startOffset: startOffset + body.dataStream.length,
- endOffset: startOffset + body.dataStream.length,
+ startOffset: startOffset + cursorMove,
+ endOffset: startOffset + cursorMove,
style: activeRange?.style,
collapsed,
},
@@ -103,11 +106,13 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
} else {
const { dos, retain } = getRetainAndDeleteFromReplace(actualRange, segmentId, 0, originBody);
textX.push(...dos);
- doMutation.params.textRanges = [{
- startOffset: startOffset + body.dataStream.length + retain,
- endOffset: startOffset + body.dataStream.length + retain,
- collapsed,
- }];
+ if (!propTextRanges) {
+ doMutation.params.textRanges = [{
+ startOffset: startOffset + cursorMove + retain,
+ endOffset: startOffset + cursorMove + retain,
+ collapsed,
+ }];
+ }
}
textX.push({
@@ -173,7 +178,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
toDeleteRanges?.forEach((range) => {
deleteIndexes.push(range.startIndex, range.endIndex);
});
- deleteIndexes.sort();
+ deleteIndexes.sort((pre, aft) => pre - aft);
const deleteStart = deleteIndexes[0];
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.ts
index 7ad37f8b84..a9c4782787 100644
--- a/packages/docs/src/commands/commands/delete.command.ts
+++ b/packages/docs/src/commands/commands/delete.command.ts
@@ -17,6 +17,8 @@
import type { ICommand, IDocumentBody, IMutationInfo, IParagraph, ITextRun } from '@univerjs/core';
import {
CommandType,
+ getCustomDecorationSlice,
+ getCustomRangeSlice,
ICommandService,
IUniverInstanceService,
JSONX,
@@ -55,36 +57,38 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
const { direction, range } = params;
const activeRange = textSelectionManagerService.getActiveRange();
+ const ranges = textSelectionManagerService.getSelections();
- if (activeRange == null) {
+ if (activeRange == null || ranges == null) {
return false;
}
const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- if (docDataModel == null) {
+ const originBody = docDataModel?.getBody();
+ if (!docDataModel || !originBody) {
return false;
}
- const unitId = docDataModel.getUnitId();
- const { startOffset, collapsed, segmentId, style } = activeRange;
- if (!collapsed) {
- return false;
- }
+ const actualRange = getDeleteSelection(activeRange, originBody);
- const segmentDataModel = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const documentBody = segmentDataModel?.getBody();
+ const { segmentId, style } = activeRange;
+ const { startOffset, collapsed } = actualRange;
- if (documentBody == null) {
+ if (!collapsed) {
return false;
}
const startIndex = direction === DeleteDirection.LEFT ? startOffset : startOffset + 1;
-
- const endIndex = (documentBody.paragraphs ?? []).find((p) => p.startIndex >= startIndex)!.startIndex;
- const body = getParagraphBody(documentBody, startIndex, endIndex);
+ const endIndex = docDataModel
+ .getBody()
+ ?.paragraphs
+ ?.find((p) => p.startIndex >= startIndex)?.startIndex!;
+ const body = getParagraphBody(docDataModel.getBody()!, startIndex, endIndex);
const cursor = direction === DeleteDirection.LEFT ? startOffset - 1 : startOffset;
+ const unitId = docDataModel.getUnitId();
+
const textRanges = [
{
startOffset: cursor,
@@ -266,10 +270,13 @@ export const DeleteLeftCommand: ICommand = {
return true;
}
if (preGlyph.content === '\r') {
- result = await commandService.executeCommand(MergeTwoParagraphCommand.id, {
- direction: DeleteDirection.LEFT,
- range: actualRange,
- });
+ result = await commandService.executeCommand(
+ MergeTwoParagraphCommand.id,
+ {
+ direction: DeleteDirection.LEFT,
+ range: actualRange,
+ }
+ );
} else {
cursor -= preGlyph.count;
result = await commandService.executeCommand(DeleteCommand.id, {
@@ -388,6 +395,8 @@ function getParagraphBody(body: IDocumentBody, startIndex: number, endIndex: num
if (originTextRuns == null) {
return {
dataStream,
+ customRanges: getCustomRangeSlice(body, startIndex, endIndex).customRanges,
+ customDecorations: getCustomDecorationSlice(body, startIndex, endIndex),
};
}
@@ -423,6 +432,8 @@ function getParagraphBody(body: IDocumentBody, startIndex: number, endIndex: num
return {
dataStream,
textRuns,
+ customRanges: getCustomRangeSlice(body, startIndex, endIndex).customRanges,
+ customDecorations: getCustomDecorationSlice(body, startIndex, endIndex),
};
}
diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.ts
index 6202d2db9e..3f88ceb6c3 100644
--- a/packages/docs/src/doc-plugin.ts
+++ b/packages/docs/src/doc-plugin.ts
@@ -56,6 +56,7 @@ import { IMEInputManagerService } from './services/ime-input-manager.service';
import { TextSelectionManagerService } from './services/text-selection-manager.service';
import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from './commands/commands/paragraph-align.command';
+import { DocCustomRangeService } from './services/doc-custom-range.service';
export interface IUniverDocsConfig {
hasScroll?: boolean;
@@ -137,6 +138,7 @@ export class UniverDocsPlugin extends Plugin {
},
],
[TextSelectionManagerService],
+ [DocCustomRangeService],
// controllers
[NormalInputController],
[IMEInputController],
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 8faded834c..90336e08ea 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -24,6 +24,7 @@ export { DocSkeletonManagerService } from './services/doc-skeleton-manager.servi
export { TextSelectionManagerService, serializeTextRange } from './services/text-selection-manager.service';
export { DocStateChangeManagerService, type IDocStateChangeParams } from './services/doc-state-change-manager.service';
export { IMEInputManagerService } from './services/ime-input-manager.service';
+export { DocCustomRangeService, type ICustomRangeHook } from './services/doc-custom-range.service';
// #region - all commands
@@ -65,7 +66,7 @@ export {
} from './commands/commands/paragraph-align.command';
export { ReplaceContentCommand, CoverContentCommand } from './commands/commands/replace-content.command';
export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
-export { addCustomRangeFactory, addCustomRangeBySelectionFactory, deleteCustomRange } from './basics/custom-range-factory';
+export { addCustomRangeFactory, addCustomRangeBySelectionFactory, deleteCustomRangeFactory } from './basics/custom-range-factory';
export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleteCustomDecorationFactory } from './basics/custom-decoration-factory';
export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';
diff --git a/packages/docs/src/services/doc-custom-range.service.ts b/packages/docs/src/services/doc-custom-range.service.ts
new file mode 100644
index 0000000000..132cef6230
--- /dev/null
+++ b/packages/docs/src/services/doc-custom-range.service.ts
@@ -0,0 +1,56 @@
+/**
+ * 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 { CustomRangeType } from '@univerjs/core';
+import { toDisposable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+
+export interface ICustomRangeBase {
+ rangeId: string;
+ rangeType: CustomRangeType;
+}
+
+export interface ICustomRangeHook {
+ onCopyCustomRange?: (range: ICustomRangeBase) => ICustomRangeBase;
+}
+
+export class DocCustomRangeService {
+ private _customRangeHooks: ICustomRangeHook[] = [];
+
+ addClipboardHook(hook: ICustomRangeHook): IDisposable {
+ this._customRangeHooks.push(hook);
+
+ return toDisposable(() => {
+ const index = this._customRangeHooks.indexOf(hook);
+
+ if (index > -1) {
+ this._customRangeHooks.splice(index, 1);
+ }
+ });
+ }
+
+ copyCustomRange(range: ICustomRangeBase) {
+ let copy = { ...range };
+
+ this._customRangeHooks.forEach((hook) => {
+ if (hook.onCopyCustomRange) {
+ copy = hook.onCopyCustomRange(copy);
+ }
+ });
+
+ return copy;
+ }
+}
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 3b44e4a860..27aea1052e 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
@@ -18,16 +18,14 @@ import type { ICustomRangeForInterceptor, ITextStyle, Nullable } from '@univerjs
import { BooleanNumber, CustomRangeType } from '@univerjs/core';
export function getCustomRangeStyle(customRange: ICustomRangeForInterceptor): Nullable<ITextStyle> {
- if (customRange.rangeType === CustomRangeType.COMMENT) {
+ if (customRange.rangeType === CustomRangeType.HYPERLINK) {
return {
- bbl: {
+ ul: {
s: BooleanNumber.TRUE,
- cl: {
- rgb: '#fcdf7e',
- },
- c: BooleanNumber.FALSE,
},
- ...customRange.active ? { bg: { rgb: '#faedc2' } } : null,
+ cl: {
+ rgb: '#274fee',
+ },
};
}
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 3b5c04088f..187ab83c40 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -62,6 +62,7 @@ import type { DocumentViewModel } from '../view-model/document-view-model';
import type { Hyphen } from './hyphenation/hyphen';
import type { LanguageDetector } from './hyphenation/language-detector';
import { getCustomDecorationStyle } from './style/custom-decoration';
+import { getCustomRangeStyle } from './style/custom-range';
export function getLastPage(pages: IDocumentSkeletonPage[]) {
return pages[pages.length - 1];
@@ -765,16 +766,19 @@ export function getFontCreateConfig(
const customDecoration = viewModel.getCustomDecoration(index + startIndex);
const showCustomDecoration = customDecoration && (customDecoration.show !== false);
const customDecorationStyle = showCustomDecoration ? getCustomDecorationStyle(customDecoration) : null;
-
+ const customRange = viewModel.getCustomRange(index + startIndex);
+ const showCustomRange = customRange && (customRange.show !== false);
+ const customRangeStyle = showCustomRange ? getCustomRangeStyle(customRange) : null;
+ const hasAddonStyle = showCustomRange || showCustomDecoration;
const { st, ed } = textRun;
let { ts: textStyle = {} } = textRun;
const cache = fontCreateConfigCache.getValue(st, ed);
- if (cache && !customDecoration) {
+ if (cache && !hasAddonStyle) {
return cache;
}
const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
- textStyle = { ...documentTextStyle, ...textStyle, ...customDecorationStyle };
+ textStyle = { ...documentTextStyle, ...textStyle, ...customDecorationStyle, ...customRangeStyle };
const fontStyle = getFontStyleString(textStyle, localeService);
@@ -794,7 +798,7 @@ export function getFontCreateConfig(
pageWidth,
};
- if (!showCustomDecoration) {
+ if (!hasAddonStyle) {
fontCreateConfigCache.setValue(st, ed, result);
}
diff --git a/packages/engine-render/src/components/docs/text-selection/text-range.ts b/packages/engine-render/src/components/docs/text-selection/text-range.ts
index 1259af1a16..d85e7c9f8b 100644
--- a/packages/engine-render/src/components/docs/text-selection/text-range.ts
+++ b/packages/engine-render/src/components/docs/text-selection/text-range.ts
@@ -80,6 +80,28 @@ export function getAnchorBounding(pointsGroup: IPoint[][]) {
};
}
+export function getLineBounding(pointsGroup: IPoint[][]) {
+ return pointsGroup.map((line) => {
+ let xMin = Infinity;
+ let xMax = -Infinity;
+ let yMin = Infinity;
+ let yMax = -Infinity;
+ line.forEach((point) => {
+ xMin = Math.min(point.x, xMin);
+ xMax = Math.max(point.x, xMax);
+
+ yMax = Math.max(point.y, yMax);
+ yMin = Math.min(point.y, yMin);
+ });
+ return {
+ left: xMin,
+ right: xMax,
+ top: yMin,
+ bottom: yMax,
+ };
+ });
+}
+
export class TextRange {
// Identifies whether the range is the current one, most of which is the last range.
private _current = false;
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index 4102bc2630..f38fa53869 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -33,7 +33,7 @@ export * from './shape';
export * from './viewport';
export { DocumentViewModel } from './components/docs/view-model/document-view-model';
-export { getAnchorBounding, TEXT_RANGE_LAYER_INDEX, TextRange } from './components/docs/text-selection/text-range';
+export { getAnchorBounding, TEXT_RANGE_LAYER_INDEX, TextRange, getLineBounding } from './components/docs/text-selection/text-range';
export { NodePositionConvertToCursor } from './components/docs/text-selection/convert-cursor';
export { Liquid } from './components/docs/liquid';
export {
diff --git a/packages/sheets-hyper-link-ui/src/common/util.ts b/packages/sheets-hyper-link-ui/src/common/util.ts
index 43f1a39b1d..21176a9fbd 100644
--- a/packages/sheets-hyper-link-ui/src/common/util.ts
+++ b/packages/sheets-hyper-link-ui/src/common/util.ts
@@ -15,20 +15,10 @@
*/
import type { ICellData, Nullable } from '@univerjs/core';
-import { DEFAULT_EMPTY_DOCUMENT_VALUE } from '@univerjs/core';
-
-const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
-const regex = new RegExp(expression);
+import { DEFAULT_EMPTY_DOCUMENT_VALUE, Tools } from '@univerjs/core';
export function isLegalLink(link: string) {
- if (!Number.isNaN(+link)) {
- return false;
- }
-
- if (link.startsWith('http://localhost:3002') || link.startsWith('localhost:3002')) {
- return true;
- }
- return Boolean(link.match(regex));
+ return Tools.isLegalUrl(link);
}
export function hasProtocol(urlString: string) {
diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.ts
index 18fe197e5f..e038068498 100644
--- a/packages/ui/src/services/popup/canvas-popup.service.ts
+++ b/packages/ui/src/services/popup/canvas-popup.service.ts
@@ -24,6 +24,8 @@ import { BehaviorSubject } from 'rxjs';
export interface IPopup extends Pick<IRectPopupProps, 'closeOnSelfTarget' | 'direction' | 'excludeOutside' | 'onClickOutside' > {
anchorRect: IBoundRectNoAngle;
anchorRect$: Observable<IBoundRectNoAngle>;
+ excludeRects?: IBoundRectNoAngle[];
+ excludeRects$?: Observable<IBoundRectNoAngle[]>;
componentKey: string;
unitId: string;
diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsx
index 8aeefeddc0..aefe835f7e 100644
--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx
+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx
@@ -25,6 +25,7 @@ import type { IPopup } from '../../../services/popup/canvas-popup.service';
const SingleCanvasPopup = ({ popup, children }: { popup: IPopup; children?: React.ReactNode }) => {
const anchorRect = useObservable(popup.anchorRect$, popup.anchorRect);
+ const excludeRects = useObservable(popup.excludeRects$, popup.excludeRects);
const { bottom, left, right, top } = anchorRect;
const { offset } = popup;
@@ -45,6 +46,7 @@ const SingleCanvasPopup = ({ popup, children }: { popup: IPopup; children?: Reac
direction={popup.direction}
onClickOutside={popup.onClickOutside}
excludeOutside={popup.excludeOutside}
+ excludeRects={excludeRects}
closeOnSelfTarget={popup.closeOnSelfTarget}
>
{children}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 333383975d..a0a30b66da 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -222,6 +222,9 @@ importers:
'@univerjs/docs-drawing-ui':
specifier: workspace:*
version: link:../packages/docs-drawing-ui
+ '@univerjs/docs-hyper-link-ui':
+ specifier: workspace:*
+ version: link:../packages/docs-hyper-link-ui
'@univerjs/docs-thread-comment-ui':
specifier: workspace:*
version: link:../packages/docs-thread-comment-ui
@@ -728,6 +731,113 @@ importers:
specifier: ^1.6.0
+ packages/docs-hyper-link:
+ dependencies:
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/docs-ui':
+ specifier: workspace:*
+ version: link:../docs-ui
+ '@univerjs/icons':
+ specifier: ^0.1.58
+ '@univerjs/thread-comment':
+ specifier: workspace:*
+ version: link:../thread-comment
+ '@univerjs/thread-comment-ui':
+ specifier: workspace:*
+ version: link:../thread-comment-ui
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@wendellhu/redi':
+ specifier: 0.15.5
+ version: 0.15.5
+ clsx:
+ specifier: ^2.1.1
+ version: 2.1.1
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.4.5
+ version: 5.5.3
+ vite:
+ specifier: ^5.2.12
+ vitest:
+ specifier: ^1.6.0
+
+ packages/docs-hyper-link-ui:
+ dependencies:
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/docs-ui':
+ specifier: workspace:*
+ version: link:../docs-ui
+ '@univerjs/icons':
+ specifier: ^0.1.58
+ '@univerjs/thread-comment':
+ specifier: workspace:*
+ version: link:../thread-comment
+ '@univerjs/thread-comment-ui':
+ specifier: workspace:*
+ version: link:../thread-comment-ui
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/docs-hyper-link':
+ specifier: workspace:*
+ version: link:../docs-hyper-link
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ '@wendellhu/redi':
+ specifier: 0.15.5
+ version: 0.15.5
+ clsx:
+ specifier: ^2.1.1
+ version: 2.1.1
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.4.5
+ version: 5.5.3
+ vite:
+ specifier: ^5.2.12
+ vitest:
+ specifier: ^1.6.0
+
packages/docs-thread-comment-ui:
dependencies:
'@univerjs/docs':