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.

fix(sheets-ui): bugfix for data-validation/comments (#2734)

zhangw75bb1f601f21
diff --git a/examples/package.json b/examples/package.json
index 50d804aaf6..4f1bdb3fee 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": "workspace:*",
"@univerjs/docs-hyper-link-ui": "workspace:*",
"@univerjs/docs-thread-comment-ui": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 946e3ad953..7f0616f683 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -46,6 +46,7 @@ import { FUniver } from '@univerjs/facade';
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
+import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';
import { enUS, ruRU, viVN, zhCN, zhTW } from '../locales';
import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';
/* eslint-disable-next-line node/prefer-global/process */
@@ -75,6 +76,7 @@ univer.registerPlugin(UniverDocsPlugin, { hasScroll: false });
univer.registerPlugin(UniverRenderEnginePlugin);
univer.registerPlugin(UniverUIPlugin, { container: 'app' });
univer.registerPlugin(UniverDocsUIPlugin);
+univer.registerPlugin(UniverDocsHyperLinkPlugin);
univer.registerPlugin(UniverSheetsPlugin, { notExecuteFormula: true });
univer.registerPlugin(UniverSheetsUIPlugin);
diff --git a/packages/core/src/common/__tests__/url.spec.ts b/packages/core/src/common/__tests__/url.spec.ts
new file mode 100644
index 0000000000..eff828e41a
--- /dev/null
+++ b/packages/core/src/common/__tests__/url.spec.ts
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { isLegalUrl, normalizeUrl } from '../url';
+
+describe('Test url utils', () => {
+ it('should return true on legal url', () => {
+ expect(isLegalUrl('https://univer.ai/')).toBeTruthy();
+ expect(isLegalUrl('univer.ai')).toBeTruthy();
+ });
+
+ it('should return false on illegal url', () => {
+ expect(isLegalUrl('https://univer')).toBeFalsy();
+ expect(isLegalUrl('univer')).toBeFalsy();
+ expect(isLegalUrl('192.168')).toBeFalsy();
+ expect(isLegalUrl('咋看手机看到. 是多少')).toBeFalsy();
+ });
+
+ it('should add protocol to no protocol url', () => {
+ expect(normalizeUrl('univer.ai')).toEqual('https://univer.ai');
+ expect(normalizeUrl('https://univer.ai')).toEqual('https://univer.ai');
+ expect(normalizeUrl('[email protected]')).toEqual('mailto://[email protected]');
+ });
+});
diff --git a/packages/core/src/common/url.ts b/packages/core/src/common/url.ts
index c345c8750a..9ffc9bddfc 100644
--- a/packages/core/src/common/url.ts
+++ b/packages/core/src/common/url.ts
@@ -14,9 +14,47 @@
* 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);
-
+const re_weburl = new RegExp(
+ '^' +
+ // protocol identifier (optional)
+ // short syntax // still required
+ '(?:(?:(?:https?|ftp):)?\\/\\/)?' +
+ // user:pass BasicAuth (optional)
+ '(?:\\S+(?::\\S*)?@)?' +
+ '(?:' +
+ // IP address exclusion
+ // private & local networks
+ '(?!(?:10|127)(?:\\.\\d{1,3}){3})' +
+ '(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' +
+ '(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' +
+ // IP address dotted notation octets
+ // excludes loopback network 0.0.0.0
+ // excludes reserved space >= 224.0.0.0
+ // excludes network & broadcast addresses
+ // (first & last IP address of each class)
+ '(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
+ '(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
+ '(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
+ '|' +
+ // host & domain names, may end with dot
+ // can be replaced by a shortest alternative
+ // (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
+ '(?:' +
+ '(?:' +
+ '[a-z0-9\\u00a1-\\uffff]' +
+ '[a-z0-9\\u00a1-\\uffff_-]{0,62}' +
+ ')?' +
+ '[a-z0-9\\u00a1-\\uffff]\\.' +
+ ')+' +
+ // TLD identifier name, may end with dot
+ '(?:[a-z\\u00a1-\\uffff]{2,}\\.?)' +
+ ')' +
+ // port number (optional)
+ '(?::\\d{2,5})?' +
+ // resource path (optional)
+ '(?:[/?#]\\S*)?' +
+ '$', 'i'
+);
export function isLegalUrl(url: string) {
// skip number 0.1
if (!Number.isNaN(+url)) {
@@ -26,5 +64,19 @@ export function isLegalUrl(url: string) {
if (url.startsWith('http://localhost:3002') || url.startsWith('localhost:3002')) {
return true;
}
- return Boolean(url.match(regex));
+ return re_weburl.test(url);
+}
+
+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);
+}
+
+export function normalizeUrl(urlStr: string) {
+ return hasProtocol(urlStr) ? urlStr : isEmail(urlStr) ? `mailto://${urlStr}` : `https://${urlStr}`;
}
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index adb11f78db..9a35a5a754 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -25,7 +25,7 @@ import type {
} from '../../types/interfaces/i-document-data';
import type { IPaddingData } from '../../types/interfaces/i-style-data';
import { UnitModel, UniverInstanceType } from '../../common/unit';
-import { getBodySlice } from './text-x/utils';
+import { getBodySlice, SliceBodyType } from './text-x/utils';
import { getEmptySnapshot } from './empty-snapshot';
import type { JSONXActions } from './json-x/json-x';
import { JSONX } from './json-x/json-x';
@@ -298,14 +298,14 @@ export class DocumentDataModel extends DocumentDataModelSimple {
return this.snapshot;
}
- sliceBody(startOffset: number, endOffset: number): Nullable<IDocumentBody> {
+ sliceBody(startOffset: number, endOffset: number, type = SliceBodyType.copy): Nullable<IDocumentBody> {
const body = this.getBody();
if (body == null) {
return;
}
- return getBodySlice(body, startOffset, endOffset);
+ return getBodySlice(body, startOffset, endOffset, false, type);
}
private _initializeHeaderFooterModel() {
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 c5646239f7..3b3fbc8341 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
@@ -383,6 +383,12 @@ export function insertCustomRanges(
}
}
+ const currentRange = customRanges.find((range) => range.startIndex > currentIndex && range.endIndex < currentIndex);
+
+ if (currentRange) {
+ return;
+ }
+
const insertCustomRanges: ICustomRange[] = [];
if (insertBody.customRanges) {
for (let i = 0, len = insertBody.customRanges.length; i < len; i++) {
@@ -402,7 +408,6 @@ export function insertCustomRanges(
body.dataStream[oldCustomRange.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END;
if (isClosed) {
- insertCustomRanges.push(customRange);
continue;
}
// old is start
@@ -791,6 +796,7 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
}
body.customRanges = newCustomRanges;
}
+
return removeCustomRanges;
}
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
index 69b5873de3..36efceb513 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
@@ -50,7 +50,6 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
let removeDataStream = '';
if (dataStream) {
body.dataStream = deleteContent(dataStream, startIndex, endIndex);
-
removeDataStream = dataStream.slice(startIndex, endIndex);
}
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 26bb831ad7..68f1ee466b 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -21,13 +21,19 @@ import { DataStreamTreeTokenType } from '../types';
import type { IRetainAction } from './action-types';
import { coverTextRuns } from './apply-utils/update-apply';
+export enum SliceBodyType {
+ copy,
+ cut,
+}
+
// TODO: Support other properties like custom ranges, tables, etc.
// eslint-disable-next-line max-lines-per-function
export function getBodySlice(
body: IDocumentBody,
startOffset: number,
endOffset: number,
- returnEmptyTextRun = false
+ returnEmptyTextRun = false,
+ type = SliceBodyType.cut
): IDocumentBody {
const { dataStream, textRuns = [], paragraphs = [], customBlocks = [] } = body;
@@ -94,8 +100,9 @@ export function getBodySlice(
startIndex: p.startIndex - startOffset,
}));
}
-
- docBody.customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);
+ if (type === SliceBodyType.cut) {
+ docBody.customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);
+ }
const { customRanges } = getCustomRangeSlice(body, startOffset, endOffset);
docBody.customRanges = customRanges;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 257316a11b..c341db66d8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -46,7 +46,7 @@ export {
} from './docs/data-model/text-x/action-types';
export { DataValidationRenderMode } from './types/enum/data-validation-render-mode';
export { ActionIterator } from './docs/data-model/text-x/action-iterator';
-export { getBodySlice, composeBody } from './docs/data-model/text-x/utils';
+export { getBodySlice, composeBody, SliceBodyType } from './docs/data-model/text-x/utils';
export { TextX } from './docs/data-model/text-x/text-x';
export type { TPriority } from './docs/data-model/text-x/text-x';
export { JSONX, JSON1 } from './docs/data-model/json-x/json-x';
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index eb4044f7be..022310bba2 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -16,7 +16,7 @@
import { customAlphabet, nanoid } from 'nanoid';
-import { isLegalUrl } from '../common/url';
+import { isLegalUrl, normalizeUrl } from '../common/url';
import type { Class, IKeyValue } from './types';
const rmsPrefix = /^-ms-/;
@@ -447,6 +447,10 @@ export class Tools {
return isLegalUrl(url);
}
+ static normalizeUrl(url: string) {
+ return normalizeUrl(url);
+ }
+
static itCount(count: number): Function {
return (callback: Function) => {
for (let i = 0; i < count; i++) {
diff --git a/packages/core/src/types/interfaces/i-document-data-interceptor.ts b/packages/core/src/types/interfaces/i-document-data-interceptor.ts
new file mode 100644
index 0000000000..b76e064665
--- /dev/null
+++ b/packages/core/src/types/interfaces/i-document-data-interceptor.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICustomDecoration, ICustomRange } from './i-document-data';
+
+export interface ICustomRangeForInterceptor extends ICustomRange {
+ active?: boolean;
+ show?: boolean;
+}
+
+export interface ICustomDecorationForInterceptor extends ICustomDecoration {
+ active?: boolean;
+ show?: boolean;
+}
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 89af1d72cb..63d2e8e661 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -130,6 +130,12 @@ export interface IDocumentBody {
customRanges?: ICustomRange[]; // plugin register,implement special logic for streams, hyperlink, field,structured document tags, bookmark,comment
customDecorations?: ICustomDecoration[];
+
+ /**
+ * for copy/paste, data of custom-range and other module
+ * it won't save to disk
+ */
+ payloads?: Record<string, string>;
}
export interface IDocStyle {
@@ -273,16 +279,6 @@ export interface ICustomRange {
rangeType: CustomRangeType;
}
-export interface ICustomRangeForInterceptor extends ICustomRange {
- active?: boolean;
- show?: boolean;
-}
-
-export interface ICustomDecorationForInterceptor extends ICustomDecoration {
- active?: boolean;
- show?: boolean;
-}
-
export enum CustomRangeType {
HYPERLINK,
FIELD, // 17.16 Fields and Hyperlinks
diff --git a/packages/core/src/types/interfaces/index.ts b/packages/core/src/types/interfaces/index.ts
index 95ced0c1c7..91b043f9ac 100644
--- a/packages/core/src/types/interfaces/index.ts
+++ b/packages/core/src/types/interfaces/index.ts
@@ -17,6 +17,7 @@
export * from './i-cell-data';
export * from './i-column-data';
export * from './i-document-data';
+export * from './i-document-data-interceptor';
export * from './i-freeze';
export * from './i-image-properties';
export * from './i-placeholder';
diff --git a/packages/docs-drawing/package.json b/packages/docs-drawing/package.json
index 7869caef57..782a318a2b 100644
--- a/packages/docs-drawing/package.json
+++ b/packages/docs-drawing/package.json
@@ -60,7 +60,6 @@
"peerDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/drawing": "workspace:*",
- "@univerjs/engine-render": "workspace:*",
"@wendellhu/redi": "0.15.5",
"rxjs": ">=7.0.0"
},
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
index 1268a94ff8..4cfd79e5bc 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { CommandType, CustomRangeType, type ICommand, ICommandService, sequenceExecuteAsync, Tools } from '@univerjs/core';
+import { CommandType, CustomRangeType, type ICommand, ICommandService, sequenceExecute, Tools } from '@univerjs/core';
import { addCustomRangeBySelectionFactory } from '@univerjs/docs';
import { AddDocHyperLinkMutation } from '@univerjs/docs-hyper-link';
@@ -52,7 +52,7 @@ export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {
},
};
- return (await sequenceExecuteAsync([commentMutation, doMutation], commandService)).result;
+ return (await sequenceExecute([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
index 286f8c0f83..e114ce02be 100644
--- 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
@@ -27,7 +27,7 @@ export interface IDeleteDocHyperLinkMutationParams {
export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationParams> = {
type: CommandType.COMMAND,
id: 'docs.command.delete-hyper-link',
- handler(accessor, params) {
+ async handler(accessor, params) {
if (!params) {
return false;
}
@@ -44,6 +44,6 @@ export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationPara
return false;
}
- return commandService.executeCommand(doMutation.id, doMutation.params);
+ return await commandService.syncExecuteCommand(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
index e0ea2eb9e4..b75ce0c9b5 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
@@ -32,6 +32,6 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
}
const commandService = accessor.get(ICommandService);
- return commandService.executeCommand(UpdateDocHyperLinkMutation.id, params);
+ return commandService.syncExecuteCommand(UpdateDocHyperLinkMutation.id, params);
},
};
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
index 344a767139..2bfaa2bde0 100644
--- 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
@@ -43,11 +43,9 @@ export class DocHyperLinkClipboardController extends Disposable {
}
const activeRange = this._textSelectionManagerService.getActiveRange();
const customRanges = doc.getBody()?.customRanges;
- if (!customRanges?.length) {
- return body;
- }
+
const matchedRange = activeRange ?
- customRanges.find(
+ customRanges?.find(
(range) =>
range.rangeType === CustomRangeType.HYPERLINK &&
range.startIndex <= activeRange.startOffset &&
@@ -68,17 +66,25 @@ export class DocHyperLinkClipboardController extends Disposable {
}
return bodyWithoutLink;
} else {
- const customRangeIds = new Set(customRanges.map((i) => i.rangeType === CustomRangeType.HYPERLINK && i.rangeId));
+ 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();
+ if (range.rangeType === CustomRangeType.HYPERLINK) {
+ if (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;
+ }
+ } else if (body.payloads?.[range.rangeId]) {
+ const url = body.payloads[range.rangeId];
this._hyperLinkModel.addLink(doc.getUnitId(), {
- payload: link.payload,
- id: newId,
+ payload: url,
+ id: range.rangeId,
});
- range.rangeId = newId;
}
}
});
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
index 258a1b8ea9..d0821e5bca 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/render.controller.ts
@@ -39,7 +39,7 @@ export class DocHyperLinkRenderController extends Disposable implements IRenderM
return next(data);
}
const { unitId } = pos;
- const activeLink = this._hyperLinkService.editing;
+ const activeLink = this._hyperLinkService.showing;
const { linkId, unitId: linkUnitId } = activeLink || {};
const isActive = linkUnitId === unitId && data.rangeId === linkId;
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 08c610264e..2fab383b58 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -46,6 +46,11 @@ export class DocHyperLinkPopupService extends Disposable {
@ICommandService private readonly _commandService: ICommandService
) {
super();
+
+ this.disposeWithMe(() => {
+ this._editingLink$.complete();
+ this._showingLink$.complete();
+ });
}
get editing() {
diff --git a/packages/docs-hyper-link/package.json b/packages/docs-hyper-link/package.json
index f044f76162..a41a6e70a1 100644
--- a/packages/docs-hyper-link/package.json
+++ b/packages/docs-hyper-link/package.json
@@ -58,12 +58,14 @@
},
"peerDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/docs": "workspace:*",
"@wendellhu/redi": "0.15.5",
"rxjs": ">=7.0.0"
},
"devDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/docs": "workspace:*",
"@univerjs/shared": "workspace:*",
"@wendellhu/redi": "0.15.5",
"rxjs": "^7.8.1",
diff --git a/packages/docs-hyper-link/src/controllers/doc-hyper-link-custom-range.controller.ts b/packages/docs-hyper-link/src/controllers/doc-hyper-link-custom-range.controller.ts
new file mode 100644
index 0000000000..9e20185c17
--- /dev/null
+++ b/packages/docs-hyper-link/src/controllers/doc-hyper-link-custom-range.controller.ts
@@ -0,0 +1,72 @@
+/**
+ * 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 { CustomRangeType, Disposable, LifecycleStages, OnLifecycle, Tools } from '@univerjs/core';
+import { DocCustomRangeService } from '@univerjs/docs';
+import { Inject } from '@wendellhu/redi';
+import { DocHyperLinkModel } from '../models/hyper-link.model';
+
+@OnLifecycle(LifecycleStages.Ready, DocHyperLinkCustomRangeController)
+export class DocHyperLinkCustomRangeController extends Disposable {
+ constructor(
+ @Inject(DocCustomRangeService) private readonly _docCustomRangeService: DocCustomRangeService,
+ @Inject(DocHyperLinkModel) private readonly _docHyperLinkModel: DocHyperLinkModel
+ ) {
+ super();
+
+ this._initCustomRangeHooks();
+ }
+
+ private _initCustomRangeHooks() {
+ this.disposeWithMe(
+ this._docCustomRangeService.addClipboardHook({
+ onCopyCustomRange: (unitId, range) => {
+ const { rangeId, rangeType, data, ...ext } = range;
+
+ if (rangeType === CustomRangeType.HYPERLINK) {
+ if (data) {
+ const id = Tools.generateRandomId();
+ this._docHyperLinkModel.addLink(unitId, {
+ id,
+ payload: data,
+ });
+ return {
+ ...range,
+ rangeId: id,
+ };
+ }
+ const link = this._docHyperLinkModel.getLink(unitId, rangeId);
+ if (!link) {
+ return range;
+ }
+ const newId = Tools.generateRandomId();
+ this._docHyperLinkModel.addLink(unitId, {
+ id: newId,
+ payload: link.payload,
+ });
+
+ return {
+ ...ext,
+ rangeId: newId,
+ rangeType,
+ };
+ }
+ return range;
+ },
+ })
+ );
+ }
+}
diff --git a/packages/docs-hyper-link/src/models/hyper-link.model.ts b/packages/docs-hyper-link/src/models/hyper-link.model.ts
index 482b719149..3751aacfff 100644
--- a/packages/docs-hyper-link/src/models/hyper-link.model.ts
+++ b/packages/docs-hyper-link/src/models/hyper-link.model.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Disposable } from '@univerjs/core';
+import { Disposable, Tools } from '@univerjs/core';
import { Subject } from 'rxjs';
import type { IDocHyperLink } from '../types/interfaces/i-doc-hyper-link';
@@ -62,6 +62,7 @@ export class DocHyperLinkModel extends Disposable {
addLink(unitId: string, link: IDocHyperLink) {
const map = this._ensureMap(unitId);
+ link.payload = Tools.normalizeUrl(link.payload);
map.set(link.id, link);
this._linkUpdate$.next({
diff --git a/packages/docs-hyper-link/src/plugin.ts b/packages/docs-hyper-link/src/plugin.ts
index aa44a2702a..59a6760fbf 100644
--- a/packages/docs-hyper-link/src/plugin.ts
+++ b/packages/docs-hyper-link/src/plugin.ts
@@ -14,14 +14,17 @@
* limitations under the License.
*/
-import { Plugin, UniverInstanceType } from '@univerjs/core';
+import { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
+import { UniverDocsPlugin } from '@univerjs/docs';
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';
+import { DocHyperLinkCustomRangeController } from './controllers/doc-hyper-link-custom-range.controller';
+@DependentOn(UniverDocsPlugin)
export class UniverDocsHyperLinkPlugin extends Plugin {
static override pluginName = DOC_HYPER_LINK_PLUGIN;
static override type = UniverInstanceType.UNIVER_DOC;
@@ -37,6 +40,7 @@ export class UniverDocsHyperLinkPlugin extends Plugin {
[DocHyperLinkModel],
[DocHyperLinkController],
[DocHyperLinkResourceController],
+ [DocHyperLinkCustomRangeController],
];
deps.forEach((dep) => {
diff --git a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts
index 6325b92740..a2b9346ad6 100644
--- a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts
+++ b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts
@@ -88,7 +88,6 @@ export const StartAddCommentOperation: ICommand = {
const text = getSelectionText(doc.getBody()?.dataStream ?? '', textRange.startOffset, textRange.endOffset);
const subUnitId = DEFAULT_DOC_SUBUNIT_ID;
const commentId = '';
-
const comment = {
unitId,
subUnitId,
diff --git a/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
index daaf6cd2ce..6b224e22a7 100644
--- a/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
@@ -22,6 +22,7 @@ import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/
import { Inject } from '@wendellhu/redi';
import { DocBackScrollRenderController } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { ThreadCommentModel } from '@univerjs/thread-comment';
import { DEFAULT_DOC_SUBUNIT_ID } from '../common/const';
import { DocThreadCommentService } from '../services/doc-thread-comment.service';
import { ShowCommentPanelOperation } from '../commands/operations/show-comment-panel.operation';
@@ -33,7 +34,8 @@ export class DocThreadCommentSelectionController extends Disposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@Inject(DocThreadCommentService) private readonly _docThreadCommentService: DocThreadCommentService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(ThreadCommentModel) private readonly _threadCommentModel: ThreadCommentModel
) {
super();
@@ -60,13 +62,16 @@ export class DocThreadCommentSelectionController extends Disposable {
}
if (customRange) {
- this._commandService.executeCommand(ShowCommentPanelOperation.id, {
- activeComment: {
- unitId,
- subUnitId: DEFAULT_DOC_SUBUNIT_ID,
- commentId: customRange.id,
- },
- });
+ const comment = this._threadCommentModel.getComment(unitId, DEFAULT_DOC_SUBUNIT_ID, customRange.id);
+ if (comment && !comment.resolved) {
+ this._commandService.executeCommand(ShowCommentPanelOperation.id, {
+ activeComment: {
+ unitId,
+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,
+ commentId: customRange.id,
+ },
+ });
+ }
return;
}
}
diff --git a/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts b/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts
index c4a50bdd18..d0384e4106 100644
--- a/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts
+++ b/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-import type { ITextRange, Nullable } from '@univerjs/core';
+import { Disposable, type ITextRange, type Nullable } from '@univerjs/core';
import type { IThreadComment } from '@univerjs/thread-comment';
import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
import { ISidebarService } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
-export class DocThreadCommentService {
+export class DocThreadCommentService extends Disposable {
private _addingComment$ = new BehaviorSubject<Nullable<IThreadComment & ITextRange>>(undefined);
readonly addingComment$ = this._addingComment$.asObservable();
@@ -33,6 +33,11 @@ export class DocThreadCommentService {
@ISidebarService private readonly _sidebarService: ISidebarService,
@Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService
) {
+ super();
+
+ this.disposeWithMe(() => {
+ this._addingComment$.complete();
+ });
}
startAdd(comment: IThreadComment & ITextRange) {
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 86e1970cf1..5f8d2242b5 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import type { ICustomRange, IDocumentBody, IParagraph } from '@univerjs/core';
-import { Disposable, ICommandService, ILogService, IUniverInstanceService, normalizeBody, toDisposable } from '@univerjs/core';
+import type { DocumentDataModel, ICustomRange, IDocumentBody, IParagraph } from '@univerjs/core';
+import { CustomRangeType, DataStreamTreeTokenType, Disposable, ICommandService, ILogService, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } 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';
-import { CutContentCommand, getDeleteSelection, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';
+import { CutContentCommand, DocCustomRangeService, getDeleteSelection, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';
import { copyContentCache, extractId, genId } from './copy-content-cache';
import { HtmlToUDMService } from './html-to-udm/converter';
import PastePluginLark from './html-to-udm/paste-plugins/plugin-lark';
@@ -32,23 +32,6 @@ HtmlToUDMService.use(PastePluginWord);
HtmlToUDMService.use(PastePluginLark);
HtmlToUDMService.use(PastePluginUniver);
-function generateBody(text: string): IDocumentBody {
- // Convert all \n to \r, because we use \r to indicate paragraph break.
- const dataStream = text.replace(/\n/g, '\r');
- const paragraphs: IParagraph[] = [];
-
- for (let i = 0; i < dataStream.length; i++) {
- if (dataStream[i] === '\r') {
- paragraphs.push({ startIndex: i });
- }
- }
-
- return {
- dataStream,
- paragraphs,
- };
-}
-
export interface IClipboardPropertyItem { }
export interface IDocClipboardHook {
@@ -58,11 +41,10 @@ export interface IDocClipboardHook {
}
export interface IDocClipboardService {
- copy(): Promise<boolean>;
+ copy(sliceType?: SliceBodyType): Promise<boolean>;
cut(): Promise<boolean>;
paste(items: ClipboardItem[]): Promise<boolean>;
legacyPaste(html?: string, text?: string): Promise<boolean>;
-
addClipboardHook(hook: IDocClipboardHook): IDisposable;
}
@@ -79,13 +61,14 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
@ILogService private readonly _logService: ILogService,
@ICommandService private readonly _commandService: ICommandService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @Inject(DocCustomRangeService) private readonly _docCustomRangeService: DocCustomRangeService
) {
super();
}
- async copy(): Promise<boolean> {
- const documentBodyList = this._getDocumentBodyInRanges();
+ async copy(sliceType: SliceBodyType = SliceBodyType.copy): Promise<boolean> {
+ const documentBodyList = this._getDocumentBodyInRanges(sliceType);
if (documentBodyList.length === 0) {
return false;
@@ -136,7 +119,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
// Set content to clipboard.
- this.copy();
+ this.copy(SliceBodyType.cut);
try {
let cursor = activeEndOffset;
@@ -246,7 +229,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
});
}
- private _getDocumentBodyInRanges(): IDocumentBody[] {
+ private _getDocumentBodyInRanges(sliceType: SliceBodyType): IDocumentBody[] {
const ranges = this._textSelectionManagerService.getCurrentSelections();
const activeRange = this._textSelectionManagerService.getActiveRange();
const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
@@ -275,7 +258,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
const deleteRange = getDeleteSelection({ startOffset, endOffset, collapsed }, body);
- const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset);
+ const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
if (docBody == null) {
continue;
}
@@ -328,10 +311,48 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
}
+ private _generateBody(text: string): IDocumentBody {
+ // Convert all \n to \r, because we use \r to indicate paragraph break.
+ const dataStream = text.replace(/\n/g, '\r');
+
+ if (!text.includes('\r') && Tools.isLegalUrl(text)) {
+ const id = Tools.generateRandomId();
+ const docDataModel = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
+ const range = this._docCustomRangeService.copyCustomRange(
+ docDataModel.getUnitId(),
+ {
+ startIndex: 0,
+ endIndex: dataStream.length - 1,
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ data: text,
+ }
+ );
+
+ return {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,
+ customRanges: [range],
+ };
+ }
+
+ const paragraphs: IParagraph[] = [];
+
+ for (let i = 0; i < dataStream.length; i++) {
+ if (dataStream[i] === '\r') {
+ paragraphs.push({ startIndex: i });
+ }
+ }
+
+ return {
+ dataStream,
+ paragraphs,
+ };
+ }
+
private _generateBodyFromHtmlAndText(html?: string, text?: string): IDocumentBody {
if (!html) {
if (text) {
- return generateBody(text);
+ return this._generateBody(text);
} else {
throw new Error('[DocClipboardService] html and text cannot be both empty!');
}
diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
index b81ad9ddd6..8c27b9fedf 100644
--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { type IDocumentBody, type ITextStyle, type Nullable, skipParseTagNames } from '@univerjs/core';
+import { CustomRangeType, DataStreamTreeTokenType, type IDocumentBody, type ITextStyle, type Nullable, skipParseTagNames, Tools } from '@univerjs/core';
import { extractNodeStyle } from './parse-node-style';
import parseToDom from './parse-to-dom';
@@ -57,7 +57,6 @@ export class HtmlToUDMService {
convert(html: string): IDocumentBody {
const pastePlugin = HtmlToUDMService._pluginList.find((plugin) => plugin.checkPasteType(html));
-
const dom = parseToDom(html);
const newDocBody: IDocumentBody = {
@@ -87,9 +86,29 @@ export class HtmlToUDMService {
}
// TODO: @JOCS, More characters need to be replaced, like `\b`
- const text = node.nodeValue?.replace(/[\r\n]/g, '');
+ let text = node.nodeValue?.replace(/[\r\n]/g, '');
let style;
+ if (parent && parent.nodeType === Node.ELEMENT_NODE) {
+ if ((parent as Element).tagName.toUpperCase() === 'A') {
+ const id = Tools.generateRandomId();
+ text = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ doc.customRanges = [
+ ...(doc.customRanges ?? []),
+ {
+ startIndex: doc.dataStream.length,
+ endIndex: doc.dataStream.length + text.length - 1,
+ rangeId: id,
+ rangeType: CustomRangeType.HYPERLINK,
+ },
+ ];
+ doc.payloads = {
+ ...doc.payloads,
+ [id]: (parent as HTMLAnchorElement).href,
+ };
+ }
+ }
+
if (parent && this._styleCache.has(parent)) {
style = this._styleCache.get(parent);
}
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 8c6727f9db..3c1cb8015a 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -99,7 +99,7 @@ export class DocCanvasPopManagerService extends Disposable {
left: offsetBound.left,
right: offsetBound.right,
top: offsetBound.top + topOffset,
- bottom: offsetBound.bottom,
+ bottom: offsetBound.bottom + topOffset,
};
return position;
};
@@ -150,7 +150,7 @@ export class DocCanvasPopManagerService extends Disposable {
left: i.left + docsLeft,
right: i.right + docsLeft,
top: i.top + docsTop + top,
- bottom: i.bottom + docsTop,
+ bottom: i.bottom + docsTop + top,
}));
return res;
};
@@ -250,6 +250,7 @@ export class DocCanvasPopManagerService extends Disposable {
excludeRects$: bounds$,
direction: direction === 'top' ? 'top' : 'bottom',
});
+
return {
dispose: () => {
this._globalPopupManagerService.removePopup(id);
diff --git a/packages/docs/src/basics/__tests__/plain-text.spec.ts b/packages/docs/src/basics/__tests__/plain-text.spec.ts
new file mode 100644
index 0000000000..a846cbde14
--- /dev/null
+++ b/packages/docs/src/basics/__tests__/plain-text.spec.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.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { getPlainTextFormDocument } from '../plain-text';
+
+describe('Test getPlainTextFormDocument', () => {
+ it('should return plain text without special tags', () => {
+ expect(getPlainTextFormDocument({
+ body: {
+ dataStream: '\x1E123\x1F\r\n',
+ },
+ id: '',
+ documentStyle: {},
+ })).toEqual('123');
+ });
+});
diff --git a/packages/docs/src/basics/plain-text.ts b/packages/docs/src/basics/plain-text.ts
new file mode 100644
index 0000000000..3ff40f9b14
--- /dev/null
+++ b/packages/docs/src/basics/plain-text.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.
+ */
+
+import { DataStreamTreeTokenType, type IDocumentData } from '@univerjs/core';
+
+/**
+ * get plain text from rich-text
+ */
+export const getPlainTextFormDocument = (data: IDocumentData) => {
+ if (!data.body) {
+ return '';
+ }
+ const str = data.body.dataStream.slice(0, -2);
+ return str.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');
+};
diff --git a/packages/docs/src/commands/commands/break-line.command.ts b/packages/docs/src/commands/commands/break-line.command.ts
index 26108ce59d..1dd0acc80f 100644
--- a/packages/docs/src/commands/commands/break-line.command.ts
+++ b/packages/docs/src/commands/commands/break-line.command.ts
@@ -19,6 +19,7 @@ import { CommandType, DataStreamTreeTokenType, getBodySlice, ICommandService, IU
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import { getInsertSelection } from '../../basics/selection';
+import { DocCustomRangeService } from '../../services/doc-custom-range.service';
import { InsertCommand } from './core-editing.command';
function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {
@@ -58,6 +59,7 @@ export const BreakLineCommand: ICommand = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
+ const customRangeService = accessor.get(DocCustomRangeService);
const activeRange = textSelectionManagerService.getActiveRange();
if (activeRange == null) {
@@ -78,6 +80,9 @@ export const BreakLineCommand: ICommand = {
// line breaks to 2
if (prevParagraph && prevParagraph.startIndex > endOffset) {
const bodyAfter = normalizeBody(getBodySlice(body, endOffset, prevParagraph.startIndex));
+
+ bodyAfter.customRanges = bodyAfter.customRanges?.map((range) => customRangeService.copyCustomRange(unitId, range));
+
const deleteRange = {
startOffset,
endOffset: prevParagraph.startIndex,
diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.ts
index 0bd10810e1..b9c9f94c6d 100644
--- a/packages/docs/src/commands/commands/delete.command.ts
+++ b/packages/docs/src/commands/commands/delete.command.ts
@@ -30,12 +30,14 @@ import {
import type { IActiveTextRange, ITextRangeWithStyle, TextRange } from '@univerjs/engine-render';
import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';
+import type { IAccessor } from '@wendellhu/redi';
import type { ITextActiveRange } from '../../services/text-selection-manager.service';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
import { getDeleteSelection, getInsertSelection } from '../../basics/selection';
import { getCommandSkeleton, getRichTextEditPath } from '../util';
+import { DocCustomRangeService } from '../../services/doc-custom-range.service';
import { CutContentCommand } from './clipboard.inner.command';
import { DeleteCommand, DeleteDirection, UpdateCommand } from './core-editing.command';
@@ -162,6 +164,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
}
const actualRange = getDeleteSelection(activeRange, originBody);
+ const unitId = docDataModel.getUnitId();
const { startOffset, collapsed } = actualRange;
if (!collapsed) {
@@ -171,12 +174,9 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
const startIndex = direction === DeleteDirection.LEFT ? startOffset : startOffset + 1;
const endIndex = originBody.paragraphs
?.find((p) => p.startIndex >= startIndex)?.startIndex!;
- const body = getParagraphBody(originBody, startIndex, endIndex);
-
+ const body = getParagraphBody(accessor, unitId, originBody, startIndex, endIndex);
const cursor = direction === DeleteDirection.LEFT ? startOffset - 1 : startOffset;
- const unitId = docDataModel.getUnitId();
-
const textRanges = [
{
startOffset: cursor,
@@ -560,13 +560,14 @@ export const DeleteRightCommand: ICommand = {
},
};
-function getParagraphBody(body: IDocumentBody, start: number, end: number): IDocumentBody {
+function getParagraphBody(accessor: IAccessor, unitId: string, body: IDocumentBody, start: number, end: number): IDocumentBody {
const { textRuns: originTextRuns = [], customBlocks: originCustomBlocks = [] } = body;
const dataStream = body.dataStream.substring(start, end);
+ const customRangeService = accessor.get(DocCustomRangeService);
const bodySlice: IDocumentBody = {
dataStream,
- customRanges: getCustomRangeSlice(body, start, end).customRanges,
+ customRanges: getCustomRangeSlice(body, start, end).customRanges.map((range) => customRangeService.copyCustomRange(unitId, range)),
customDecorations: getCustomDecorationSlice(body, start, end),
};
diff --git a/packages/docs/src/commands/commands/ime-input.command.ts b/packages/docs/src/commands/commands/ime-input.command.ts
index f9ebdc2e6f..7316e502db 100644
--- a/packages/docs/src/commands/commands/ime-input.command.ts
+++ b/packages/docs/src/commands/commands/ime-input.command.ts
@@ -41,7 +41,6 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
// eslint-disable-next-line max-lines-per-function
handler: async (accessor, params: IIMEInputCommandParams) => {
const { unitId, newText, oldTextLen, isCompositionEnd, isCompositionStart } = params;
- // console.log('===ime', params);
const commandService = accessor.get(ICommandService);
const imeInputManagerService = accessor.get(IMEInputManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 51e1461df1..02fa779936 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -93,20 +93,15 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
};
}
- // console.log(params);
- // console.log('redoActions', actions);
-
// Step 1: Update Doc Data Model.
const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());
// console.log('undoActions', undoActions);
documentDataModel.apply(actions);
-
- // console.log('trigger', trigger);
- // console.log(documentDataModel);
+ // console.log('===redoActions', { actions, undoActions, noHistory });
+ // console.log('===body', documentDataModel);
// Step 2: Update Doc View Model.
documentViewModel.reset(documentDataModel);
-
// Step 3: Update cursor & selection.
// Make sure update cursor & selection after doc skeleton is calculated.
if (!noNeedSetTextRange && textRanges && trigger != null) {
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 51bbcb0a1e..dff427637a 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -83,6 +83,9 @@ export {
SetTextSelectionsOperation,
type ISetTextSelectionsOperationParams,
} from './commands/operations/text-selection.operation';
+
+// #endregion
+
export { getRetainAndDeleteFromReplace } from './basics/retain-delete-params';
export { getRichTextEditPath } from './commands/util';
-// #endregion
+export { getPlainTextFormDocument } from './basics/plain-text';
diff --git a/packages/docs/src/services/doc-custom-range.service.ts b/packages/docs/src/services/doc-custom-range.service.ts
index 132cef6230..9e911129cf 100644
--- a/packages/docs/src/services/doc-custom-range.service.ts
+++ b/packages/docs/src/services/doc-custom-range.service.ts
@@ -14,17 +14,16 @@
* limitations under the License.
*/
-import type { CustomRangeType } from '@univerjs/core';
+import type { ICustomRange } from '@univerjs/core';
import { toDisposable } from '@univerjs/core';
import type { IDisposable } from '@wendellhu/redi';
-export interface ICustomRangeBase {
- rangeId: string;
- rangeType: CustomRangeType;
+export interface ICustomRangeData extends ICustomRange {
+ data?: string;
}
export interface ICustomRangeHook {
- onCopyCustomRange?: (range: ICustomRangeBase) => ICustomRangeBase;
+ onCopyCustomRange?: (unitId: string, range: ICustomRangeData) => ICustomRange;
}
export class DocCustomRangeService {
@@ -42,12 +41,12 @@ export class DocCustomRangeService {
});
}
- copyCustomRange(range: ICustomRangeBase) {
+ copyCustomRange(unitId: string, range: ICustomRangeData) {
let copy = { ...range };
this._customRangeHooks.forEach((hook) => {
if (hook.onCopyCustomRange) {
- copy = hook.onCopyCustomRange(copy);
+ copy = hook.onCopyCustomRange(unitId, 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 27aea1052e..34e1c5763f 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
@@ -20,12 +20,8 @@ import { BooleanNumber, CustomRangeType } from '@univerjs/core';
export function getCustomRangeStyle(customRange: ICustomRangeForInterceptor): Nullable<ITextStyle> {
if (customRange.rangeType === CustomRangeType.HYPERLINK) {
return {
- ul: {
- s: BooleanNumber.TRUE,
- },
- cl: {
- rgb: '#274fee',
- },
+ ...customRange.active ? { ul: { s: BooleanNumber.TRUE } } : null,
+ cl: { rgb: '#274fee' },
};
}
diff --git a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
index 2754dd305a..fa72dac76b 100644
--- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
@@ -91,6 +91,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
this.disposeWithMe(this._editorBridgeService.visible$.subscribe((visible) => {
if (!visible.visible) {
+ this._dropdownManagerService.hideDropdown();
return;
}
@@ -128,18 +129,21 @@ export class SheetsDataValidationRenderController extends RxDisposable {
return;
}
- this._dropdownManagerService.showDropdown({
- location: {
- unitId,
- subUnitId: sheetId,
- row,
- col: column,
- workbook,
- worksheet,
+ this._dropdownManagerService.showDropdown(
+ {
+ location: {
+ unitId,
+ subUnitId: sheetId,
+ row,
+ col: column,
+ workbook,
+ worksheet,
+ },
+ componentKey: validator.dropdown,
+ onHide: () => { /* empty */ },
},
- componentKey: validator.dropdown,
- onHide: () => { /* empty */ },
- });
+ false
+ );
}
}));
}
diff --git a/packages/sheets-data-validation/src/services/data-validation-panel.service.ts b/packages/sheets-data-validation/src/services/data-validation-panel.service.ts
index 259115c3b4..eaa2629900 100644
--- a/packages/sheets-data-validation/src/services/data-validation-panel.service.ts
+++ b/packages/sheets-data-validation/src/services/data-validation-panel.service.ts
@@ -57,7 +57,7 @@ export class DataValidationPanelService extends Disposable {
this._open$.next(false);
this._open$.complete();
-
+ this._activeRule$.complete();
this._closeDisposable?.dispose();
}
diff --git a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts b/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
index b4eba7f4b1..6ee1957e1f 100644
--- a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
+++ b/packages/sheets-data-validation/src/services/dropdown-manager.service.ts
@@ -61,6 +61,10 @@ export class DataValidationDropdownManagerService extends Disposable {
) {
super();
this._init();
+
+ this.disposeWithMe(() => {
+ this._activeDropdown$.complete();
+ });
}
private _init() {
@@ -72,7 +76,7 @@ export class DataValidationDropdownManagerService extends Disposable {
}));
}
- showDropdown(param: IDropdownParam) {
+ showDropdown(param: IDropdownParam, closeOnOutSide = true) {
const { location } = param;
const { row, col } = location;
@@ -91,7 +95,9 @@ export class DataValidationDropdownManagerService extends Disposable {
{
componentKey: DROP_DOWN_KEY,
onClickOutside: () => {
- this.hideDropdown();
+ if (closeOnOutSide) {
+ this.hideDropdown();
+ }
},
offset: [0, 3],
excludeOutside: [currentRender?.engine.getCanvasElement()].filter(Boolean) as HTMLElement[],
diff --git a/packages/sheets-data-validation/src/services/dv.service.ts b/packages/sheets-data-validation/src/services/dv.service.ts
index 9ec56f4cf4..ed2969897b 100644
--- a/packages/sheets-data-validation/src/services/dv.service.ts
+++ b/packages/sheets-data-validation/src/services/dv.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import { Disposable, type Nullable } from '@univerjs/core';
import { Subject } from 'rxjs';
import { DataValidationModel } from '@univerjs/data-validation';
import { Inject } from '@wendellhu/redi';
@@ -26,7 +26,7 @@ export interface ICurrentDataValidationManager {
subUnitId: string;
}
-export class SheetDataValidationService {
+export class SheetDataValidationService extends Disposable {
private _currentManager: Nullable<ICurrentDataValidationManager>;
private _currentManager$ = new Subject<ICurrentDataValidationManager>();
@@ -41,6 +41,10 @@ export class SheetDataValidationService {
@Inject(DataValidationModel) private _dataValidationModel: DataValidationModel
) {
// empty
+ super();
+ this.disposeWithMe(() => {
+ this._currentManager$.complete();
+ });
}
private _ensureManager(unitId: string, subUnitId: string) {
diff --git a/packages/sheets-data-validation/src/validators/date-validator.ts b/packages/sheets-data-validation/src/validators/date-validator.ts
index 119d401f21..3e42434287 100644
--- a/packages/sheets-data-validation/src/validators/date-validator.ts
+++ b/packages/sheets-data-validation/src/validators/date-validator.ts
@@ -89,7 +89,7 @@ export class DateValidator extends BaseDataValidator<number> {
override async isValidType(info: IValidatorCellInfo): Promise<boolean> {
const { value } = info;
if (typeof value === 'string') {
- return dayjs(value).isValid();
+ return dayjs(value, 'YYYY-MM-DD HH:mm:ss', true).isValid();
}
if (typeof value === 'number') {
diff --git a/packages/sheets-data-validation/src/views/date-dropdown/index.tsx b/packages/sheets-data-validation/src/views/date-dropdown/index.tsx
index de3b342b05..0e7e9158c3 100644
--- a/packages/sheets-data-validation/src/views/date-dropdown/index.tsx
+++ b/packages/sheets-data-validation/src/views/date-dropdown/index.tsx
@@ -41,7 +41,11 @@ const transformDate = (value: Nullable<CellValue>) => {
return dayjs(date);
}
- return dayjs(value);
+ const date = dayjs(value);
+ if (date.isValid()) {
+ return date;
+ }
+ return undefined;
};
export function DateDropdown(props: IDropdownComponentProps) {
diff --git a/packages/sheets-data-validation/src/views/detail/index.tsx b/packages/sheets-data-validation/src/views/detail/index.tsx
index 0b03273062..c23e8438d3 100644
--- a/packages/sheets-data-validation/src/views/detail/index.tsx
+++ b/packages/sheets-data-validation/src/views/detail/index.tsx
@@ -162,9 +162,10 @@ export function DataValidationDetail() {
const operators = validator.operators;
const rule = dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
- const newRule = newType === rule?.type
+ const newRule = (newType === rule?.type || (newType.includes('list') && rule?.type.includes('list')))
? {
...rule,
+ type: newType as DataValidationType,
}
: {
...localRule,
@@ -261,7 +262,7 @@ export function DataValidationDetail() {
{FormulaInput
? (
<FormulaInput
- key={key}
+ key={key + localRule.type}
isTwoFormula={isTwoFormula}
value={{
formula1: localRule.formula1,
diff --git a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx b/packages/sheets-data-validation/src/views/list-dropdown/index.tsx
index c4d4d9ed21..0be2f5c1b3 100644
--- a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx
+++ b/packages/sheets-data-validation/src/views/list-dropdown/index.tsx
@@ -148,6 +148,9 @@ export function ListDropDown(props: IDropdownComponentProps) {
p: null,
f: null,
si: null,
+ custom: {
+ __link_url: '',
+ },
},
};
diff --git a/packages/sheets-hyper-link-ui/package.json b/packages/sheets-hyper-link-ui/package.json
index b7681a3b0b..061170647b 100644
--- a/packages/sheets-hyper-link-ui/package.json
+++ b/packages/sheets-hyper-link-ui/package.json
@@ -67,6 +67,8 @@
"peerDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-hyper-link": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/sheets": "workspace:*",
@@ -84,6 +86,8 @@
},
"devDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-hyper-link": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
diff --git a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
index e222ad7ee1..b98bdadbde 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
@@ -153,10 +153,7 @@ export class SheetsHyperLinkCopyPasteController extends Disposable {
if (!this._copyInfo) {
return { redos: [], undos: [] };
}
- if (copyInfo.copyType === COPY_TYPE.CUT) {
- this._copyInfo = null;
- return { redos: [], undos: [] };
- }
+
if (!this._copyInfo || !this._copyInfo.matrix.getSizeOf() || !copyInfo.copyRange) {
return { redos: [], undos: [] };
}
@@ -245,9 +242,6 @@ export class SheetsHyperLinkCopyPasteController extends Disposable {
});
});
- return {
- redos,
- undos,
- };
+ return { redos, undos };
}
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
index 68eef74c7c..43afb4df86 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
@@ -15,12 +15,15 @@
*/
import type { IMutationInfo, Workbook } from '@univerjs/core';
-import { CellValueType, Disposable, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Tools, UniverInstanceType } from '@univerjs/core';
+import { CellValueType, CustomRangeType, Disposable, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Tools, UniverInstanceType } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, getSheetCommandTarget, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAddHyperLinkCommandParams, IUpdateHyperLinkCommandParams } from '@univerjs/sheets-hyper-link';
import { AddHyperLinkCommand, AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation, UpdateHyperLinkCommand } from '@univerjs/sheets-hyper-link';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { DOC_HYPER_LINK_PLUGIN } from '@univerjs/docs-hyper-link';
+import { getPlainTextFormDocument } from '@univerjs/docs';
import { isLegalLink, serializeUrl } from '../common/util';
@OnLifecycle(LifecycleStages.Starting, SheetHyperLinkSetRangeController)
@@ -30,7 +33,8 @@ export class SheetHyperLinkSetRangeController extends Disposable {
@Inject(Injector) private readonly _injector: Injector,
@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
) {
super();
@@ -42,6 +46,11 @@ export class SheetHyperLinkSetRangeController extends Disposable {
this._initSetRangeValuesCommandInterceptor();
this._initUpdateHyperLinkCommandInterceptor();
this._initClearSelectionCommandInterceptor();
+ this._initRichTextEditorInterceptor();
+ }
+
+ private _getCurrentCell(unitId: string, subUnitId: string, row: number, col: number) {
+ return this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)?.getSheetBySheetId(subUnitId)?.getCell(row, col);
}
private _initAddHyperLinkCommandInterceptor() {
@@ -138,7 +147,6 @@ export class SheetHyperLinkSetRangeController extends Disposable {
getMutations: (command) => {
if (command.id === SetRangeValuesCommand.id) {
const params = command.params as ISetRangeValuesMutationParams;
-
const { unitId, subUnitId } = params;
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
@@ -148,7 +156,8 @@ export class SheetHyperLinkSetRangeController extends Disposable {
const cellValue = (cellValueRaw ?? '').toString();
const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);
if (!link) {
- if (isLegalLink(cellValue)) {
+ if (isLegalLink(cellValue) || cell?.custom?.__link_url) {
+ const url = cell?.custom?.__link_url ?? cellValue;
const id = Tools.generateRandomId();
undos.push({
id: RemoveHyperLinkMutation.id,
@@ -168,7 +177,7 @@ export class SheetHyperLinkSetRangeController extends Disposable {
row,
column: col,
display: cellValue,
- payload: serializeUrl(cellValue),
+ payload: serializeUrl(url),
},
},
});
@@ -176,7 +185,7 @@ export class SheetHyperLinkSetRangeController extends Disposable {
return;
}
- if (cellValueRaw === '') {
+ if (cellValueRaw === '' || cell?.custom?.__link_url === '') {
redos.push({
id: RemoveHyperLinkMutation.id,
params: {
@@ -261,7 +270,35 @@ export class SheetHyperLinkSetRangeController extends Disposable {
}));
}
- private _getCurrentCell(unitId: string, subUnitId: string, row: number, col: number) {
- return this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)?.getSheetBySheetId(subUnitId)?.getCell(row, col);
+ private _initRichTextEditorInterceptor() {
+ this.disposeWithMe(
+ this._editorBridgeService.interceptor.intercept(
+ this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT,
+ {
+ handler: (data, context, next) => {
+ if (data?.p) {
+ const range = data.p.body?.customRanges?.find((i) => i.rangeType === CustomRangeType.HYPERLINK);
+ const resource = data.p.resources?.find((i) => i.name === DOC_HYPER_LINK_PLUGIN);
+ if (range && resource) {
+ const rangeId = range.rangeId;
+ const url = JSON.parse(resource.data)?.links?.find((i: { id: string; payload: string }) => i.id === rangeId)?.payload;
+
+ return next({
+ ...data,
+ p: null,
+ v: getPlainTextFormDocument(data.p),
+ t: CellValueType.STRING,
+ custom: {
+ __link_url: url,
+ },
+ });
+ }
+ }
+
+ return next(data);
+ },
+ }
+ )
+ );
}
}
diff --git a/packages/sheets-hyper-link/src/plugin.ts b/packages/sheets-hyper-link/src/plugin.ts
index 34eab1e9cd..701576b015 100644
--- a/packages/sheets-hyper-link/src/plugin.ts
+++ b/packages/sheets-hyper-link/src/plugin.ts
@@ -14,15 +14,17 @@
* limitations under the License.
*/
-import { Plugin, UniverInstanceType } from '@univerjs/core';
+import { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
import { SheetsHyperLinkController } from './controllers/sheet-hyper-link.controller';
import { HyperLinkModel } from './models/hyper-link.model';
import { SHEET_HYPER_LINK_PLUGIN } from './types/const';
import { SheetsHyperLinkResourceController } from './controllers/sheet-hyper-link-resource.controller';
import { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';
+@DependentOn(UniverSheetsPlugin)
export class UniverSheetsHyperLinkPlugin extends Plugin {
static override pluginName = SHEET_HYPER_LINK_PLUGIN;
static override type = UniverInstanceType.UNIVER_SHEET;
diff --git a/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts b/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts
index 879ef674a9..41f6211c4c 100644
--- a/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts
+++ b/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts
@@ -39,6 +39,9 @@ export class SheetsThreadCommentModel extends Disposable {
) {
super();
this._init();
+ this.disposeWithMe(() => {
+ this._commentUpdate$.complete();
+ });
}
private _init() {
diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
index 55a6771374..97258e7327 100644
--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DependencyOverride, Workbook } from '@univerjs/core';
+import type { DependencyOverride, Nullable, Workbook } from '@univerjs/core';
import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import type { MenuConfig } from '@univerjs/ui';
import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';
@@ -26,7 +26,7 @@ import { RangeProtectionPermissionViewPoint, SelectionMoveType, SetSelectionsOpe
import { singleReferenceToGrid } from '@univerjs/engine-formula';
import type { IDeleteCommentMutationParams } from '@univerjs/thread-comment';
import { DeleteCommentMutation } from '@univerjs/thread-comment';
-import { ScrollToRangeOperation, SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
+import { IMarkSelectionService, ScrollToRangeOperation, SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';
import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment-base';
import { SheetsThreadCommentCell } from '../views/sheets-thread-comment-cell';
import { COMMENT_SINGLE_ICON, SHEETS_THREAD_COMMENT_MODAL } from '../types/const';
@@ -43,8 +43,18 @@ export const DefaultSheetsThreadCommentConfig: IUniverSheetsThreadCommentConfig
};
+interface ISelectionShapeInfo {
+ shapeId: string;
+ unitId: string;
+ subUnitId: string;
+ commentId: string;
+}
+
@OnLifecycle(LifecycleStages.Starting, SheetsThreadCommentController)
export class SheetsThreadCommentController extends Disposable {
+ private _isSwitchToCommenting = false;
+ private _selectionShapeInfo: Nullable<ISelectionShapeInfo> = null;
+
constructor(
private readonly _config: Partial<IUniverSheetsThreadCommentConfig>,
@IMenuService private readonly _menuService: IMenuService,
@@ -56,7 +66,8 @@ export class SheetsThreadCommentController extends Disposable {
@Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService,
@IShortcutService private readonly _shortcutService: IShortcutService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController
+ @Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController,
+ @IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService
) {
super();
this._initMenu();
@@ -64,6 +75,7 @@ export class SheetsThreadCommentController extends Disposable {
this._initComponent();
this._initCommandListener();
this._initPanelListener();
+ this._initMarkSelection();
}
private _initShortcut() {
@@ -73,9 +85,16 @@ export class SheetsThreadCommentController extends Disposable {
private _initCommandListener() {
this._commandService.onCommandExecuted((commandInfo) => {
if (commandInfo.id === SetSelectionsOperation.id) {
+ if (this._isSwitchToCommenting) {
+ return;
+ }
const params = commandInfo.params as ISetSelectionsOperationParams;
const { unitId, subUnitId, selections, type } = params;
if ((type === SelectionMoveType.MOVE_END || type === undefined) && selections[0].primary) {
+ const range = selections[0].range;
+ if (range.endColumn - range.startColumn > 0 || range.endRow - range.startRow > 0) {
+ return;
+ }
const row = selections[0].primary.actualRow;
const col = selections[0].primary.actualColumn;
if (!this._sheetsThreadCommentModel.showCommentMarker(unitId, subUnitId, row, col)) {
@@ -148,6 +167,7 @@ export class SheetsThreadCommentController extends Disposable {
if (currentUnitId !== unitId) {
return;
}
+ this._isSwitchToCommenting = true;
const currentSheetId = currentUnit.getActiveSheet()?.getSheetId();
if (currentSheetId !== subUnitId) {
await this._commandService.executeCommand(SetWorksheetActiveOperation.id, {
@@ -155,6 +175,7 @@ export class SheetsThreadCommentController extends Disposable {
subUnitId,
});
}
+ this._isSwitchToCommenting = false;
const location = singleReferenceToGrid(comment.ref);
@@ -164,6 +185,7 @@ export class SheetsThreadCommentController extends Disposable {
worksheetTypes: [WorksheetViewPermission],
rangeTypes: [RangeProtectionPermissionViewPoint],
}, [{ startRow: row, startColumn: col, endRow: row, endColumn: col }]);
+
if (!commentPermission) {
return;
}
@@ -177,6 +199,7 @@ export class SheetsThreadCommentController extends Disposable {
endColumn: location.column + GAP,
},
});
+
this._sheetsThreadCommentPopupService.showPopup({
unitId,
subUnitId,
@@ -190,4 +213,61 @@ export class SheetsThreadCommentController extends Disposable {
}
}));
}
+
+ private _initMarkSelection() {
+ this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.subscribe((activeComment) => {
+ if (!activeComment) {
+ if (this._selectionShapeInfo) {
+ this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
+ this._selectionShapeInfo = null;
+ }
+ return;
+ }
+ const { unitId, subUnitId, commentId } = activeComment;
+ if (this._selectionShapeInfo) {
+ if (this._selectionShapeInfo.unitId === unitId && this._selectionShapeInfo.subUnitId === subUnitId && this._selectionShapeInfo.commentId === commentId) {
+ return;
+ }
+
+ this._markSelectionService.removeShape(this._selectionShapeInfo.shapeId);
+ this._selectionShapeInfo = null;
+ }
+ const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);
+ if (!comment) {
+ return;
+ }
+
+ const location = singleReferenceToGrid(comment.ref);
+
+ const { row, column } = location;
+ if (Number.isNaN(row) || Number.isNaN(column)) {
+ return;
+ }
+
+ const shapeId = this._markSelectionService.addShape({
+ range: {
+ startColumn: column,
+ endColumn: column,
+ startRow: row,
+ endRow: row,
+ },
+ style: {
+ hasAutoFill: false,
+ fill: 'rgb(255, 189, 55, 0.35)',
+ strokeWidth: 1,
+ stroke: '#FFBD37',
+ widgets: {},
+ },
+ primary: null,
+ });
+ if (!shapeId) {
+ return;
+ }
+
+ this._selectionShapeInfo = {
+ ...activeComment,
+ shapeId,
+ };
+ }));
+ }
}
diff --git a/packages/sheets-thread-comment/src/services/sheets-thread-comment-popup.service.ts b/packages/sheets-thread-comment/src/services/sheets-thread-comment-popup.service.ts
index 9b52a065fa..10ba8195fd 100644
--- a/packages/sheets-thread-comment/src/services/sheets-thread-comment-popup.service.ts
+++ b/packages/sheets-thread-comment/src/services/sheets-thread-comment-popup.service.ts
@@ -47,6 +47,10 @@ export class SheetsThreadCommentPopupService extends Disposable {
) {
super();
this._initZenVisible();
+
+ this.disposeWithMe(() => {
+ this._activePopup$.complete();
+ });
}
private _initZenVisible() {
diff --git a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx
index caf2ab2ff1..6e673672a4 100644
--- a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx
+++ b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx
@@ -21,7 +21,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import { useObservable } from '@univerjs/ui';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { map } from 'rxjs';
-import { type IThreadComment, ThreadCommentModel } from '@univerjs/thread-comment';
+import type { IThreadComment } from '@univerjs/thread-comment';
import { singleReferenceToGrid } from '@univerjs/engine-formula';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
import { ShowAddSheetCommentModalOperation } from '../../commands/operations/comment.operation';
@@ -30,19 +30,16 @@ import { SheetsThreadCommentPopupService } from '../../services/sheets-thread-co
export const SheetsThreadCommentPanel = () => {
const markSelectionService = useDependency(IMarkSelectionService);
const univerInstanceService = useDependency(IUniverInstanceService);
- const threadCommentModel = useDependency(ThreadCommentModel);
const sheetsThreadCommentPopupService = useDependency(SheetsThreadCommentPopupService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) {
- return null;
- }
+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const unitId = workbook.getUnitId();
const commandService = useDependency(ICommandService);
const subUnitId$ = useMemo(() => workbook.activeSheet$.pipe(map((i) => i?.getSheetId())), [workbook.activeSheet$]);
const subUnitId = useObservable(subUnitId$, workbook.getActiveSheet()?.getSheetId());
- const activeShapeId = useRef<string | null>();
+ const hoverShapeId = useRef<string | null>();
const panelService = useDependency(ThreadCommentPanelService);
const activeCommentId = useObservable(panelService.activeCommentId$);
+ const panelVisible = useObservable(panelService.panelVisible$, panelService.panelVisible);
const sortComments = useCallback((comments: IThreadComment[]) => {
const worksheets = workbook.getSheets();
const sheetIndex: Record<string, number> = {};
@@ -115,18 +112,18 @@ export const SheetsThreadCommentPanel = () => {
return;
}
- if (activeShapeId.current) {
- markSelectionService.removeShape(activeShapeId.current);
- activeShapeId.current = null;
+ if (hoverShapeId.current) {
+ markSelectionService.removeShape(hoverShapeId.current);
+ hoverShapeId.current = null;
}
- activeShapeId.current = showShape(comment);
+ hoverShapeId.current = showShape(comment);
};
const handleLeave = () => {
- if (activeShapeId.current) {
- markSelectionService.removeShape(activeShapeId.current);
- activeShapeId.current = null;
+ if (hoverShapeId.current) {
+ markSelectionService.removeShape(hoverShapeId.current);
+ hoverShapeId.current = null;
}
};
@@ -137,20 +134,10 @@ export const SheetsThreadCommentPanel = () => {
};
useEffect(() => {
- if (!activeCommentId) {
- return;
- }
- const comment = threadCommentModel.getComment(activeCommentId.unitId, activeCommentId.subUnitId, activeCommentId.commentId);
- if (!comment) {
- return;
+ if (!panelVisible && hoverShapeId.current) {
+ markSelectionService.removeShape(hoverShapeId.current);
}
- const id = showShape(comment);
- return () => {
- if (id) {
- markSelectionService.removeShape(id);
- }
- };
- }, [showShape, activeCommentId, threadCommentModel, markSelectionService]);
+ }, [markSelectionService, panelVisible]);
return (
<ThreadCommentPanel
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
index 13aedd060c..c56a1508a6 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
@@ -63,7 +63,6 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
override onStarting(injector: Injector): void {
injector.add([SheetsSelectionsService]);
injector.add([SheetInterceptorService]);
-
dependencies?.forEach((d) => injector.add(d));
}
}
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
index 8894203731..c1eda5d8d0 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, IDocumentData, Univer, Workbook } from '@univerjs/core';
-import { CellValueType, IContextService, LocaleService } from '@univerjs/core';
+import { CellValueType, IContextService, IResourceLoaderService, LocaleService } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { Injector } from '@wendellhu/redi';
@@ -76,6 +76,7 @@ describe('Test EndEditController', () => {
let contextService: IContextService;
let lexerTreeBuilder: LexerTreeBuilder;
let spreadsheetSkeleton: SpreadsheetSkeleton;
+ let resourceLoaderService: IResourceLoaderService;
let getCellDataByInputCell: (cell: ICellData, inputCell: ICellData) => ICellData | null;
beforeEach(() => {
@@ -88,6 +89,7 @@ describe('Test EndEditController', () => {
localeService = get(LocaleService);
contextService = get(IContextService);
lexerTreeBuilder = new LexerTreeBuilder();
+ resourceLoaderService = get(IResourceLoaderService);
const worksheet = workbook.getActiveSheet()!;
const config = worksheet.getConfig();
@@ -106,7 +108,7 @@ describe('Test EndEditController', () => {
throw new Error('documentLayoutObject is undefined');
}
- return getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);
+ return getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder, (model) => model.getSnapshot());
};
});
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index 7c07c18b0d..89cb43cc02 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -16,7 +16,7 @@
/* eslint-disable max-lines-per-function */
-import type { ICellData, ICommandInfo, IDocumentBody, IPosition, Nullable, Workbook } from '@univerjs/core';
+import type { DocumentDataModel, ICellData, ICommandInfo, IDocumentBody, IDocumentData, IPosition, Nullable, Workbook } from '@univerjs/core';
import {
CellValueType,
DEFAULT_EMPTY_DOCUMENT_VALUE,
@@ -33,6 +33,7 @@ import {
HorizontalAlign,
ICommandService,
IContextService,
+ IResourceLoaderService,
isFormulaString,
IUndoRedoService,
IUniverInstanceService,
@@ -117,7 +118,8 @@ export class EditingRenderController extends Disposable implements IRenderModule
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService,
@Inject(LocaleService) protected readonly _localService: LocaleService,
- @IEditorService private readonly _editorService: IEditorService
+ @IEditorService private readonly _editorService: IEditorService,
+ @IResourceLoaderService private readonly _resourceLoaderService: IResourceLoaderService
) {
super();
@@ -805,7 +807,8 @@ export class EditingRenderController extends Disposable implements IRenderModule
const cellData: Nullable<ICellData> = getCellDataByInput(
worksheet.getCellRaw(row, column) || {},
documentLayoutObject,
- this._lexerTreeBuilder
+ this._lexerTreeBuilder,
+ (model) => this._resourceLoaderService.saveDoc(model)
);
if (cellData == null) {
@@ -965,7 +968,8 @@ export class EditingRenderController extends Disposable implements IRenderModule
export function getCellDataByInput(
cellData: ICellData,
documentLayoutObject: IDocumentLayoutObject,
- lexerTreeBuilder: LexerTreeBuilder
+ lexerTreeBuilder: LexerTreeBuilder,
+ getSnapshot: (data: DocumentDataModel) => IDocumentData
) {
cellData = Tools.deepClone(cellData);
@@ -974,7 +978,7 @@ export function getCellDataByInput(
return null;
}
- const snapshot = documentModel.getSnapshot();
+ const snapshot = getSnapshot(documentModel);
const { body } = snapshot;
if (body == null) {
@@ -1033,12 +1037,13 @@ export function getCellDataByInput(
}
function isRichText(body: IDocumentBody) {
- const { textRuns = [], paragraphs = [], customBlocks = [] } = body;
+ const { textRuns = [], paragraphs = [], customRanges, customBlocks = [] } = body;
return (
textRuns.some((textRun) => textRun.ts && !Tools.isEmptyObject(textRun.ts)) ||
paragraphs.some((paragraph) => paragraph.bullet) ||
paragraphs.length >= 2 ||
+ Boolean(customRanges?.length) ||
customBlocks.length > 0
);
}
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 80586a51da..7a688cbae0 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -418,7 +418,6 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// 1. get properties of the table by parsing raw html content, including col properties / row properties
// cell properties and cell contents.
const { rowProperties, colProperties, cellMatrix } = this._htmlToUSM.convert(html);
-
if (!cellMatrix) {
return false;
}
@@ -461,7 +460,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
// 4. execute these mutations by the one method
- return this._pasteUSM(
+ const res = this._pasteUSM(
{
rowProperties,
colProperties,
@@ -470,6 +469,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
pasteTarget,
pasteType
);
+ return res;
}
private async _pasteInternal(copyId: string, pasteType: string): Promise<boolean> {
@@ -577,6 +577,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return pasteRes;
}
+ // eslint-disable-next-line max-lines-per-function
private _pasteUSM(
data: IUniverSheetCopyDataModel,
target: IPasteTarget,
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
index a5a87857ca..31bd996312 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
@@ -144,7 +144,7 @@ export class HtmlToUSMService {
const tableStrings = html.match(/<table\b[^>]*>([\s\S]*?)<\/table>/gi);
const tables: IParsedTablesInfo[] = [];
this.process(null, this._dom.childNodes!, newDocBody, tables);
- const { paragraphs, dataStream, textRuns } = newDocBody;
+ const { paragraphs, dataStream, textRuns, payloads } = newDocBody;
// use paragraph to split rows
if (paragraphs) {
@@ -192,6 +192,7 @@ export class HtmlToUSMService {
dataStream: singleDataStream,
textRuns,
paragraphs: generateParagraphs(singleDataStream),
+ payloads,
};
const dataStreamLength = dataStream.length;
@@ -503,6 +504,7 @@ export class HtmlToUSMService {
return documentModel?.getSnapshot();
}
+ // eslint-disable-next-line max-lines-per-function
private process(
parent: Nullable<ChildNode>,
nodes: NodeListOf<ChildNode>,
@@ -531,6 +533,24 @@ export class HtmlToUSMService {
textRuns: [],
};
+ // if ((parent as Element).tagName.toUpperCase() === 'A') {
+ // const id = Tools.generateRandomId();
+ // text = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;
+ // doc.customRanges = [
+ // ...(doc.customRanges ?? []),
+ // {
+ // startIndex: doc.dataStream.length,
+ // endIndex: doc.dataStream.length + text.length - 1,
+ // rangeId: id,
+ // rangeType: CustomRangeType.HYPERLINK,
+ // },
+ // ];
+ // doc.payloads = {
+ // ...doc.payloads,
+ // [id]: (parent as HTMLAnchorElement).href,
+ // };
+ // }
+
doc.dataStream += text;
newDoc.dataStream += text;
if (style && Object.getOwnPropertyNames(style).length) {
diff --git a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
index 2d0f31952f..c5e2114511 100644
--- a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
+++ b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, ICustomBlock, IDocumentData, IDrawings, IParagraph, ITextRun } from '@univerjs/core';
+import type { ICommandInfo, ICustomBlock, ICustomRange, IDocumentData, IDrawings, IParagraph, ITextRun } from '@univerjs/core';
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
@@ -192,7 +192,6 @@ export class ZenEditorController extends RxDisposable {
private _editorSyncHandler(param: IEditorBridgeServiceParam) {
const body = param.documentLayoutObject.documentModel?.getBody();
-
const dataStream = body?.dataStream;
const paragraphs = body?.paragraphs;
let textRuns: ITextRun[] = [];
@@ -218,7 +217,8 @@ export class ZenEditorController extends RxDisposable {
textRuns: ITextRun[] = [],
customBlocks: ICustomBlock[] = [],
drawings: IDrawings = {},
- drawingsOrder: string[] = []
+ drawingsOrder: string[] = [],
+ customRanges: ICustomRange[] = []
) {
const INCLUDE_LIST = [
DOCS_ZEN_EDITOR_UNIT_ID_KEY,
@@ -241,6 +241,7 @@ export class ZenEditorController extends RxDisposable {
docBody.dataStream = dataStream;
docBody.paragraphs = paragraphs;
docBody.customBlocks = customBlocks;
+ docBody.customRanges = customRanges;
snapshot.drawings = drawings;
snapshot.drawingsOrder = drawingsOrder;
@@ -356,7 +357,7 @@ export class ZenEditorController extends RxDisposable {
const customBlocks = docBody?.customBlocks;
const drawings = editorDocDataModel?.getDrawings();
const drawingsOrder = editorDocDataModel?.getDrawingsOrder();
-
+ const customRanges = editorDocDataModel?.getCustomRanges();
/**
* Fix the issue where content cannot be saved in the doc under Zen mode.
*/
@@ -366,7 +367,7 @@ export class ZenEditorController extends RxDisposable {
return;
}
- this._syncContentAndRender(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns, customBlocks, drawings, drawingsOrder);
+ this._syncContentAndRender(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns, customBlocks, drawings, drawingsOrder, customRanges);
}
}
})
diff --git a/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts b/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts
index b2ba1e7884..11ac812543 100644
--- a/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts
+++ b/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts
@@ -38,6 +38,11 @@ export class ThreadCommentPanelService extends Disposable {
) {
super();
this._init();
+
+ this.disposeWithMe(() => {
+ this._activeCommentId$.complete();
+ this._panelVisible$.complete();
+ });
}
private _init() {
diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/index.module.less b/packages/thread-comment-ui/src/views/thread-comment-panel/index.module.less
index acf10703ca..c4602f09a9 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-panel/index.module.less
+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/index.module.less
@@ -2,6 +2,7 @@
min-height: 100%;
display: flex;
flex-direction: column;
+ padding-bottom: 12px;
.thread-comment {
margin-top: 12px;
@@ -37,4 +38,9 @@
margin-right: 6px;
}
}
+
+ &-solved {
+ margin-top: 12px;
+ font-size: var(--font-size-xs);
+ }
}
diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
index 0a5ab3c721..663408f1b7 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
@@ -131,6 +131,9 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
? [tempComment, ...statuedComments]
: statuedComments;
+ const unSolvedComments = renderComments.filter((comment) => !comment.resolved);
+ const solvedComments = renderComments.filter((comment) => comment.resolved);
+
const isFiltering = status !== 'all' || unit !== 'all';
const onReset = () => {
@@ -159,6 +162,42 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
document.getElementById(id)?.scrollIntoView({ block: 'center' });
}, [activeCommentId]);
+ const renderComment = (comment: IThreadComment) => (
+ <ThreadCommentTree
+ prefix={prefix}
+ getSubUnitName={getSubUnitName}
+ key={comment.id}
+ id={comment.id}
+ unitId={comment.unitId}
+ subUnitId={comment.subUnitId}
+ refStr={comment.ref}
+ type={type}
+ showEdit={activeCommentId?.commentId === comment.id}
+ showHighlight={activeCommentId?.commentId === comment.id}
+ onClick={() => {
+ shouldScroll.current = false;
+ if (!comment.resolved) {
+ commandService.executeCommand(
+ SetActiveCommentOperation.id,
+ {
+ unitId: comment.unitId,
+ subUnitId: comment.subUnitId,
+ commentId: comment.id,
+ temp: false,
+ }
+ );
+ } else {
+ commandService.executeCommand(SetActiveCommentOperation.id);
+ }
+ }}
+ onMouseEnter={() => onItemEnter?.(comment)}
+ onMouseLeave={() => onItemLeave?.(comment)}
+ onAddComment={onAddComment}
+ onDeleteComment={onDeleteComment}
+ onResolve={(resolved: boolean) => onResolve?.(comment.id, resolved)}
+ />
+ );
+
return (
<div className={styles.threadCommentPanel}>
<div className={styles.threadCommentPanelForms}>
@@ -203,41 +242,9 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
]}
/>
</div>
- {renderComments.map((comment) => (
- <ThreadCommentTree
- prefix={prefix}
- getSubUnitName={getSubUnitName}
- key={comment.id}
- id={comment.id}
- unitId={comment.unitId}
- subUnitId={comment.subUnitId}
- refStr={comment.ref}
- type={type}
- showEdit={activeCommentId?.commentId === comment.id}
- showHighlight={activeCommentId?.commentId === comment.id}
- onClick={() => {
- shouldScroll.current = false;
- if (!comment.resolved) {
- commandService.executeCommand(
- SetActiveCommentOperation.id,
- {
- unitId: comment.unitId,
- subUnitId: comment.subUnitId,
- commentId: comment.id,
- temp: false,
- }
- );
- } else {
- commandService.executeCommand(SetActiveCommentOperation.id);
- }
- }}
- onMouseEnter={() => onItemEnter?.(comment)}
- onMouseLeave={() => onItemLeave?.(comment)}
- onAddComment={onAddComment}
- onDeleteComment={onDeleteComment}
- onResolve={(resolved: boolean) => onResolve?.(comment.id, resolved)}
- />
- ))}
+ {unSolvedComments.map(renderComment)}
+ {solvedComments.length ? <div className={styles.threadCommentPanelSolved}>已解决</div> : null}
+ {solvedComments.map(renderComment)}
{renderComments.length
? null
: (
diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
index c1878cf3fb..765fbee8ec 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
@@ -275,7 +275,7 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
const subUnitName = getSubUnitName(comments?.root.subUnitId ?? subUnitId);
const editorVisible = showEdit && !editingId && !resolved;
- const title = `${refStr || comments?.root.ref}${subUnitName ? ' · ' : ''}${subUnitName}`;
+ const title = `${refStr || comments?.root.ref || ''}${subUnitName ? ' · ' : ''}${subUnitName}`;
return (
<div
diff --git a/packages/thread-comment/src/models/thread-comment.model.ts b/packages/thread-comment/src/models/thread-comment.model.ts
index 998715ab91..4ea34aba6e 100644
--- a/packages/thread-comment/src/models/thread-comment.model.ts
+++ b/packages/thread-comment/src/models/thread-comment.model.ts
@@ -15,7 +15,7 @@
*/
import { BehaviorSubject, map, Subject } from 'rxjs';
-import { CustomRangeType, ICommandService } from '@univerjs/core';
+import { CustomRangeType, Disposable, ICommandService } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import type { IBaseComment, IThreadComment } from '../types/interfaces/i-thread-comment';
import type { IUpdateCommentPayload, IUpdateCommentRefPayload } from '../commands/mutations/comment.mutation';
@@ -53,7 +53,7 @@ export type CommentUpdate = {
payload: IThreadComment;
});
-export class ThreadCommentModel {
+export class ThreadCommentModel extends Disposable {
private _commentsMap: Record<string, Record<string, Record<string, IThreadComment>>> = {};
private _commentsTreeMap: Map<string, Map<string, Map<string, IThreadComment>>> = new Map();
private _threadMap: Map<string, Map<string, IThreadComment>> = new Map();
@@ -68,6 +68,12 @@ export class ThreadCommentModel {
@Inject(IThreadCommentDataSourceService) private readonly _dataSourceService: IThreadCommentDataSourceService,
@ICommandService private readonly _commandService: ICommandService
) {
+ super();
+
+ this.disposeWithMe(() => {
+ this._commentUpdate$.complete();
+ this._commentsMap$.complete();
+ });
}
private _ensureCommentMap(unitId: string, subUnitId: string) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b4c90fd653..453b723f6d 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':
+ specifier: workspace:*
+ version: link:../packages/docs-hyper-link
'@univerjs/docs-hyper-link-ui':
specifier: workspace:*
version: link:../packages/docs-hyper-link-ui
@@ -743,6 +746,9 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
'@univerjs/shared':
specifier: workspace:*
version: link:../../common/shared
@@ -1851,6 +1857,12 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/docs-hyper-link':
+ specifier: workspace:*
+ version: link:../docs-hyper-link
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula