Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(sheets-hyper-link): add hyper link for sheet (#2330)
zhangw09518aa58f26
diff --git a/eslint.config.js b/eslint.config.jsindex c03b759639..dade416b26 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -1,6 +1,7 @@import antfu from '@antfu/eslint-config';import header from 'eslint-plugin-header';import barrel from 'eslint-plugin-no-barrel-import';+import penetrating from 'eslint-plugin-no-penetrating-import';import { baseRules, typescriptPreset } from '@univerjs/shared/eslint';export default antfu({@@ -71,4 +72,19 @@ export default antfu({2,],},-}, typescriptPreset());+}, {+ // Not penetrating for source files+ files: ['**/*.ts', '**/*.tsx'],+ plugins: {+ penetrating,+ },+ ignores: [+ '**/__tests__/**/*',+ '**/__testing__/**/*',+ 'examples/**/*',+ ],+ rules: {+ 'penetrating/no-penetrating-import': 2,+ },+},+typescriptPreset());diff --git a/examples/package.json b/examples/package.jsonindex 0bb03cdc03..03191dd0f8 100644--- a/examples/package.json+++ b/examples/package.json@@ -36,6 +36,8 @@"@univerjs/sheets-filter-ui": "workspace:*","@univerjs/sheets-find-replace": "workspace:*","@univerjs/sheets-formula": "workspace:*",+ "@univerjs/sheets-hyper-link": "workspace:*",+ "@univerjs/sheets-hyper-link-ui": "workspace:*","@univerjs/sheets-numfmt": "workspace:*","@univerjs/sheets-permission-ui": "workspace:*","@univerjs/sheets-thread-comment": "workspace:*",diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo.ts b/examples/src/data/sheets/demo/default-workbook-data-demo.tsindex 5e298fcf91..d8c777e29b 100644--- a/examples/src/data/sheets/demo/default-workbook-data-demo.ts+++ b/examples/src/data/sheets/demo/default-workbook-data-demo.ts@@ -18,6 +18,7 @@ import type { IDocumentData, IWorkbookData } from '@univerjs/core';import { BooleanNumber, DataValidationErrorStyle, DataValidationOperator, DataValidationType, LocaleType } from '@univerjs/core';import { DATA_VALIDATION_PLUGIN_NAME } from '@univerjs/sheets-data-validation';+import type { ICellHyperLink } from '@univerjs/sheets-hyper-link';import { PAGE5_RICHTEXT_1 } from '../../slides/rich-text/page5-richtext1';const richTextDemo: IDocumentData = {@@ -174,6 +175,14 @@ const dataValidation = [},];+const hyperLink = [{+ row: 20,+ column: 12,+ id: '123',+ display: 'linkTest哈哈哈哈',+ payload: '#gid=sheet-0011&range=1:1',+}] as ICellHyperLink[];+export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {id: 'workbook-01',locale: LocaleType.ZH_CN,@@ -14073,6 +14082,10 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {v: 345,t: 2,},+ 12: {+ v: 'linkTest哈哈哈哈',+ t: 1,+ },},21: {4: {@@ -23541,6 +23554,12 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {// },},resources: [+ {+ name: 'SHEET_HYPER_LINK_PLUGIN',+ data: JSON.stringify({+ 'sheet-0011': hyperLink,+ }),+ },{name: DATA_VALIDATION_PLUGIN_NAME,data: JSON.stringify({diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex e88bdf9afa..c153770245 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -37,7 +37,7 @@ import { UniverSheetsPermissionUIPlugin } from '@univerjs/sheets-permission-ui';import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';import { UniverDebuggerPlugin } from '@univerjs/debugger';-+import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';import { FUniver } from '@univerjs/facade';import { IThreadCommentMentionDataService } from '@univerjs/thread-comment-ui';import { UniverDrawingPlugin } from '@univerjs/drawing';@@ -93,6 +93,8 @@ univer.registerPlugin(UniverRPCMainThreadPlugin, {workerURL: './worker.js',} as IUniverRPCMainThreadConfig);+univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);+// find replaceuniver.registerPlugin(UniverFindReplacePlugin);univer.registerPlugin(UniverSheetsFindReplacePlugin);diff --git a/package.json b/package.jsonindex f28ee9e587..9c1830bd4f 100644--- a/package.json+++ b/package.json@@ -62,6 +62,7 @@"eslint-plugin-format": "^0.1.1","eslint-plugin-header": "^3.1.1","eslint-plugin-no-barrel-import": "^0.0.2",+ "eslint-plugin-no-penetrating-import": "^0.0.1","eslint-plugin-react": "^7.34.1","eslint-plugin-react-hooks": "^4.6.2","eslint-plugin-react-refresh": "^0.4.7",diff --git a/packages/core/src/shared/rectangle.ts b/packages/core/src/shared/rectangle.tsindex c2f0194dcb..c3b535595b 100644--- a/packages/core/src/shared/rectangle.ts+++ b/packages/core/src/shared/rectangle.ts@@ -57,15 +57,32 @@ export class Rectangle {}static intersects(src: IRange, target: IRange): boolean {- const currentStartRow = src.startRow;- const currentEndRow = src.endRow;- const currentStartColumn = src.startColumn;- const currentEndColumn = src.endColumn;+ if (src.rangeType === RANGE_TYPE.ROW && target.rangeType === RANGE_TYPE.COLUMN) {+ return true;+ }- const incomingStartRow = target.startRow;- const incomingEndRow = target.endRow;- const incomingStartColumn = target.startColumn;- const incomingEndColumn = target.endColumn;+ if (src.rangeType === RANGE_TYPE.COLUMN && target.rangeType === RANGE_TYPE.ROW) {+ return true;+ }++ if (src.rangeType === RANGE_TYPE.ROW && target.rangeType === RANGE_TYPE.ROW) {+ return src.startRow <= target.endRow && src.endRow >= target.startRow;+ }++ if (src.rangeType === RANGE_TYPE.COLUMN && target.rangeType === RANGE_TYPE.COLUMN) {+ return src.startColumn <= target.endColumn && src.endColumn >= target.startColumn;+ }++ const MAX = Math.floor(Number.MAX_SAFE_INTEGER / 10);+ const currentStartRow = Number.isNaN(src.startRow) ? 0 : src.startRow;+ const currentEndRow = Number.isNaN(src.endRow) ? MAX : src.endRow;+ const currentStartColumn = Number.isNaN(src.startColumn) ? 0 : src.startColumn;+ const currentEndColumn = Number.isNaN(src.endColumn) ? MAX : src.endColumn;++ const incomingStartRow = Number.isNaN(target.startRow) ? 0 : target.startRow;+ const incomingEndRow = Number.isNaN(target.endRow) ? MAX : target.endRow;+ const incomingStartColumn = Number.isNaN(target.startColumn) ? 0 : target.startColumn;+ const incomingEndColumn = Number.isNaN(target.endColumn) ? MAX : target.endColumn;const zx = Math.abs(currentStartColumn + currentEndColumn - incomingStartColumn - incomingEndColumn);const x = Math.abs(currentStartColumn - currentEndColumn) + Math.abs(incomingStartColumn - incomingEndColumn);@@ -185,6 +202,19 @@ export class Rectangle {);}+ static realUnion(...ranges: IRange[]): IRange {+ const hasColRange = ranges.some((range) => range.rangeType === RANGE_TYPE.COLUMN);+ const hasRowRange = ranges.some((range) => range.rangeType === RANGE_TYPE.ROW);+ const res = Rectangle.union(...ranges);+ return {+ startColumn: hasRowRange ? Number.NaN : res.startColumn,+ endColumn: hasRowRange ? Number.NaN : res.endColumn,+ startRow: hasColRange ? Number.NaN : res.startRow,+ endRow: hasColRange ? Number.NaN : res.endRow,+ rangeType: hasRowRange ? RANGE_TYPE.ROW : hasColRange ? RANGE_TYPE.COLUMN : RANGE_TYPE.NORMAL,+ };+ }+static getRelativeRange = (range: IRange, originRange: IRange) =>({startRow: range.startRow - originRange.startRow,diff --git a/packages/design/package.json b/packages/design/package.jsonindex ea2c50f97e..ec7c66cb86 100644--- a/packages/design/package.json+++ b/packages/design/package.json@@ -77,7 +77,7 @@"@rc-component/color-picker": "^1.5.3","@rc-component/trigger": "^1.18.3","@types/react-mentions": "^4.1.13",- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","rc-dialog": "^9.4.0","rc-dropdown": "^4.2.0","rc-input": "^1.4.5",diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.jsonindex 590c7f085e..76ba853b0f 100644--- a/packages/docs-drawing-ui/package.json+++ b/packages/docs-drawing-ui/package.json@@ -75,7 +75,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.46"+ "@univerjs/icons": "^0.1.54"},"devDependencies": {"@univerjs/core": "workspace:*",@@ -90,7 +90,8 @@"@wendellhu/redi": "0.15.2","clsx": "^2.1.0","less": "^4.2.0",- "react": "^18.2.0",+ "ot-json1": "^1.0.2",+ "react": "18.2.0","rxjs": "^7.8.1","typescript": "^5.3.3","vite": "^5.1.4",diff --git a/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.tsindex edc47273eb..278a6695ea 100644--- a/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts@@ -20,9 +20,8 @@ import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import type { BaseObject, Scene } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';-import { COMPONENT_IMAGE_POPUP_MENU, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';+import { COMPONENT_IMAGE_POPUP_MENU, ImageCropperObject, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';import { takeUntil } from 'rxjs';-import { ImageCropperObject } from '@univerjs/drawing-ui/views/crop/image-cropper-object.js';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';import { RemoveDocDrawingCommand } from '../commands/commands/remove-doc-drawing.command';import { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.tsindex db2c2ada97..622037425f 100644--- a/packages/drawing-ui/src/index.ts+++ b/packages/drawing-ui/src/index.ts@@ -21,3 +21,4 @@ export { DrawingCommonPanel } from './views/panel/DrawingCommonPanel';export { ImagePopupMenu } from './views/image-popup-menu/ImagePopupMenu';export { COMPONENT_IMAGE_POPUP_MENU } from './views/image-popup-menu/component-name';export { UniverDrawingUIPlugin } from './plugin';+export { ImageCropperObject } from './views/crop/image-cropper-object';diff --git a/packages/engine-render/src/shape/image.ts b/packages/engine-render/src/shape/image.tsindex 011d8ae9aa..573a460883 100644--- a/packages/engine-render/src/shape/image.ts+++ b/packages/engine-render/src/shape/image.ts@@ -153,7 +153,6 @@ export class Image extends Shape<IImageProps> {this._renderByCropper = true;this._transformBySrcRect();}-// override transformForAngle(transform: Transform) {// if (this.angle === 0) {// return transform;diff --git a/packages/find-replace/package.json b/packages/find-replace/package.jsonindex bf77aa89f8..9f0724f736 100644--- a/packages/find-replace/package.json+++ b/packages/find-replace/package.json@@ -77,7 +77,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52"+ "@univerjs/icons": "^0.1.54"},"devDependencies": {"@types/react": "^18.2.79",diff --git a/packages/sheets-conditional-formatting-ui/package.json b/packages/sheets-conditional-formatting-ui/package.jsonindex dec0528db3..02ba5681a1 100644--- a/packages/sheets-conditional-formatting-ui/package.json+++ b/packages/sheets-conditional-formatting-ui/package.json@@ -83,7 +83,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","@univerjs/protocol": "^0.1.34","@univerjs/sheets-conditional-formatting": "workspace:*","lodash.get": "^4.4.2",diff --git a/packages/sheets-data-validation/package.json b/packages/sheets-data-validation/package.jsonindex 6171490e3b..c9c7297aee 100644--- a/packages/sheets-data-validation/package.json+++ b/packages/sheets-data-validation/package.json@@ -77,7 +77,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52"+ "@univerjs/icons": "^0.1.54"},"devDependencies": {"@univerjs/core": "workspace:*",diff --git a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts b/packages/sheets-data-validation/src/controllers/dv-alert.controller.tsindex f15c75e125..2672b1376e 100644--- a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts+++ b/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts@@ -19,6 +19,7 @@ import { DataValidationStatus, Disposable, IUniverInstanceService, LifecycleStagimport { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';import type { BaseDataValidator } from '@univerjs/data-validation';+import { debounceTime } from 'rxjs';const ALERT_KEY = 'SHEET_DATA_VALIDATION_ALERT';@@ -39,7 +40,7 @@ export class DataValidationAlertController extends Disposable {}private _initCellAlertPopup() {- this.disposeWithMe(this._hoverManagerService.currentCell$.subscribe((cellPos) => {+ this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cellPos) => {if (cellPos) {const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();diff --git a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.tsindex d25df24d4d..3f3651c804 100644--- a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts+++ b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts@@ -81,6 +81,7 @@ export class DataValidationCopyPasteController extends Disposable {});}+ // eslint-disable-next-line max-lines-per-functionprivate _generateMutations(pastedRange: IDiscreteRange,copyInfo: {diff --git a/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.tsindex 202cfda331..c29dd6ece5 100644--- a/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts+++ b/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts@@ -20,10 +20,9 @@ import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import type { BaseObject, Scene } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';-import { COMPONENT_IMAGE_POPUP_MENU, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';+import { COMPONENT_IMAGE_POPUP_MENU, ImageCropperObject, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';import { takeUntil } from 'rxjs';-import { ImageCropperObject } from '@univerjs/drawing-ui/views/crop/image-cropper-object.js';import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-drawing.command';import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';diff --git a/packages/sheets-filter-ui/package.json b/packages/sheets-filter-ui/package.jsonindex 1914881bc1..4438351ba9 100644--- a/packages/sheets-filter-ui/package.json+++ b/packages/sheets-filter-ui/package.json@@ -75,7 +75,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","rc-virtual-list": "^3.11.5"},"devDependencies": {diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.jsonindex 31feead48b..453114f497 100644--- a/packages/sheets-formula/package.json+++ b/packages/sheets-formula/package.json@@ -77,7 +77,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52"+ "@univerjs/icons": "^0.1.54"},"devDependencies": {"@types/react": "^18.2.79",diff --git a/packages/sheets-hyper-link-ui/README-zh.md b/packages/sheets-hyper-link-ui/README-zh.mdnew file mode 100644index 0000000000..c050794143--- /dev/null+++ b/packages/sheets-hyper-link-ui/README-zh.md@@ -0,0 +1,23 @@+# @univerjs/sheets-hyper-link-ui++[](https://npmjs.org/packages/@univerjs/hyper-link-ui)+[](https://img.shields.io/npm/l/@univerjs/hyper-link-ui)++## 简介++`@univerjs/sheets-hyper-link-ui` 提供了超链接功能允许用户创建快速访问工作表内外部资源的链接,包括网页、文件、电子邮件地址或工作簿中的其他位置。++## 使用++### 安装++```shell+npm i @univerjs/sheets-hyper-link-ui+```++### 注册插件+```js+import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';++univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);+```diff --git a/packages/sheets-hyper-link-ui/README.md b/packages/sheets-hyper-link-ui/README.mdnew file mode 100644index 0000000000..585ea24239--- /dev/null+++ b/packages/sheets-hyper-link-ui/README.md@@ -0,0 +1,22 @@+# @univerjs/sheets-hyper-link-ui++[](https://npmjs.org/packages/@univerjs/hyper-link-ui)+[](https://img.shields.io/npm/l/@univerjs/hyper-link-ui)++## Introduction++`@univerjs/sheets-hyper-link-ui` provides a hyperlink feature that allows users to create links for quick access to resources both within and outside of the spreadsheet, including web pages, files, email addresses, or other locations in the workbook.+## Usage++### Installation++```shell+npm i @univerjs/sheets-hyper-link-ui+```++### Register Plugin+```js+import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';++univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);+```diff --git a/packages/sheets-hyper-link-ui/package.json b/packages/sheets-hyper-link-ui/package.jsonnew file mode 100644index 0000000000..e201909489--- /dev/null+++ b/packages/sheets-hyper-link-ui/package.json@@ -0,0 +1,94 @@+{+ "name": "@univerjs/sheets-hyper-link-ui",+ "version": "0.0.1",+ "private": true,+ "description": "",+ "author": "DreamNum <[email protected]>",+ "license": "Apache-2.0",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/univer"+ },+ "homepage": "https://univer.ai",+ "repository": {+ "type": "git",+ "url": "https://github.com/dream-num/univer"+ },+ "bugs": {+ "url": "https://github.com/dream-num/univer/issues"+ },+ "keywords": [],+ "exports": {+ ".": "./src/index.ts",+ "./*": "./src/*"+ },+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "types": "./lib/types/index.d.ts",+ "publishConfig": {+ "access": "public",+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "exports": {+ ".": {+ "import": "./lib/es/index.js",+ "require": "./lib/cjs/index.js",+ "types": "./lib/types/index.d.ts"+ },+ "./*": {+ "import": "./lib/es/*",+ "require": "./lib/cjs/*",+ "types": "./lib/types/index.d.ts"+ },+ "./lib/*": "./lib/*"+ }+ },+ "directories": {+ "lib": "lib"+ },+ "files": [+ "lib"+ ],+ "scripts": {+ "test": "vitest run",+ "test:watch": "vitest",+ "coverage": "vitest run --coverage",+ "lint:types": "tsc --noEmit",+ "build": "tsc && vite build"+ },+ "peerDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/design": "workspace:*",+ "@univerjs/engine-formula": "workspace:*",+ "@univerjs/engine-render": "workspace:*",+ "@univerjs/sheets": "workspace:*",+ "@univerjs/sheets-formula": "workspace:*",+ "@univerjs/sheets-hyper-link": "workspace:*",+ "@univerjs/sheets-ui": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.15.2",+ "clsx": "^2.1.1",+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {+ "@univerjs/sheets-hyper-link": "workspace:*"+ },+ "devDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/engine-formula": "workspace:*",+ "@univerjs/engine-render": "workspace:*",+ "@univerjs/icons": "^0.1.54",+ "@univerjs/shared": "workspace:*",+ "@univerjs/sheets": "workspace:*",+ "@univerjs/sheets-formula": "workspace:*",+ "@univerjs/sheets-ui": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "^0.15.2",+ "clsx": "^2.1.1",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.2.11",+ "vitest": "^1.6.0"+ }+}diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts b/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.tsnew file mode 100644index 0000000000..1a86109096--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts@@ -0,0 +1,108 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CommandType, type ICommand, ICommandService, IUniverInstanceService } from '@univerjs/core';+import { getSheetCommandTarget, type ISheetCommandSharedParams, SelectionManagerService } from '@univerjs/sheets';+import { HyperLinkModel } from '@univerjs/sheets-hyper-link';+import { ISidebarService } from '@univerjs/ui';+import { CellLinkEdit } from '../../views/CellLinkEdit';+import { SheetsHyperLinkPopupService } from '../../services/popup.service';++export interface IOpenHyperLinkSidebarOperationParams extends ISheetCommandSharedParams {+ row: number;+ column: number;+}++export const OpenHyperLinkSidebarOperation: ICommand<IOpenHyperLinkSidebarOperationParams> = {+ type: CommandType.OPERATION,+ id: 'sheet.operation.open-hyper-link-sidebar',+ handler(accessor, params) {+ if (!params) {+ return false;+ }++ const { unitId, subUnitId, row, column } = params;+ const hyperLinkModel = accessor.get(HyperLinkModel);+ const sidebarService = accessor.get(ISidebarService);+ const popupService = accessor.get(SheetsHyperLinkPopupService);+ const currentLink = hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);+ popupService.startEditing(params);++ sidebarService.open({+ header: {+ title: !currentLink ? 'hyperLink.form.addTitle' : 'hyperLink.form.editTitle',+ },+ children: {+ label: CellLinkEdit.componentKey,+ },+ });++ return true;+ },+};++export const CloseHyperLinkSidebarOperation: ICommand = {+ type: CommandType.OPERATION,+ id: 'sheet.operation.close-hyper-link-sidebar',+ handler(accessor) {+ const sidebarService = accessor.get(ISidebarService);+ const popupService = accessor.get(SheetsHyperLinkPopupService);++ sidebarService.close();+ popupService.endEditing();+ return true;+ },+};++export const InsertHyperLinkOperation: ICommand = {+ type: CommandType.OPERATION,+ id: 'sheet.operation.insert-hyper-link',+ handler(accessor) {+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const target = getSheetCommandTarget(univerInstanceService);+ if (!target) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const selectionManagerService = accessor.get(SelectionManagerService);+ const selection = selectionManagerService.getFirst();+ if (!selection?.primary) {+ return false;+ }+ const row = selection.primary.actualRow;+ const column = selection.primary.actualColumn;+ return commandService.executeCommand(OpenHyperLinkSidebarOperation.id, {+ unitId: target.unitId,+ subUnitId: target.subUnitId,+ row,+ column,+ });+ },+};++export const InsertHyperLinkToolbarOperation: ICommand = {+ type: CommandType.OPERATION,+ id: 'sheet.operation.insert-hyper-link-toolbar',+ handler(accessor) {+ const commandService = accessor.get(ICommandService);+ const popupService = accessor.get(SheetsHyperLinkPopupService);+ if (popupService.currentEditing) {+ return commandService.executeCommand(CloseHyperLinkSidebarOperation.id);+ } else {+ return commandService.executeCommand(InsertHyperLinkOperation.id);+ }+ },+};diff --git a/packages/sheets-hyper-link-ui/src/common/util.ts b/packages/sheets-hyper-link-ui/src/common/util.tsnew file mode 100644index 0000000000..ceade6f83d--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/common/util.ts@@ -0,0 +1,30 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;+const regex = new RegExp(expression);++export function isLegalLink(link: string) {+ if (link.startsWith('http://localhost:3002') || link.startsWith('localhost:3002')) {+ return true;+ }+ return Boolean(link.match(regex));+}++export function hasProtocol(urlString: string) {+ const pattern = /^[a-zA-Z]+:\/\//;+ return pattern.test(urlString);+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.tsnew file mode 100644index 0000000000..8bc011a254--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts@@ -0,0 +1,163 @@+/**+ * 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 { IMutationInfo } from '@univerjs/core';+import { Disposable, LifecycleStages, OnLifecycle, Range, Rectangle, Tools } from '@univerjs/core';+import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';+import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';+import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';+import { Inject } from '@wendellhu/redi';+import { SHEETS_HYPER_LINK_UI_PLUGIN } from '../types/const';++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkAutoFillController)+export class SheetsHyperLinkAutoFillController extends Disposable {+ constructor(+ @IAutoFillService private readonly _autoFillService: IAutoFillService,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel+ ) {+ super();+ this._initAutoFill();+ }++ // eslint-disable-next-line max-lines-per-function+ private _initAutoFill() {+ const noopReturnFunc = () => ({ redos: [], undos: [] });++ // eslint-disable-next-line max-lines-per-function+ const generalApplyFunc = (location: IAutoFillLocation, applyType: APPLY_TYPE) => {+ const { source: sourceRange, target: targetRange, unitId, subUnitId } = location;++ const virtualRange = virtualizeDiscreteRanges([sourceRange, targetRange]);+ const [vSourceRange, vTargetRange] = virtualRange.ranges;+ const { mapFunc } = virtualRange;+ const sourceStartCell = {+ row: vSourceRange.startRow,+ col: vSourceRange.startColumn,+ };+ const repeats = getAutoFillRepeatRange(vSourceRange, vTargetRange);+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];++ // eslint-disable-next-line max-lines-per-function+ repeats.forEach((repeat) => {+ const targetStartCell = repeat.repeatStartCell;+ const relativeRange = repeat.relativeRange;+ const sourceRange = {+ startRow: sourceStartCell.row,+ startColumn: sourceStartCell.col,+ endColumn: sourceStartCell.col,+ endRow: sourceStartCell.row,+ };+ const targetRange = {+ startRow: targetStartCell.row,+ startColumn: targetStartCell.col,+ endColumn: targetStartCell.col,+ endRow: targetStartCell.row,+ };+ Range.foreach(relativeRange, (row, col) => {+ const sourcePositionRange = Rectangle.getPositionRange(+ {+ startRow: row,+ startColumn: col,+ endColumn: col,+ endRow: row,+ },+ sourceRange+ );+ const { row: sourceRow, col: sourceCol } = mapFunc(sourcePositionRange.startRow, sourcePositionRange.startColumn);+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, sourceRow, sourceCol);+ if (link) {+ const targetPositionRange = Rectangle.getPositionRange(+ {+ startRow: row,+ startColumn: col,+ endColumn: col,+ endRow: row,+ },+ targetRange+ );+ const { row: targetRow, col: targetCol } = mapFunc(targetPositionRange.startRow, targetPositionRange.startColumn);+ const id = Tools.generateRandomId();+ const currentLink = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, targetRow, targetCol);+ if (currentLink) {+ redos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: currentLink.id,+ },+ });+ }+ if (APPLY_TYPE.COPY === applyType) {+ redos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link: {+ ...link,+ id,+ row: targetRow,+ column: targetCol,+ },+ },+ });+ undos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id,+ },+ });+ }+ if (currentLink) {+ undos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link: currentLink,+ },+ });+ }+ }+ });+ });++ return {+ undos,+ redos,+ };+ };+ const hook: ISheetAutoFillHook = {+ id: SHEETS_HYPER_LINK_UI_PLUGIN,+ onFillData: (location, direction, applyType) => {+ if (+ applyType === APPLY_TYPE.COPY ||+ applyType === APPLY_TYPE.ONLY_FORMAT ||+ applyType === APPLY_TYPE.SERIES+ ) {+ return generalApplyFunc(location, applyType);+ }++ return noopReturnFunc();+ },+ };+ this.disposeWithMe(this._autoFillService.addHook(hook));+ }+}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.tsnew file mode 100644index 0000000000..aa44d58533--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts@@ -0,0 +1,269 @@+/**+ * 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 { IMutationInfo, IRange, Nullable } from '@univerjs/core';+import { Disposable, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Rectangle, Tools } from '@univerjs/core';+import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';+import type { IDiscreteRange, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';+import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME, rangeToDiscreteRange, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';+import { Inject, Injector } from '@wendellhu/redi';+import { SPECIAL_PASTE_FORMULA } from '@univerjs/sheets-formula';+import { SHEETS_HYPER_LINK_UI_PLUGIN } from '../types/const';+import { hasProtocol, isLegalLink } from '../common/util';+import { SheetsHyperLinkResolverService } from '../services/resolver.service';++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkCopyPasteController)+export class SheetsHyperLinkCopyPasteController extends Disposable {+ private _copyInfo: Nullable<{+ matrix: ObjectMatrix<string>;+ unitId: string;+ subUnitId: string;+ }>;++ constructor(+ @ISheetClipboardService private _sheetClipboardService: ISheetClipboardService,+ @Inject(HyperLinkModel) private _hyperLinkModel: HyperLinkModel,+ @Inject(Injector) private _injector: Injector,+ @Inject(SheetsHyperLinkResolverService) private _resolverService: SheetsHyperLinkResolverService+ ) {+ super();+ this._initCopyPaste();+ }++ // eslint-disable-next-line max-lines-per-function+ private _initCopyPaste() {+ this._sheetClipboardService.addClipboardHook({+ id: SHEETS_HYPER_LINK_UI_PLUGIN,+ onBeforeCopy: (unitId, subUnitId, range) => this._collect(unitId, subUnitId, range),+ onPasteCells: (pasteFrom, pasteTo, data, payload) => {+ const { copyType = COPY_TYPE.COPY, pasteType } = payload;+ const { range: copyRange } = pasteFrom || {};+ const { range: pastedRange, unitId, subUnitId } = pasteTo;+ return this._generateMutations(pastedRange, { copyType, pasteType, copyRange, unitId, subUnitId });+ },+ onPastePlainText: (pasteTo: ISheetDiscreteRangeLocation, clipText: string) => {+ if (isLegalLink(clipText)) {+ let text = hasProtocol(clipText) ? clipText : `http://${clipText}`;+ const url = new URL(text);+ const name = clipText;+ if (+ url.hostname === location.hostname &&+ url.port === location.port &&+ url.protocol === location.protocol &&+ url.pathname === location.pathname &&+ url.hash+ ) {+ text = url.hash;+ // const urlInfo = this._resolverService.parseHyperLink(text);+ // name = urlInfo.name || clipText;+ }++ const { range, unitId, subUnitId } = pasteTo;+ const { ranges: [pasteToRange], mapFunc } = virtualizeDiscreteRanges([range]);+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ Range.foreach(pasteToRange, (originRow, originCol) => {+ const { row, col: column } = mapFunc(originRow, originCol);+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, column);+ if (link) {+ redos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ },+ });+ }+ const newId = Tools.generateRandomId();+ redos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link: {+ id: newId,+ row,+ column,+ display: name,+ payload: text,+ },+ },+ });+ undos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: newId,+ },+ });+ if (link) {+ undos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ },+ });+ }+ });+ return { redos, undos };+ }++ return { undos: [], redos: [] };+ },+ });+ }++ private _collect(unitId: string, subUnitId: string, range: IRange) {+ const matrix = new ObjectMatrix<string>();+ this._copyInfo = {+ unitId,+ subUnitId,+ matrix,+ };++ const accessor = {+ get: this._injector.get.bind(this._injector),+ };+ const discreteRange = rangeToDiscreteRange(range, accessor, unitId, subUnitId);+ if (!discreteRange) {+ return;+ }+ const { rows, cols } = discreteRange;+ rows.forEach((row, rowIndex) => {+ cols.forEach((col, colIndex) => {+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);++ matrix.setValue(rowIndex, colIndex, link?.id ?? '');+ });+ });+ }++ // eslint-disable-next-line max-lines-per-function+ private _generateMutations(+ pastedRange: IDiscreteRange,+ copyInfo: {+ copyType: COPY_TYPE;+ copyRange?: IDiscreteRange;+ pasteType: string;+ unitId: string;+ subUnitId: string;+ }+ ) {+ 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: [] };+ }++ if (+ [+ PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH,+ PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE,+ PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,+ SPECIAL_PASTE_FORMULA,+ ].includes(+ copyInfo.pasteType+ )+ ) {+ return { redos: [], undos: [] };+ }++ const { unitId, subUnitId } = this._copyInfo;++ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];++ const { ranges: [vCopyRange, vPastedRange], mapFunc } = virtualizeDiscreteRanges([copyInfo.copyRange, pastedRange]);+ const repeatRange = getRepeatRange(vCopyRange, vPastedRange, true);++ repeatRange.forEach(({ startRange }) => {+ this._copyInfo?.matrix.forValue((row, col, ruleId) => {+ const range = Rectangle.getPositionRange(+ {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ },+ startRange+ );+ const oldLink = this._hyperLinkModel.getHyperLink(unitId, subUnitId, ruleId);++ const { row: startRow, col: startColumn } = mapFunc(range.startRow, range.startColumn);+ const currentLink = this._hyperLinkModel.getHyperLinkByLocation(copyInfo.unitId, copyInfo.subUnitId, startRow, startColumn);+ const id = Tools.generateRandomId();+ if (currentLink) {+ redos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId: copyInfo.unitId,+ subUnitId: copyInfo.subUnitId,+ id: currentLink.id,+ },+ });+ }+ if (oldLink) {+ redos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId: copyInfo.unitId,+ subUnitId: copyInfo.subUnitId,+ link: {+ ...oldLink,+ id,+ row: startRow,+ column: startColumn,+ },+ },+ });+ undos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId: copyInfo.unitId,+ subUnitId: copyInfo.subUnitId,+ id,+ },+ });+ }++ if (currentLink) {+ undos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId: copyInfo.unitId,+ subUnitId: copyInfo.subUnitId,+ link: currentLink,+ },+ });+ }+ });+ });++ return {+ redos,+ undos,+ };+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/menu.ts b/packages/sheets-hyper-link-ui/src/controllers/menu.tsnew file mode 100644index 0000000000..bfc86153c0--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/menu.ts@@ -0,0 +1,52 @@+/**+ * 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 { UniverInstanceType } from '@univerjs/core';+import type { IMenuItem, IShortcutItem } from '@univerjs/ui';+import { getMenuHiddenObservable, KeyCode, MenuGroup, MenuItemType, MenuPosition, MetaKeys } from '@univerjs/ui';+import type { IAccessor } from '@wendellhu/redi';+import { whenSheetEditorFocused } from '@univerjs/sheets-ui';+import { InsertHyperLinkOperation, InsertHyperLinkToolbarOperation } from '../commands/operations/sidebar.operations';++export const insertLinkMenuFactory = (accessor: IAccessor) => {+ return {+ id: InsertHyperLinkOperation.id,+ type: MenuItemType.BUTTON,+ positions: [MenuPosition.CONTEXT_MENU],+ title: 'hyperLink.menu.add',+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),+ icon: 'LinkSingle',+ } as IMenuItem;+};++export const insertLinkMenuToolbarFactory = (accessor: IAccessor) => {+ return {+ tooltip: 'hyperLink.form.addTitle',+ positions: MenuPosition.TOOLBAR_START,+ group: MenuGroup.TOOLBAR_OTHERS,+ id: InsertHyperLinkToolbarOperation.id,+ type: MenuItemType.BUTTON,+ icon: 'LinkSingle',+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),++ };+};++export const InsertLinkShortcut: IShortcutItem = {+ id: InsertHyperLinkOperation.id,+ binding: KeyCode.K | MetaKeys.CTRL_COMMAND,+ preconditions: whenSheetEditorFocused,+};diff --git a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.tsnew file mode 100644index 0000000000..4885c13ab4--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { HoverManagerService } from '@univerjs/sheets-ui';+import { Inject } from '@wendellhu/redi';+import { debounceTime } from 'rxjs';+import { SheetsHyperLinkPopupService } from '../services/popup.service';++@OnLifecycle(LifecycleStages.Rendered, SheetsHyperLinkPopupController)+export class SheetsHyperLinkPopupController extends Disposable {+ constructor(+ @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,+ @Inject(SheetsHyperLinkPopupService) private readonly _sheetsHyperLinkPopupService: SheetsHyperLinkPopupService+ ) {+ super();++ this._initHoverListener();+ }++ private _initHoverListener() {+ this.disposeWithMe(+ this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((currentCell) => {+ if (!currentCell) {+ this._sheetsHyperLinkPopupService.hideCurrentPopup();+ return;+ }++ this._sheetsHyperLinkPopupService.showPopup(currentCell.location);+ })+ );+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/ref-range.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/ref-range.controller.tsnew file mode 100644index 0000000000..e4cbb48240--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/ref-range.controller.ts@@ -0,0 +1,237 @@+/**+ * 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 { IRange } from '@univerjs/core';+import { Disposable, isValidRange, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';+import type { EffectRefRangeParams } from '@univerjs/sheets';+import { handleDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';+import type { IAddHyperLinkMutationParams, ICellHyperLink, IRemoveHyperLinkMutationParams, IUpdateHyperLinkMutationParams, IUpdateHyperLinkRefMutationParams } from '@univerjs/sheets-hyper-link';+import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation, UpdateHyperLinkMutation, UpdateHyperLinkRefMutation } from '@univerjs/sheets-hyper-link';+import type { IDisposable } from '@wendellhu/redi';+import { Inject } from '@wendellhu/redi';+import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';+import { SheetsHyperLinkResolverService } from '../services/resolver.service';+import { ERROR_RANGE } from '../types/const';++@OnLifecycle(LifecycleStages.Starting, SheetsHyperLinkRefRangeController)+export class SheetsHyperLinkRefRangeController extends Disposable {+ private _disposableMap = new Map<string, IDisposable>();+ private _rangeDisableMap = new Map<string, IDisposable>();++ constructor(+ @Inject(RefRangeService) private readonly _refRangeService: RefRangeService,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,+ @Inject(SheetsHyperLinkResolverService) private readonly _resolverService: SheetsHyperLinkResolverService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ ) {+ super();+ this._initData();+ this._initRefRange();+ }++ private _register(unitId: string, subUnitId: string, link: ICellHyperLink) {+ const id = link.id;+ const oldRange: IRange = {+ startColumn: link.column,+ endColumn: link.column,+ startRow: link.row,+ endRow: link.row,+ };++ const handleRangeChange = (commandInfo: EffectRefRangeParams) => {+ const resultRange = handleDefaultRangeChangeWithEffectRefCommands(oldRange, commandInfo);+ if (resultRange && resultRange.startColumn === oldRange.startColumn && resultRange.startRow === oldRange.startRow) {+ return {+ undos: [],+ redos: [],+ };+ }++ if (!resultRange) {+ return {+ redos: [{+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ } as IRemoveHyperLinkMutationParams,+ }],+ undos: [{+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ } as IAddHyperLinkMutationParams,+ }],+ };+ }+ return {+ redos: [{+ id: UpdateHyperLinkRefMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ row: resultRange.startRow,+ column: resultRange.startColumn,+ } as IUpdateHyperLinkRefMutationParams,+ }],+ undos: [{+ id: UpdateHyperLinkRefMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ row: oldRange.startRow,+ column: oldRange.startColumn,+ } as IUpdateHyperLinkRefMutationParams,+ }],+ };+ };++ this._disposableMap.set(+ id,+ this._refRangeService.registerRefRange(oldRange, handleRangeChange, unitId, subUnitId)+ );+ }++ private _unregister(id: string) {+ const disposable = this._disposableMap.get(id);+ disposable?.dispose();+ this._disposableMap.delete(id);+ }++ private _registerRange(unitId: string, id: string, payload: string) {+ const linkInfo = this._resolverService.parseHyperLink(payload);+ if (linkInfo.searchObj && linkInfo.searchObj.range && linkInfo.searchObj.gid) {+ const subUnitId = linkInfo.searchObj.gid;+ const range = deserializeRangeWithSheet(linkInfo.searchObj.range).range;++ if (isValidRange(range) && linkInfo.searchObj.range !== ERROR_RANGE) {+ const handleRangeChange = (commandInfo: EffectRefRangeParams) => {+ const resultRange = handleDefaultRangeChangeWithEffectRefCommands(range, commandInfo);+ if (resultRange && serializeRange(resultRange) === serializeRange(range)) {+ return {+ redos: [],+ undos: [],+ };+ }++ return {+ redos: [{+ id: UpdateHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id,+ payload: {+ payload: `#gid=${subUnitId}&range=${resultRange ? serializeRange(resultRange) : 'err'}`,+ },+ } as IUpdateHyperLinkMutationParams,+ }],+ undos: [{+ id: UpdateHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id,+ payload: {+ payload,+ },+ } as IUpdateHyperLinkMutationParams,+ }],+ };+ };+ this._rangeDisableMap.set(id, this._refRangeService.registerRefRange(range, handleRangeChange, unitId, subUnitId));+ }+ }+ }++ private _unregisterRange(id: string) {+ const disposable = this._rangeDisableMap.get(id);+ disposable?.dispose();+ this._rangeDisableMap.delete(id);+ }++ private _initData() {+ const data = this._hyperLinkModel.getAll();++ data.forEach((unitData) => {+ unitData.forEach((subUnitData) => {+ const { unitId, subUnitId, links } = subUnitData;++ links.forEach((link) => {+ this._register(unitId, subUnitId, link);+ });+ });+ });+ }++ private _initRefRange() {+ this.disposeWithMe(+ this._hyperLinkModel.linkUpdate$.subscribe((option) => {+ switch (option.type) {+ case 'add': {+ this._register(option.unitId, option.subUnitId, option.payload);+ this._registerRange(option.unitId, option.payload.id, option.payload.payload);+ break;+ }+ case 'remove': {+ this._unregister(option.payload.id);+ this._unregisterRange(option.payload.id);+ break;+ }+ case 'updateRef': {+ const { unitId, subUnitId, id } = option;+ const link = this._hyperLinkModel.getHyperLink(unitId, subUnitId, id);+ if (!link) {+ return;+ }++ this._unregister(id);+ this._register(unitId, subUnitId, link);+ break;+ }+ case 'unload': {+ const { unitLinks } = option;+ unitLinks.forEach((subUnitData) => {+ const { links } = subUnitData;+ links.forEach((link) => {+ this._unregister(link.id);+ this._unregisterRange(link.id);+ });+ });+ break;+ }+ case 'update': {+ this._unregisterRange(option.id);+ this._registerRange(option.unitId, option.id, option.payload.payload);+ break;+ }+ }+ })+ );++ this.disposeWithMe(toDisposable(() => {+ this._disposableMap.forEach((item) => {+ item.dispose();+ });+ this._disposableMap.clear();+ }));+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.tsnew file mode 100644index 0000000000..b37b0cce90--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts@@ -0,0 +1,74 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Workbook } from '@univerjs/core';+import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import type { IRemoveSheetCommandParams } from '@univerjs/sheets';+import { RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';+import { Inject } from '@wendellhu/redi';+import { AddHyperLinkCommand, HyperLinkModel, RemoveHyperLinkCommand } from '@univerjs/sheets-hyper-link';++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkRemoveSheetController)+export class SheetsHyperLinkRemoveSheetController extends Disposable {+ constructor(+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService,+ @Inject(HyperLinkModel) private _hyperLinkModel: HyperLinkModel+ ) {+ super();+ this._initSheetChange();+ }++ private _initSheetChange() {+ this.disposeWithMe(+ this._sheetInterceptorService.interceptCommand({+ getMutations: (commandInfo) => {+ if (commandInfo.id === RemoveSheetCommand.id) {+ const params = commandInfo.params as IRemoveSheetCommandParams;+ const workbook = params.unitId ? this._univerInstanceService.getUnit<Workbook>(params.unitId) : this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return { redos: [], undos: [] };+ }+ const unitId = workbook.getUnitId();+ const subUnitId = params.subUnitId || workbook.getActiveSheet().getSheetId();+ const links = this._hyperLinkModel.getSubUnit(unitId, subUnitId);++ const redos = links.map((link) => ({+ id: RemoveHyperLinkCommand.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ },+ }));++ const undos = links.map((link) => ({+ id: AddHyperLinkCommand.id,+ params: {+ unitId,+ subUnitId,+ link,+ },+ }));++ return { redos, undos };+ }+ return { redos: [], undos: [] };+ },+ })+ );+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.tsnew file mode 100644index 0000000000..1c750ab93f--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts@@ -0,0 +1,95 @@+/**+ * 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 { Workbook } from '@univerjs/core';+import { BooleanNumber, Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, ThemeService, UniverInstanceType } from '@univerjs/core';+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';+import { Inject } from '@wendellhu/redi';+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import type { Spreadsheet } from '@univerjs/engine-render';+import { IRenderManagerService } from '@univerjs/engine-render';+import { HyperLinkModel } from '@univerjs/sheets-hyper-link';++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkRenderController)+export class SheetsHyperLinkRenderController extends Disposable {+ constructor(+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @Inject(ThemeService) private readonly _themeService: ThemeService+ ) {+ super();+ this._initViewModelIntercept();+ this._initSkeletonChange();+ }++ private _initViewModelIntercept() {+ this.disposeWithMe(+ this._sheetInterceptorService.intercept(+ INTERCEPTOR_POINT.CELL_CONTENT,+ {+ handler: (cell, pos, next) => {+ const { row, col, unitId, subUnitId } = pos;+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);+ const styleSheet = this._themeService.getCurrentTheme();++ if (link) {+ return next({+ ...cell,+ interceptorStyle: {+ ul: {+ s: BooleanNumber.TRUE,+ },+ cl: {+ rgb: styleSheet.blue500,+ },+ },+ });+ }++ return next(cell);+ },+ priority: 100,+ }+ )+ );+ }++ private _initSkeletonChange() {+ const markSkeletonDirty = () => {+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) return;++ const unitId = workbook.getUnitId();+ const subUnitId = workbook.getActiveSheet().getSheetId();+ const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ unitId, sheetId: subUnitId });+ const currentRender = this._renderManagerService.getRenderById(unitId);++ skeleton?.makeDirty(true);+ skeleton?.calculate();++ if (currentRender) {+ (currentRender.mainComponent as Spreadsheet).makeForceDirty();+ }+ };++ this.disposeWithMe(this._hyperLinkModel.linkUpdate$.subscribe(() => {+ markSkeletonDirty();+ }));+ }+}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.tsnew file mode 100644index 0000000000..bf0f74d62a--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts@@ -0,0 +1,291 @@+/**+ * 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 { IMutationInfo } from '@univerjs/core';+import { CellValueType, Disposable, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Tools } from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';+import { ClearSelectionAllCommand, ClearSelectionContentCommand, getSheetCommandTarget, SelectionManagerService, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';+import type { IAddHyperLinkCommandParams, IUpdateHyperLinkCommandParams, IUpdateHyperLinkMutationParams } from '@univerjs/sheets-hyper-link';+import { AddHyperLinkCommand, AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation, UpdateHyperLinkCommand, UpdateHyperLinkMutation } from '@univerjs/sheets-hyper-link';+import { hasProtocol, isLegalLink } from '../common/util';++@OnLifecycle(LifecycleStages.Starting, SheetHyperLinkSetRangeController)+export class SheetHyperLinkSetRangeController extends Disposable {+ constructor(+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ ) {+ super();++ this._initCommandInterceptor();+ }++ private _initCommandInterceptor() {+ this._initAddHyperLinkCommandInterceptor();+ this._initSetRangeValuesCommandInterceptor();+ this._initUpdateHyperLinkCommandInterceptor();+ this._initClearSelectionCommandInterceptor();+ }++ private _initAddHyperLinkCommandInterceptor() {+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({++ getMutations: (command) => {+ if (command.id === AddHyperLinkCommand.id) {+ const params = command.params as IAddHyperLinkCommandParams;+ const { unitId, subUnitId, link } = params;+ const redoParams: ISetRangeValuesMutationParams = {+ unitId,+ subUnitId,+ cellValue: {+ [link.row]: {+ [link.column]: {+ v: link.display,+ t: CellValueType.STRING,+ p: null,+ },+ },+ },+ };++ return {+ redos: [{+ id: SetRangeValuesMutation.id,+ params: redoParams,+ }],+ undos: [{+ id: SetRangeValuesMutation.id,+ params: SetRangeValuesUndoMutationFactory(this._injector, redoParams),++ }],+ };+ }++ return {+ redos: [],+ undos: [],+ };+ },+ }));+ }++ private _initUpdateHyperLinkCommandInterceptor() {+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({+ getMutations: (command) => {+ if (command.id === UpdateHyperLinkCommand.id) {+ const params = command.params as IUpdateHyperLinkCommandParams;+ const { unitId, subUnitId, id, payload } = params;+ const current = this._hyperLinkModel.getHyperLink(unitId, subUnitId, id);+ if (current && current.display !== payload.display) {+ const redoParams: ISetRangeValuesMutationParams = {+ unitId,+ subUnitId,+ cellValue: {+ [current.row]: {+ [current.column]: {+ v: payload.display,+ t: CellValueType.STRING,+ p: null,+ },+ },+ },+ };++ return {+ redos: [{+ id: SetRangeValuesMutation.id,+ params: redoParams,+ }],+ undos: [{+ id: SetRangeValuesMutation.id,+ params: SetRangeValuesUndoMutationFactory(this._injector, redoParams),++ }],+ };+ }+ }++ return {+ redos: [],+ undos: [],+ };+ },+ }));+ }++ // eslint-disable-next-line max-lines-per-function+ private _initSetRangeValuesCommandInterceptor() {+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({++ // eslint-disable-next-line max-lines-per-function+ getMutations: (command) => {+ if (command.id === SetRangeValuesCommand.id) {+ const params = command.params as ISetRangeValuesMutationParams;++ const { unitId, subUnitId } = params;+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ if (params.cellValue) {+ // eslint-disable-next-line max-lines-per-function+ new ObjectMatrix(params.cellValue).forValue((row, col, cell) => {+ const cellValue = (cell?.v ?? cell?.p?.body?.dataStream.slice(0, -2) ?? '').toString();+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);++ if (!link) {+ if (isLegalLink(cellValue)) {+ const id = Tools.generateRandomId();+ undos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id,+ },+ });+ redos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link: {+ id,+ row,+ column: col,+ display: cellValue,+ payload: hasProtocol(cellValue) ? cellValue : `http://${cellValue}`,+ },+ },+ });+ }+ return;+ }++ if (link.display === cellValue) {+ return;+ }++ if (!cellValue) {+ redos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ },+ });+ undos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ },+ });+ }++ const redoParams: IUpdateHyperLinkMutationParams = {+ unitId,+ subUnitId,+ id: link.id,+ payload: {+ payload: link.payload,+ display: cellValue,+ },+ };+ const undoParams: IUpdateHyperLinkMutationParams = {+ unitId,+ subUnitId,+ id: link.id,+ payload: {+ payload: link.payload,+ display: link.display,+ },+ };+ redos.push({+ id: UpdateHyperLinkMutation.id,+ params: redoParams,+ });+ undos.push({+ id: UpdateHyperLinkMutation.id,+ params: undoParams,+ });+ });+ }++ return {+ undos,+ redos,+ };+ }+ return {+ redos: [],+ undos: [],+ };+ },+ }));+ }++ private _initClearSelectionCommandInterceptor() {+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({+ getMutations: (command) => {+ if (command.id === ClearSelectionContentCommand.id || command.id === ClearSelectionAllCommand.id) {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ const selection = this._selectionManagerService.getFirst();+ const target = getSheetCommandTarget(this._univerInstanceService);+ if (selection && target) {+ const { unitId, subUnitId } = target;+ Range.foreach(selection.range, (row, col) => {+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);+ if (link) {+ redos.push({+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ },+ });+ undos.push({+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ },+ });+ }+ });+ }++ return {+ redos,+ undos,+ };+ }++ return {+ redos: [],+ undos: [],+ };+ },+ }));+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.tsnew file mode 100644index 0000000000..52b62b610e--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts@@ -0,0 +1,87 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, ICommandService, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';+import type { MenuConfig } from '@univerjs/ui';+import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';+import { Inject, Injector } from '@wendellhu/redi';+import { LinkSingle } from '@univerjs/icons';+import { CellLinkPopup } from '../views/CellLinkPopup';+import { CellLinkEdit } from '../views/CellLinkEdit';+import { CloseHyperLinkSidebarOperation, InsertHyperLinkOperation, InsertHyperLinkToolbarOperation, OpenHyperLinkSidebarOperation } from '../commands/operations/sidebar.operations';+import { zhCN } from '../locales';+import { insertLinkMenuFactory, insertLinkMenuToolbarFactory, InsertLinkShortcut } from './menu';++export interface IUniverSheetsHyperLinkUIConfig {+ menu?: MenuConfig;+}++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkUIController)+export class SheetsHyperLinkUIController extends Disposable {+ constructor(+ private _config: IUniverSheetsHyperLinkUIConfig | undefined,+ @Inject(ComponentManager) private _componentManager: ComponentManager,+ @ICommandService private _commandService: ICommandService,+ @Inject(LocaleService) private _localeService: LocaleService,+ @IMenuService private _menuService: IMenuService,+ @Inject(Injector) private _injector: Injector,+ @Inject(IShortcutService) private _shortcutService: IShortcutService+ ) {+ super();++ this._initComponents();+ this._initCommands();+ this._initLocale();+ this._initMenus();+ this._initShortCut();+ }++ private _initComponents() {+ ([+ [CellLinkPopup, CellLinkPopup.componentKey],+ [CellLinkEdit, CellLinkEdit.componentKey],+ [LinkSingle, 'LinkSingle'],+ ] as const).forEach(([comp, key]) => {+ this._componentManager.register(key, comp);+ });+ }++ private _initCommands() {+ [+ OpenHyperLinkSidebarOperation,+ CloseHyperLinkSidebarOperation,+ InsertHyperLinkOperation,+ InsertHyperLinkToolbarOperation,+ ].forEach((command) => {+ this._commandService.registerCommand(command);+ });+ }++ private _initLocale() {+ this._localeService.load({+ zhCN,+ });+ }++ private _initMenus() {+ this._menuService.addMenuItem(insertLinkMenuFactory(this._injector), this._config?.menu ?? {});+ this._menuService.addMenuItem(insertLinkMenuToolbarFactory(this._injector), this._config?.menu ?? {});+ }++ private _initShortCut() {+ this._shortcutService.registerShortcut(InsertLinkShortcut);+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/url.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/url.controller.tsnew file mode 100644index 0000000000..98624d2f0b--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/url.controller.ts@@ -0,0 +1,37 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import { SheetsHyperLinkResolverService } from '../services/resolver.service';++@OnLifecycle(LifecycleStages.Rendered, SheetHyperLinkUrlController)+export class SheetHyperLinkUrlController extends Disposable {+ constructor(+ @Inject(SheetsHyperLinkResolverService) private _resolverService: SheetsHyperLinkResolverService+ ) {+ super();+ this._handleInitUrl();+ }++ private _handleInitUrl() {+ const hash = location.hash;+ if (hash) {+ const linkInfo = this._resolverService.parseHyperLink(hash);+ linkInfo.handler();+ }+ }+}diff --git a/packages/sheets-hyper-link-ui/src/index.ts b/packages/sheets-hyper-link-ui/src/index.tsnew file mode 100644index 0000000000..ee65bb8636--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/index.ts@@ -0,0 +1,31 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';+export { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';+export { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';+export { SheetsHyperLinkPopupService } from './services/popup.service';+export { SheetsHyperLinkResolverService } from './services/resolver.service';+export { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';+export { SheetsHyperLinkPopupController } from './controllers/popup.controller';+export { SheetsHyperLinkUIController } from './controllers/ui.controller';+export { SheetsHyperLinkAutoFillController } from './controllers/auto-fill.controller';+export { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';+export { SheetHyperLinkUrlController } from './controllers/url.controller';++export { UniverSheetsHyperLinkUIPlugin } from './plugin';+export { OpenHyperLinkSidebarOperation, InsertHyperLinkOperation, CloseHyperLinkSidebarOperation } from './commands/operations/sidebar.operations';+export type { IOpenHyperLinkSidebarOperationParams } from './commands/operations/sidebar.operations';diff --git a/packages/sheets-hyper-link-ui/src/locales/en-US.ts b/packages/sheets-hyper-link-ui/src/locales/en-US.tsnew file mode 100644index 0000000000..c2f36252ea--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/locales/en-US.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type zhCN from './zh-CN';++const enUS: typeof zhCN = {+ hyperLink: {+ form: {+ editTitle: 'Edit Link',+ addTitle: 'Insert Link',+ label: 'Label',+ type: 'Type',+ link: 'Link',+ linkPlaceholder: 'Enter link',+ range: 'Range',+ worksheet: 'Worksheet',+ definedName: 'Defined Name',+ ok: 'OK',+ cancel: 'Cancel',+ labelPlaceholder: 'Enter label',+ inputError: 'Please enter',+ selectError: 'Please select',+ linkError: 'Please enter a legal link',+ },+ menu: {+ add: 'Insert Link',+ },+ message: {+ noSheet: 'Target sheet has been delete',+ refError: 'Invalid Range',+ hiddenSheet: 'Cannot open the link because the linked sheet is hidden',+ coped: 'Link copied to clipboard',+ },+ popup: {+ copy: 'Copy Link',+ edit: 'Edit Link',+ cancel: 'Cancel Link',+ },+ },+};++export default enUS;diff --git a/packages/sheets-hyper-link-ui/src/locales/index.ts b/packages/sheets-hyper-link-ui/src/locales/index.tsnew file mode 100644index 0000000000..9175ead08b--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/locales/index.ts@@ -0,0 +1,20 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import zhCN from './zh-CN';+import enUS from './en-US';++export { zhCN, enUS };diff --git a/packages/sheets-hyper-link-ui/src/locales/zh-CN.ts b/packages/sheets-hyper-link-ui/src/locales/zh-CN.tsnew file mode 100644index 0000000000..c48eb6b7dc--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/locales/zh-CN.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export default {+ hyperLink: {+ form: {+ editTitle: '编辑链接',+ addTitle: '插入链接',+ label: '文本',+ labelPlaceholder: '输入文本',+ type: '类型',+ link: '链接',+ linkPlaceholder: '输入链接地址',+ range: '单元格',+ worksheet: '工作表',+ definedName: '定义的名称',+ ok: '确认',+ cancel: '取消',+ inputError: '请输入',+ selectError: '请选择',+ linkError: '请输入合法的链接',+ },+ menu: {+ add: '添加链接',+ },+ message: {+ noSheet: '该子表已被删除',+ refError: '错误的引用',+ hiddenSheet: '无法打开被隐藏的子表',+ coped: '链接已被复制到剪贴板',+ },+ popup: {+ copy: '复制',+ edit: '编辑',+ cancel: '取消链接',+ },+ },+};diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.tsnew file mode 100644index 0000000000..044e6db278--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/plugin.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 type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import { UniverInstanceType } from '@univerjs/core';+import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';+import { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';+import { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';+import { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';+import { SheetsHyperLinkPopupService } from './services/popup.service';+import { SheetsHyperLinkResolverService } from './services/resolver.service';+import { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';+import { SheetsHyperLinkPopupController } from './controllers/popup.controller';+import type { IUniverSheetsHyperLinkUIConfig } from './controllers/ui.controller';+import { SheetsHyperLinkUIController } from './controllers/ui.controller';+import { SHEETS_HYPER_LINK_UI_PLUGIN } from './types/const';+import { SheetsHyperLinkAutoFillController } from './controllers/auto-fill.controller';+import { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';+import { SheetHyperLinkUrlController } from './controllers/url.controller';++export class UniverSheetsHyperLinkUIPlugin extends UniverSheetsHyperLinkPlugin {+ static override pluginName: string = SHEETS_HYPER_LINK_UI_PLUGIN;+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ private _config: IUniverSheetsHyperLinkUIConfig,+ @Inject(Injector) protected override _injector: Injector+ ) {+ super(_config, _injector);+ }++ override onStarting(injector: Injector): void {+ super.onStarting(injector);+ const dependencies: Dependency[] = [+ [SheetsHyperLinkResolverService],+ [SheetsHyperLinkPopupService],++ [SheetsHyperLinkRemoveSheetController],+ [SheetsHyperLinkRefRangeController],+ [SheetsHyperLinkRenderController],+ [SheetHyperLinkSetRangeController],+ [SheetsHyperLinkPopupController],+ [+ SheetsHyperLinkUIController,+ {+ useFactory: () => this._injector.createInstance(SheetsHyperLinkUIController, this._config),+ },+ ],+ [SheetsHyperLinkAutoFillController],+ [SheetsHyperLinkCopyPasteController],+ [SheetHyperLinkUrlController],+ ];++ dependencies.forEach((dep) => {+ injector.add(dep);+ });+ }+}diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.tsnew file mode 100644index 0000000000..f7a9f1f2e8--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts@@ -0,0 +1,99 @@+/**+ * 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 { ISheetLocationBase } from '@univerjs/sheets';+import { HyperLinkModel } from '@univerjs/sheets-hyper-link';+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import type { IDisposable } from '@wendellhu/redi';+import { Inject } from '@wendellhu/redi';+import { BehaviorSubject, Subject } from 'rxjs';+import { CellLinkPopup } from '../views/CellLinkPopup';++interface IHyperLinkPopup {+ unitId: string;+ subUnitId: string;+ id: string;+ disposable?: IDisposable;+}++interface IHyperLinkEditing {+ unitId: string;+ subUnitId: string;+ row: number;+ column: number;+}++export class SheetsHyperLinkPopupService {+ private _currentPopup: IHyperLinkPopup | null = null;+ private _currentPopup$ = new Subject<IHyperLinkPopup | null>();+ currentPopup$ = this._currentPopup$.asObservable();++ private _currentEditing$ = new BehaviorSubject<IHyperLinkEditing | null>(null);+ currentEditing$ = this._currentEditing$.asObservable();++ get currentPopup() {+ return this._currentPopup;+ }++ get currentEditing() {+ return this._currentEditing$.getValue();+ }++ constructor(+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,+ @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService+ ) {}++ showPopup(location: ISheetLocationBase) {+ this.hideCurrentPopup();+ const { unitId, subUnitId, row, col } = location;+ const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);+ if (!link) {+ return;+ }++ const disposable = this._sheetCanvasPopManagerService.attachPopupToCell(row, col, {+ componentKey: CellLinkPopup.componentKey,+ direction: 'bottom',+ closeOnSelfTarget: true,+ });+ if (disposable) {+ this._currentPopup = {+ unitId,+ subUnitId,+ id: link.id,+ disposable,+ };+ this._currentPopup$.next(this._currentPopup);+ }+ }++ hideCurrentPopup() {+ if (this._currentPopup) {+ this._currentPopup.disposable?.dispose();+ this._currentPopup = null;+ this._currentPopup$.next(null);+ }+ }++ startEditing(link: IHyperLinkEditing) {+ this._currentEditing$.next(link);+ }++ endEditing() {+ this._currentEditing$.next(null);+ }+}diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.tsnew file mode 100644index 0000000000..46fc927bf3--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts@@ -0,0 +1,265 @@+/**+ * 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 { IRange, Workbook } from '@univerjs/core';+import { ICommandService, isValidRange, IUniverInstanceService, LocaleService, Rectangle, UniverInstanceType } from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { deserializeRangeWithSheet, IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';+import { NORMAL_SELECTION_PLUGIN_NAME, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { ScrollToCellCommand } from '@univerjs/sheets-ui';+import { IMessageService } from '@univerjs/ui';+import { Inject } from '@wendellhu/redi';+import { ERROR_RANGE } from '../types/const';++interface ISheetUrlParams {+ gid?: string;+ range?: string;+ rangeid?: string;+}++function getContainRange(range: IRange, mergedCells: IRange[]) {+ const relativeCells: IRange[] = [];+ mergedCells.forEach((cell) => {+ if (Rectangle.intersects(range, cell)) {+ relativeCells.push(cell);+ }+ });++ return Rectangle.realUnion(range, ...relativeCells);+}++export class SheetsHyperLinkResolverService {+ constructor(+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService,+ @ICommandService private _commandService: ICommandService,+ @IDefinedNamesService private _definedNamesService: IDefinedNamesService,+ @IMessageService private _messageService: IMessageService,+ @Inject(LocaleService) private _localeService: LocaleService+ ) { }++ private _getURLName(params: ISheetUrlParams) {+ const { gid, range, rangeid } = params;+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return null;+ }++ const sheet = gid ? workbook.getSheetBySheetId(gid) : workbook.getActiveSheet();+ const sheetName = sheet?.getName() ?? '';++ if (range) {+ const rangeObj = deserializeRangeWithSheet(range).range;+ if (isValidRange(rangeObj) && range !== ERROR_RANGE) {+ return {+ type: 'range',+ name: serializeRangeWithSheet(sheetName, rangeObj),+ } as const;+ } else {+ return {+ type: 'range-error',+ name: this._localeService.t('hyperLink.message.refError'),+ } as const;+ }+ }++ if (rangeid) {+ const range = this._definedNamesService.getValueById(workbook.getUnitId(), rangeid);+ if (range) {+ return {+ type: 'defineName',+ name: range.formulaOrRefString,+ } as const;+ } else {+ return {+ type: 'range-error',+ name: this._localeService.t('hyperLink.message.refError'),+ } as const;+ }+ }++ if (gid) {+ const worksheet = workbook.getSheetBySheetId(gid);+ if (worksheet) {+ return {+ type: 'sheet',+ name: worksheet.getName(),+ } as const;+ } else {+ return {+ type: 'sheet-error',+ name: this._localeService.t('hyperLink.message.refError'),+ } as const;+ }+ }++ return null;+ }++ navigateTo(params: ISheetUrlParams) {+ const { gid, range, rangeid } = params;+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return;+ }+ const unitId = workbook.getUnitId();+ if (rangeid) {+ this.navigateToDefineName(unitId, rangeid);+ }++ if (!gid) {+ return;+ }++ if (range) {+ const rangeInfo = deserializeRangeWithSheet(range);+ if (isValidRange(rangeInfo.range) && range !== ERROR_RANGE) {+ this.navigateToRange(unitId, gid, rangeInfo.range);+ }+ return;+ }++ this.navigateToSheetById(unitId, gid);+ }++ parseHyperLink(urlStr: string) {+ if (urlStr?.startsWith('#')) {+ const search = new URLSearchParams(urlStr.slice(1));+ // range, gid, rangeid+ const searchObj: ISheetUrlParams = {+ gid: search.get('gid') ?? '',+ range: search.get('range') ?? '',+ rangeid: search.get('rangeid') ?? '',+ };+ const urlInfo = this._getURLName(searchObj);+ return {+ type: urlInfo?.type || 'link',+ name: urlInfo?.name || urlStr,+ url: urlStr,+ searchObj,+ handler: () => {+ this.navigateTo(searchObj);+ },+ } as const;+ } else {+ return {+ type: 'outer',+ name: urlStr,+ url: urlStr,+ handler: () => {+ this.navigateToOtherWebsite(urlStr);+ },+ } as const;+ }+ }++ async navigateToRange(unitId: string, subUnitId: string, range: IRange) {+ const worksheet = await this.navigateToSheetById(unitId, subUnitId);+ if (worksheet) {+ const realRange = getContainRange(range, worksheet.getMergeData());+ await this._commandService.executeCommand(+ SetSelectionsOperation.id,+ {+ unitId,+ subUnitId,+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [{++ range: realRange,+ }],+ } as ISetSelectionsOperationParams+ );+ await this._commandService.executeCommand(ScrollToCellCommand.id, {+ range: realRange,+ });+ }+ }++ async navigateToSheet(unitId: string, sheetName: string) {+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return false;+ }+ const worksheet = workbook.getActiveSheet();++ if (worksheet?.getName() === sheetName) {+ return true;+ }+ const targetSheet = workbook.getSheetBySheetName(sheetName);++ if (!targetSheet) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.noSheet'),+ type: MessageType.Error,+ });+ return;+ }++ const sheetId = targetSheet.getSheetId();+ if (workbook.getHiddenWorksheets().indexOf(sheetId) > -1) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.hiddenSheet'),+ type: MessageType.Error,+ });+ }++ return await this._commandService.executeCommand(SetWorksheetActiveOperation.id, { unitId, subUnitId: sheetId });+ }++ async navigateToSheetById(unitId: string, subUnitId: string) {+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return false;+ }+ const worksheet = workbook.getActiveSheet();++ if (worksheet.getSheetId() === subUnitId) {+ return worksheet;+ }++ const targetSheet = workbook.getSheetBySheetId(subUnitId);++ if (!targetSheet) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.noSheet'),+ type: MessageType.Error,+ });+ return false;+ }++ if (workbook.getHiddenWorksheets().indexOf(subUnitId) > -1) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.hiddenSheet'),+ type: MessageType.Error,+ });+ return false;+ }++ if (await this._commandService.executeCommand(SetWorksheetActiveOperation.id, { unitId, subUnitId })) {+ return targetSheet;+ }+ return false;+ }++ async navigateToDefineName(unitId: string, rangeid: string) {+ this._definedNamesService.focusRange(unitId, rangeid);+ return true;+ }++ async navigateToOtherWebsite(url: string) {+ window.open(url, '_blank', 'noopener noreferrer');+ }+}diff --git a/packages/sheets-hyper-link-ui/src/types/const.ts b/packages/sheets-hyper-link-ui/src/types/const.tsnew file mode 100644index 0000000000..1ae494cceb--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/types/const.ts@@ -0,0 +1,19 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export const SHEETS_HYPER_LINK_UI_PLUGIN = 'SHEETS_HYPER_LINK_UI_PLUGIN';++export const ERROR_RANGE = 'err';diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.lessnew file mode 100644index 0000000000..a18b5b4038--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.module.less@@ -0,0 +1,5 @@+.cell-link-edit-buttons {+ display: flex;+ flex-direction: row;+ justify-content: flex-end;+}diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsxnew file mode 100644index 0000000000..14fa63ffc5--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx@@ -0,0 +1,362 @@+/**+ * 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 React, { useEffect, useMemo, useRef, useState } from 'react';+import { Button, FormLayout, Input, Select } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';+import type { ICellData, Nullable, Workbook } from '@univerjs/core';+import { createInternalEditorID, DEFAULT_EMPTY_DOCUMENT_VALUE, ICommandService, isValidRange, IUniverInstanceService, LocaleService, Tools, UniverInstanceType } from '@univerjs/core';+import { RangeSelector, useObservable } from '@univerjs/ui';+import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeToRefString, serializeRangeWithSheet } from '@univerjs/engine-formula';+import { AddHyperLinkCommand, HyperLinkModel, UpdateHyperLinkCommand } from '@univerjs/sheets-hyper-link';+import { SetWorksheetActiveOperation } from '@univerjs/sheets';+import { ScrollToCellCommand } from '@univerjs/sheets-ui';+import { SheetsHyperLinkPopupService } from '../../services/popup.service';+import { SheetsHyperLinkResolverService } from '../../services/resolver.service';+import { CloseHyperLinkSidebarOperation } from '../../commands/operations/sidebar.operations';+import { hasProtocol, isLegalLink } from '../../common/util';+import styles from './index.module.less';++enum LinkType {+ link = 'link',+ range = 'range',+ sheet = 'gid',+ definedName = 'rangeid',+}++function getCellValueOrigin(cell: Nullable<ICellData>) {+ if (cell === null) {+ return '';+ }++ if (cell?.p) {+ const body = cell?.p.body;++ if (body == null) {+ return '';+ }++ const data = body.dataStream;+ const lastString = data.substring(data.length - 2, data.length);+ const newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;++ return newDataStream;+ }++ return cell?.v;+}++export const CellLinkEdit = () => {+ const [id, setId] = useState('');+ const [display, setDisplay] = useState('');+ const [type, setType] = useState(LinkType.link);+ const [payload, setPayload] = useState('');+ const localeService = useDependency(LocaleService);+ const definedNameService = useDependency(IDefinedNamesService);+ const univerInstanceService = useDependency(IUniverInstanceService);+ const popupService = useDependency(SheetsHyperLinkPopupService);+ const editing = useObservable(popupService.currentEditing$);+ const hyperLinkModel = useDependency(HyperLinkModel);+ const resolverService = useDependency(SheetsHyperLinkResolverService);+ const commandService = useDependency(ICommandService);+ const [showError, setShowError] = useState(false);++ const setByPayload = useRef(false);++ useEffect(() => {+ if (editing?.row !== undefined && editing.column !== undefined) {+ const link = hyperLinkModel.getHyperLinkByLocation(editing.unitId, editing.subUnitId, editing.row, editing.column);+ if (link) {+ const linkInfo = resolverService.parseHyperLink(link.payload);+ setId(link.id);+ setDisplay(link.display);+ if (linkInfo.type === 'outer') {+ setType(LinkType.link);+ setPayload(linkInfo.url);+ return;+ } else {+ const params = linkInfo.searchObj;+ if (params.rangeid) {+ setType(LinkType.definedName);+ setPayload(params.rangeid);+ return;+ }++ if (params.range) {+ const sheetName = params.gid ?+ univerInstanceService+ .getUnit<Workbook>(editing.unitId)+ ?.getSheetBySheetId(params.gid)+ ?.getName()+ ?? ''+ : '';+ setType(LinkType.range);+ setPayload(serializeRangeWithSheet(sheetName, deserializeRangeWithSheet(params.range).range));+ return;+ }++ if (params.gid) {+ setType(LinkType.sheet);+ setPayload(params.gid);+ return;+ }+ }+ }+ const workbook = univerInstanceService.getUnit<Workbook>(editing.unitId);+ const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);+ const cell = worksheet?.getCellRaw(editing.row, editing.column);++ const cellValue = getCellValueOrigin(cell);+ setType(LinkType.link);+ setPayload('');+ setDisplay((cellValue ?? '').toString());+ setId('');+ return;+ }++ setType(LinkType.link);+ setPayload('');+ setDisplay('');+ setId('');+ }, [editing, hyperLinkModel, resolverService, univerInstanceService]);++ const payloadInitial = useMemo(() => payload, [type]);++ const linkTypeOptions = [+ {+ label: localeService.t('hyperLink.form.link'),+ value: LinkType.link,+ },+ {+ label: localeService.t('hyperLink.form.range'),+ value: LinkType.range,+ },+ {+ label: localeService.t('hyperLink.form.worksheet'),+ value: LinkType.sheet,+ },+ {+ label: localeService.t('hyperLink.form.definedName'),+ value: LinkType.definedName,+ },+ ];+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return;+ }+ const hiddens = workbook.getHiddenWorksheets();+ const sheetsOption = workbook.getSheets().map((sheet) => ({ label: sheet.getName(), value: sheet.getSheetId() })).filter((opt) => hiddens.indexOf(opt.value) === -1);+ const definedNames = Object.values(definedNameService.getDefinedNameMap(workbook.getUnitId()) ?? {}).map((value) => ({+ label: value.name,+ value: value.id,+ }));++ const formatUrl = (type: LinkType, payload: string) => {+ if (type === LinkType.link) {+ return hasProtocol(payload) ? payload : `http://${payload}`;+ }++ if (type === LinkType.range) {+ const info = deserializeRangeWithSheet(payload);+ const worksheet = workbook.getSheetBySheetName(info.sheetName);+ if (worksheet) {+ return `#gid=${worksheet.getSheetId()}&range=${serializeRange(info.range)}`;+ }+ }++ return `#${type}=${payload}`;+ };++ const handleSubmit = async () => {+ if (editing) {+ if (id) {+ await commandService.executeCommand(UpdateHyperLinkCommand.id, {+ unitId: editing.unitId,+ subUnitId: editing.subUnitId,+ id,+ payload: {+ display,+ payload: formatUrl(type, payload),+ },+ });+ } else {+ await commandService.executeCommand(AddHyperLinkCommand.id, {+ unitId: editing.unitId,+ subUnitId: editing.subUnitId,+ link: {+ id: Tools.generateRandomId(),+ row: editing.row,+ column: editing.column,+ payload: formatUrl(type, payload),+ display,+ },+ });+ }+ }+ if (editing) {+ await commandService.executeCommand(SetWorksheetActiveOperation.id, {+ unitId: editing.unitId,+ subUnitId: editing.subUnitId,+ });++ await commandService.executeCommand(ScrollToCellCommand.id, {+ range: {+ startRow: editing.row,+ endRow: editing.row,+ startColumn: editing.column,+ endColumn: editing.column,+ },+ });+ }++ commandService.executeCommand(CloseHyperLinkSidebarOperation.id);+ };++ return (+ <div>+ <FormLayout+ label={localeService.t('hyperLink.form.label')}+ error={showError && !display ? localeService.t('hyperLink.form.inputError') : ''}+ >+ <Input+ value={display}+ onChange={(v) => {+ setDisplay(v);+ setByPayload.current = false;+ }}+ placeholder={localeService.t('hyperLink.form.labelPlaceholder')}+ />+ </FormLayout>+ <FormLayout label={localeService.t('hyperLink.form.type')}>+ <Select+ options={linkTypeOptions}+ value={type}+ onChange={(newType) => {+ setType(newType as LinkType);+ setPayload('');+ }}+ />+ </FormLayout>+ {type === LinkType.link && (+ <FormLayout+ error={showError ? !payload ? localeService.t('hyperLink.form.inputError') : !isLegalLink(payload) ? localeService.t('hyperLink.form.linkError') : '' : ''}+ >+ <Input+ value={payload}+ onChange={(newLink) => {+ setPayload(newLink);+ if (newLink && (setByPayload.current || !display)) {+ setDisplay(newLink);+ setByPayload.current = true;+ }+ }}+ placeholder={localeService.t('hyperLink.form.linkPlaceholder')}+ />+ </FormLayout>+ )}+ {type === LinkType.range && (+ <FormLayout error={showError && !payload ? localeService.t('hyperLink.form.inputError') : ''}>+ <RangeSelector+ openForSheetUnitId={workbook.getUnitId()}+ id={createInternalEditorID('hyper-link-edit')}+ isSingleChoice+ value={payloadInitial}+ onChange={(newValue) => {+ const range = newValue[0];+ if (!range || !isValidRange(range.range)) {+ return;+ }+ if (!range.sheetName) {+ range.sheetName = workbook.getActiveSheet().getName();+ }+ const newPayload = serializeRangeToRefString(range);+ setPayload(newPayload);++ if (newPayload && (setByPayload.current || !display)) {+ setDisplay(newPayload);+ setByPayload.current = true;+ }+ }}++ />+ </FormLayout>+ )}+ {type === LinkType.sheet && (+ <FormLayout error={showError && !payload ? localeService.t('hyperLink.form.selectError') : ''}>+ <Select+ options={sheetsOption}+ value={payload}+ onChange={(newPayload) => {+ setPayload(newPayload);+ const label = sheetsOption.find((i) => i.value === newPayload)?.label;+ if (label && (setByPayload.current || !display)) {+ setDisplay(label);+ setByPayload.current = true;+ }+ }}+ />+ </FormLayout>+ )}+ {type === LinkType.definedName && (+ <FormLayout error={showError && !payload ? localeService.t('hyperLink.form.selectError') : ''}>+ <Select+ options={definedNames}+ value={payload}+ onChange={(newValue) => {+ setPayload(newValue);+ const label = definedNames.find((i) => i.value === newValue)?.label;+ if (label && (setByPayload.current || !display)) {+ setDisplay(label);+ setByPayload.current = true;+ }+ }}+ />+ </FormLayout>+ )}+ <div className={styles.cellLinkEditButtons}>+ <Button+ onClick={() => {+ if (editing) {+ commandService.executeCommand(SetWorksheetActiveOperation.id, {+ unitId: editing.unitId,+ subUnitId: editing.subUnitId,+ });+ }+ commandService.executeCommand(CloseHyperLinkSidebarOperation.id);+ }}+ >+ {localeService.t('hyperLink.form.cancel')}+ </Button>+ <Button+ type="primary"+ style={{ marginLeft: 8 }}+ onClick={async () => {+ if (!display || !payload || (type === LinkType.link && !isLegalLink(payload))) {+ setShowError(true);+ return;+ }++ handleSubmit();+ }}+ >+ {localeService.t('hyperLink.form.ok')}+ </Button>+ </div>+ </div>+ );+};++CellLinkEdit.componentKey = 'univer.sheet.cell-link-edit';diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.less b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.lessnew file mode 100644index 0000000000..6869fe1b64--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.less@@ -0,0 +1,82 @@+.cell-link {+ display: flex;+ flex-direction: row;+ align-items: center;+ justify-content: space-between;+ padding: 12px;+ box-shadow: var(--box-shadow-base);+ border-radius: 8px;+ border: 1px solid rgb(var(--grey-200));+ background: rgb(var(--color-white));+ max-width: 328px;+ overflow: hidden;+}++.cell-link-type {+ height: 20px;+ width: 20px;+ font-size: 16px;+ margin-right: 8px;+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 auto;+ color: rgb(var(--color-black));+}++.cell-link-content {+ height: 24px;+ display: flex;+ flex-direction: row;+ align-items: center;+ font-size: 13px;+ line-height: 20px;+ color: rgb(var(--blue-500));+ cursor: pointer;+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.cell-link-content-error {+ color: rgb(var(--grey-500));+}++.cell-link-url {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+}++.cell-link-operations {+ display: flex;+ flex-direction: row;+ justify-content: center;+ align-items: center;+ height: 24px;+ flex-basis: auto;+ flex-grow: 0;+ flex-shrink: 0;+}++.cell-link-operation {+ width: 24px;+ height: 24px;+ border-radius: 4px;+ margin-left: 8px;+ font-size: 16px;+ display: flex;+ flex-direction: row;+ justify-content: center;+ align-items: center;+ cursor: pointer;+ border-radius: 4px;+}+.cell-link-operation-error {+ color: rgb(var(--grey-500));+}++.cell-link-operation:hover {+ background: #ccc;+}diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsxnew file mode 100644index 0000000000..ae780717d3--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx@@ -0,0 +1,128 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { useDependency, useObservable } from '@wendellhu/redi/react-bindings';+import { CancelHyperLinkCommand, HyperLinkModel } from '@univerjs/sheets-hyper-link';+import React from 'react';+import { AllBorderSingle, CopySingle, LinkSingle, UnlinkSingle, WriteSingle, Xlsx } from '@univerjs/icons';+import { ICommandService, LocaleService } from '@univerjs/core';+import cs from 'clsx';+import { MessageType, Tooltip } from '@univerjs/design';+import { IMessageService } from '@univerjs/ui';+import { SheetsHyperLinkPopupService } from '../../services/popup.service';+import { SheetsHyperLinkResolverService } from '../../services/resolver.service';+import { OpenHyperLinkSidebarOperation } from '../../commands/operations/sidebar.operations';+import styles from './index.module.less';++const iconsMap = {+ outer: <LinkSingle />,+ link: <LinkSingle />,+ sheet: <Xlsx />,+ range: <AllBorderSingle />,+ defineName: <AllBorderSingle />,+ 'range-error': <AllBorderSingle />,+ 'sheet-error': <Xlsx />,+};++export const CellLinkPopup = () => {+ const popupService = useDependency(SheetsHyperLinkPopupService);+ const hyperLinkModel = useDependency(HyperLinkModel);+ const commandService = useDependency(ICommandService);+ const messageService = useDependency(IMessageService);+ const localeService = useDependency(LocaleService);+ const currentPopup = useObservable(popupService.currentPopup$, popupService.currentPopup);+ const resolverService = useDependency(SheetsHyperLinkResolverService);+ if (!currentPopup) {+ return null;+ }+ const { unitId, subUnitId, id } = currentPopup;+ const link = hyperLinkModel.getHyperLink(unitId, subUnitId, id);+ if (!link) {+ return null;+ }+ const linkObj = resolverService.parseHyperLink(link.payload);+ const isError = linkObj.type.indexOf('error') > -1;++ return (+ <div className={styles.cellLink} onClick={() => popupService.hideCurrentPopup()}>+ <div className={cs(styles.cellLinkContent, { [styles.cellLinkContentError]: isError })} onClick={linkObj.handler}>+ <div className={styles.cellLinkType}>+ {iconsMap[linkObj.type]}+ </div>+ <div className={styles.cellLinkUrl}>+ {linkObj.name}+ </div>+ </div>+ <div className={styles.cellLinkOperations}>+ <div+ className={cs(styles.cellLinkOperation, { [styles.cellLinkOperationError]: isError })}+ onClick={() => {+ if (isError) {+ return;+ }+ if (linkObj.type !== 'outer') {+ const url = new URL(window.location.href);+ url.hash = linkObj.url.slice(1);+ navigator.clipboard.writeText(url.href);+ } else {+ navigator.clipboard.writeText(linkObj.url);+ }+ messageService.show({+ content: localeService.t('hyperLink.message.coped'),+ type: MessageType.Info,+ });+ }}+ >+ <Tooltip placement="bottom" title={localeService.t('hyperLink.popup.copy')}>+ <CopySingle />+ </Tooltip>++ </div>+ <div+ className={styles.cellLinkOperation}+ onClick={() => {+ commandService.executeCommand(OpenHyperLinkSidebarOperation.id, {+ unitId,+ subUnitId,+ row: link.row,+ column: link.column,+ });+ }}+ >+ <Tooltip placement="bottom" title={localeService.t('hyperLink.popup.edit')}>+ <WriteSingle />+ </Tooltip>+ </div>+ <div+ className={styles.cellLinkOperation}+ onClick={() => {+ commandService.executeCommand(CancelHyperLinkCommand.id, {+ unitId,+ subUnitId,+ id: link.id,+ });+ }}+ >+ <Tooltip placement="bottom" title={localeService.t('hyperLink.popup.cancel')}>+ <UnlinkSingle />+ </Tooltip>+ </div>+ </div>+ </div>+ );+};++CellLinkPopup.componentKey = 'univer.sheet.cell-link-popup';diff --git a/packages/sheets-hyper-link-ui/src/vite-env.d.ts b/packages/sheets-hyper-link-ui/src/vite-env.d.tsnew file mode 100644index 0000000000..11f02fe2a0--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/packages/sheets-hyper-link-ui/tsconfig.json b/packages/sheets-hyper-link-ui/tsconfig.jsonnew file mode 100644index 0000000000..d676ad2a20--- /dev/null+++ b/packages/sheets-hyper-link-ui/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [{ "path": "./tsconfig.node.json" }],+ "include": ["src"]+}diff --git a/packages/sheets-hyper-link-ui/tsconfig.node.json b/packages/sheets-hyper-link-ui/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages/sheets-hyper-link-ui/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages/sheets-hyper-link-ui/vite.config.ts b/packages/sheets-hyper-link-ui/vite.config.tsnew file mode 100644index 0000000000..e38cd8530b--- /dev/null+++ b/packages/sheets-hyper-link-ui/vite.config.ts@@ -0,0 +1,12 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+ features: {+ react: true,+ css: true,+ dom: true,+ },+});diff --git a/packages/sheets-hyper-link/README.md b/packages/sheets-hyper-link/README.mdnew file mode 100644index 0000000000..dbe4144be3--- /dev/null+++ b/packages/sheets-hyper-link/README.md@@ -0,0 +1,19 @@+# @univerjs/sheets-hyper-link++[](https://npmjs.org/packages/@univerjs/hyper-link)+[](https://img.shields.io/npm/l/@univerjs/hyper-link)++## Introduction++A internal package for `@univerjs/sheets-hyper-link-ui`, for using hyper-link feature please refer to [`@univerjs/sheets-hyper-link-ui`](../sheets-hyper-link-ui//README.md).++为 `@univerjs/sheets-hyper-link-ui` 准备的内部包, 如需使用链接功能请查看+[`@univerjs/sheets-hyper-link-ui`](../sheets-hyper-link-ui//README-zh.md)。++## Usage++### Installation++```shell+npm i @univerjs/sheets-hyper-link+```diff --git a/packages/sheets-hyper-link/package.json b/packages/sheets-hyper-link/package.jsonnew file mode 100644index 0000000000..d30599aa5a--- /dev/null+++ b/packages/sheets-hyper-link/package.json@@ -0,0 +1,77 @@+{+ "name": "@univerjs/sheets-hyper-link",+ "version": "0.0.1",+ "private": true,+ "description": "",+ "author": "DreamNum <[email protected]>",+ "license": "Apache-2.0",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/univer"+ },+ "homepage": "https://univer.ai",+ "repository": {+ "type": "git",+ "url": "https://github.com/dream-num/univer"+ },+ "bugs": {+ "url": "https://github.com/dream-num/univer/issues"+ },+ "keywords": [],+ "exports": {+ ".": "./src/index.ts",+ "./*": "./src/*"+ },+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "types": "./lib/types/index.d.ts",+ "publishConfig": {+ "access": "public",+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "exports": {+ ".": {+ "import": "./lib/es/index.js",+ "require": "./lib/cjs/index.js",+ "types": "./lib/types/index.d.ts"+ },+ "./*": {+ "import": "./lib/es/*",+ "require": "./lib/cjs/*",+ "types": "./lib/types/index.d.ts"+ },+ "./lib/*": "./lib/*"+ }+ },+ "directories": {+ "lib": "lib"+ },+ "files": [+ "lib"+ ],+ "scripts": {+ "test": "vitest run",+ "test:watch": "vitest",+ "coverage": "vitest run --coverage",+ "lint:types": "tsc --noEmit",+ "build": "tsc && vite build"+ },+ "peerDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/sheets": "workspace:*",+ "@wendellhu/redi": "0.15.2",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {},+ "devDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/protocol": "^0.1.32",+ "@univerjs/shared": "workspace:*",+ "@univerjs/sheets": "workspace:*",+ "@wendellhu/redi": "^0.15.2",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.2.11",+ "vitest": "^1.6.0"+ }+}diff --git a/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.tsnew file mode 100644index 0000000000..d566edb4f9--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts@@ -0,0 +1,69 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IMutationInfo } from '@univerjs/core';+import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';+import { SheetInterceptorService } from '@univerjs/sheets';+import type { ICellHyperLink } from '../../types/interfaces/i-hyper-link';+import { AddHyperLinkMutation } from '../mutations/add-hyper-link.mutation';+import { RemoveHyperLinkMutation } from '../mutations/remove-hyper-link.mutation';++export interface IAddHyperLinkCommandParams {+ unitId: string;+ subUnitId: string;+ link: ICellHyperLink;+}++export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {+ type: CommandType.COMMAND,+ id: 'sheets.command.add-hyper-link',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const sheetInterceptorService = accessor.get(SheetInterceptorService);+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const { unitId, subUnitId, link } = params;+ const { redos, undos } = sheetInterceptorService.onCommandExecute({+ id: AddHyperLinkCommand.id,+ params,+ });+ const redo: IMutationInfo = {+ id: AddHyperLinkMutation.id,+ params,+ };+ const undo: IMutationInfo = {+ id: RemoveHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id: link.id,+ },+ };+ const res = await sequenceExecuteAsync([redo, ...redos], commandService);+ if (res.result) {+ undoRedoService.pushUndoRedo({+ redoMutations: [redo, ...redos],+ undoMutations: [undo, ...undos],+ unitID: unitId,+ });+ return true;+ }++ return false;+ },+};diff --git a/packages/sheets-hyper-link/src/commands/commands/remove-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/remove-hyper-link.command.tsnew file mode 100644index 0000000000..302bb8d98f--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/commands/remove-hyper-link.command.ts@@ -0,0 +1,114 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IMutationInfo } from '@univerjs/core';+import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';+import { SheetInterceptorService } from '@univerjs/sheets';+import type { IAddHyperLinkMutationParams } from '../mutations/add-hyper-link.mutation';+import { AddHyperLinkMutation } from '../mutations/add-hyper-link.mutation';+import { RemoveHyperLinkMutation } from '../mutations/remove-hyper-link.mutation';+import { HyperLinkModel } from '../../models/hyper-link.model';++export interface IRemoveHyperLinkCommandParams {+ unitId: string;+ subUnitId: string;+ id: string;+}++export const RemoveHyperLinkCommand: ICommand<IRemoveHyperLinkCommandParams> = {+ type: CommandType.COMMAND,+ id: 'sheets.command.remove-hyper-link',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const sheetInterceptorService = accessor.get(SheetInterceptorService);+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, id } = params;+ const link = model.getHyperLink(unitId, subUnitId, id);+ const { redos, undos } = sheetInterceptorService.onCommandExecute({+ id: RemoveHyperLinkCommand.id,+ params,+ });++ const redo: IMutationInfo = {+ id: RemoveHyperLinkMutation.id,+ params,+ };+ const undo: IMutationInfo = {+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ } as IAddHyperLinkMutationParams,+ };++ const res = await sequenceExecuteAsync([redo, ...redos], commandService);+ if (res.result) {+ undoRedoService.pushUndoRedo({+ redoMutations: [redo, ...redos],+ undoMutations: [undo, ...undos],+ unitID: unitId,+ });+ return true;+ }++ return false;+ },+};++export const CancelHyperLinkCommand: ICommand<IRemoveHyperLinkCommandParams> = {+ type: CommandType.COMMAND,+ id: 'sheets.command.cancel-hyper-link',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, id } = params;+ const link = model.getHyperLink(unitId, subUnitId, id);++ const redo: IMutationInfo = {+ id: RemoveHyperLinkMutation.id,+ params,+ };+ const undo: IMutationInfo = {+ id: AddHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ link,+ } as IAddHyperLinkMutationParams,+ };++ const res = await sequenceExecuteAsync([redo], commandService);+ if (res.result) {+ undoRedoService.pushUndoRedo({+ redoMutations: [redo],+ undoMutations: [undo],+ unitID: unitId,+ });+ return true;+ }++ return false;+ },+};diff --git a/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.tsnew file mode 100644index 0000000000..0a00cc36c3--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts@@ -0,0 +1,82 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IMutationInfo } from '@univerjs/core';+import { CommandType, ICommandService, IUndoRedoService, sequenceExecuteAsync } from '@univerjs/core';+import { SheetInterceptorService } from '@univerjs/sheets';+import { HyperLinkModel } from '../../models/hyper-link.model';+import { UpdateHyperLinkMutation } from '../mutations/update-hyper-link.mutation';+import type { ICellHyperLink, ICellLinkContent } from '../../types/interfaces/i-hyper-link';++export interface IUpdateHyperLinkCommandParams {+ unitId: string;+ subUnitId: string;+ id: string;+ payload: ICellLinkContent;+}++function getHyperLinkContent(link: ICellHyperLink) {+ const { row, column, id, ...content } = link;+ return content;+}++export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {+ type: CommandType.COMMAND,+ id: 'sheets.command.update-hyper-link',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const sheetInterceptorService = accessor.get(SheetInterceptorService);+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, id } = params;+ const link = model.getHyperLink(unitId, subUnitId, id);+ if (!link) {+ return false;+ }+ const { redos, undos } = sheetInterceptorService.onCommandExecute({+ id: UpdateHyperLinkCommand.id,+ params,+ });+ const redo: IMutationInfo = {+ id: UpdateHyperLinkMutation.id,+ params,+ };+ const undo: IMutationInfo = {+ id: UpdateHyperLinkMutation.id,+ params: {+ unitId,+ subUnitId,+ id,+ payload: getHyperLinkContent(link),+ },+ };++ const res = await sequenceExecuteAsync([redo, ...redos], commandService);+ if (res.result) {+ undoRedoService.pushUndoRedo({+ redoMutations: [redo, ...redos],+ undoMutations: [undo, ...undos],+ unitID: unitId,+ });+ return true;+ }++ return false;+ },+};diff --git a/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts b/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.tsnew file mode 100644index 0000000000..1f53ac328e--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/mutations/add-hyper-link.mutation.ts@@ -0,0 +1,40 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import { HyperLinkModel } from '../../models/hyper-link.model';+import type { ICellHyperLink } from '../../types/interfaces/i-hyper-link';++export interface IAddHyperLinkMutationParams {+ unitId: string;+ subUnitId: string;+ link: ICellHyperLink;+}++export const AddHyperLinkMutation: ICommand<IAddHyperLinkMutationParams> = {+ type: CommandType.MUTATION,+ id: 'sheets.mutation.add-hyper-link',+ handler(accessor, params) {+ if (!params) {+ return false;+ }++ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, link } = params;+ return model.addHyperLink(unitId, subUnitId, link);+ },+};diff --git a/packages/sheets-hyper-link/src/commands/mutations/remove-hyper-link.mutation.ts b/packages/sheets-hyper-link/src/commands/mutations/remove-hyper-link.mutation.tsnew file mode 100644index 0000000000..2a93981fbf--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/mutations/remove-hyper-link.mutation.ts@@ -0,0 +1,39 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import { HyperLinkModel } from '../../models/hyper-link.model';++export interface IRemoveHyperLinkMutationParams {+ unitId: string;+ subUnitId: string;+ id: string;+}++export const RemoveHyperLinkMutation: ICommand<IRemoveHyperLinkMutationParams> = {+ type: CommandType.MUTATION,+ id: 'sheets.mutation.remove-hyper-link',+ handler(accessor, params) {+ if (!params) {+ return false;+ }++ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, id } = params;+ return model.removeHyperLink(unitId, subUnitId, id);+ },+};diff --git a/packages/sheets-hyper-link/src/commands/mutations/update-hyper-link.mutation.ts b/packages/sheets-hyper-link/src/commands/mutations/update-hyper-link.mutation.tsnew file mode 100644index 0000000000..6725d241a8--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/mutations/update-hyper-link.mutation.ts@@ -0,0 +1,63 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import { HyperLinkModel } from '../../models/hyper-link.model';+import type { ICellLinkContent } from '../../types/interfaces/i-hyper-link';++export interface IUpdateHyperLinkMutationParams {+ unitId: string;+ subUnitId: string;+ id: string;+ payload: ICellLinkContent;+}++export const UpdateHyperLinkMutation: ICommand<IUpdateHyperLinkMutationParams> = {+ type: CommandType.MUTATION,+ id: 'sheets.mutation.update-hyper-link',+ handler(accessor, params) {+ if (!params) {+ return false;+ }++ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, payload, id } = params;+ return model.updateHyperLink(unitId, subUnitId, id, payload);+ },+};++export interface IUpdateHyperLinkRefMutationParams {+ unitId: string;+ subUnitId: string;+ id: string;+ row: number;+ column: number;+}++export const UpdateHyperLinkRefMutation: ICommand<IUpdateHyperLinkRefMutationParams> = {+ type: CommandType.MUTATION,+ id: 'sheets.mutation.update-hyper-link-ref',+ handler(accessor, params) {+ if (!params) {+ return false;+ }++ const model = accessor.get(HyperLinkModel);+ const { unitId, subUnitId, id, row, column } = params;+ return model.updateHyperLinkRef(unitId, subUnitId, id, { row, column });+ },+};diff --git a/packages/sheets-hyper-link/src/controllers/sheet-hyper-link-resource.controller.ts b/packages/sheets-hyper-link/src/controllers/sheet-hyper-link-resource.controller.tsnew file mode 100644index 0000000000..75996b3e73--- /dev/null+++ b/packages/sheets-hyper-link/src/controllers/sheet-hyper-link-resource.controller.ts@@ -0,0 +1,80 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, IResourceManagerService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import { UniverType } from '@univerjs/protocol';+import { HyperLinkModel } from '../models/hyper-link.model';+import type { ICellHyperLink } from '../types/interfaces/i-hyper-link';+import { SHEET_HYPER_LINK_PLUGIN } from '../types/const';++type UnitHyperLinkJSON = Record<string, ICellHyperLink[]>;++@OnLifecycle(LifecycleStages.Starting, SheetsHyperLinkResourceController)+export class SheetsHyperLinkResourceController extends Disposable {+ constructor(+ @IResourceManagerService private readonly _resourceManagerService: IResourceManagerService,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel+ ) {+ super();+ this._initSnapshot();+ }++ private _initSnapshot() {+ const toJson = (unitID: string) => {+ const map = this._hyperLinkModel.getUnit(unitID);+ const resultMap: UnitHyperLinkJSON = {};+ if (map) {+ map.forEach((info) => {+ resultMap[info.subUnitId] = info.links;+ });++ return JSON.stringify(resultMap);+ }+ return '';+ };+ const parseJson = (json: string): UnitHyperLinkJSON => {+ if (!json) {+ return {};+ }+ try {+ return JSON.parse(json);+ } catch (err) {+ return {};+ }+ };++ this.disposeWithMe(+ this._resourceManagerService.registerPluginResource({+ pluginName: SHEET_HYPER_LINK_PLUGIN,+ businesses: [UniverType.UNIVER_SHEET],+ toJson: (unitID) => toJson(unitID),+ parseJson: (json) => parseJson(json),+ onUnLoad: (unitID) => {+ this._hyperLinkModel.deleteUnit(unitID);+ },+ onLoad: async (unitID, value) => {+ Object.keys(value).forEach((subunitId) => {+ const linkList = value[subunitId];+ linkList.forEach((link) => {+ this._hyperLinkModel.addHyperLink(unitID, subunitId, link);+ });+ });+ },+ })+ );+ }+}diff --git a/packages/sheets-hyper-link/src/controllers/sheet-hyper-link.controller.ts b/packages/sheets-hyper-link/src/controllers/sheet-hyper-link.controller.tsnew file mode 100644index 0000000000..fed7810666--- /dev/null+++ b/packages/sheets-hyper-link/src/controllers/sheet-hyper-link.controller.ts@@ -0,0 +1,50 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { AddHyperLinkMutation } from '../commands/mutations/add-hyper-link.mutation';+import { UpdateHyperLinkMutation, UpdateHyperLinkRefMutation } from '../commands/mutations/update-hyper-link.mutation';+import { RemoveHyperLinkMutation } from '../commands/mutations/remove-hyper-link.mutation';+import { AddHyperLinkCommand } from '../commands/commands/add-hyper-link.command';+import { UpdateHyperLinkCommand } from '../commands/commands/update-hyper-link.command';+import { CancelHyperLinkCommand, RemoveHyperLinkCommand } from '../commands/commands/remove-hyper-link.command';++@OnLifecycle(LifecycleStages.Starting, SheetsHyperLinkController)+export class SheetsHyperLinkController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService+ ) {+ super();++ this._registerCommands();+ }++ private _registerCommands() {+ [+ AddHyperLinkMutation,+ UpdateHyperLinkMutation,+ RemoveHyperLinkMutation,+ UpdateHyperLinkRefMutation,++ AddHyperLinkCommand,+ UpdateHyperLinkCommand,+ RemoveHyperLinkCommand,+ CancelHyperLinkCommand,+ ].forEach((command) => {+ this._commandService.registerCommand(command);+ });+ }+}diff --git a/packages/sheets-hyper-link/src/index.ts b/packages/sheets-hyper-link/src/index.tsnew file mode 100644index 0000000000..efc5fe03d3--- /dev/null+++ b/packages/sheets-hyper-link/src/index.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.+ */++export { CancelHyperLinkCommand } from './commands/commands/remove-hyper-link.command';+export { AddHyperLinkMutation, type IAddHyperLinkMutationParams } from './commands/mutations/add-hyper-link.mutation';+export { UpdateHyperLinkMutation, UpdateHyperLinkRefMutation, type IUpdateHyperLinkMutationParams, type IUpdateHyperLinkRefMutationParams } from './commands/mutations/update-hyper-link.mutation';+export { RemoveHyperLinkMutation, type IRemoveHyperLinkMutationParams } from './commands/mutations/remove-hyper-link.mutation';++export { AddHyperLinkCommand, type IAddHyperLinkCommandParams } from './commands/commands/add-hyper-link.command';+export { UpdateHyperLinkCommand, type IUpdateHyperLinkCommandParams } from './commands/commands/update-hyper-link.command';+export { RemoveHyperLinkCommand, type IRemoveHyperLinkCommandParams } from './commands/commands/remove-hyper-link.command';++export { HyperLinkModel } from './models/hyper-link.model';+export { SheetsHyperLinkController } from './controllers/sheet-hyper-link.controller';+export { HyperLinkType } from './types/enums/hyper-link-type';+export { UniverSheetsHyperLinkPlugin } from './plugin';+export type { ICellHyperLink, ICellLinkContent } from './types/interfaces/i-hyper-link';diff --git a/packages/sheets-hyper-link/src/models/hyper-link.model.ts b/packages/sheets-hyper-link/src/models/hyper-link.model.tsnew file mode 100644index 0000000000..1206276804--- /dev/null+++ b/packages/sheets-hyper-link/src/models/hyper-link.model.ts@@ -0,0 +1,247 @@+/**+ * 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 { Subject } from 'rxjs';+import { Disposable, ObjectMatrix } from '@univerjs/core';+import type { ICellHyperLink, ICellLinkContent } from '../types/interfaces/i-hyper-link';++type LinkUpdate = {+ type: 'add';+ payload: ICellHyperLink;+ unitId: string;+ subUnitId: string;+} | {+ type: 'remove';+ payload: ICellHyperLink;+ unitId: string;+ subUnitId: string;+} | {+ type: 'update';+ unitId: string;+ subUnitId: string;+ payload: ICellLinkContent;+ id: string;+} | {+ type: 'updateRef';+ unitId: string;+ subUnitId: string;+ id: string;+ payload: { row: number; column: number };+} | {+ type: 'unload';+ unitId: string;+ unitLinks: {+ unitId: string;+ subUnitId: string;+ links: ICellHyperLink[];+ }[];+};++export class HyperLinkModel extends Disposable {+ private _linkUpdate$ = new Subject<LinkUpdate>();+ linkUpdate$ = this._linkUpdate$.asObservable();++ private _linkMap: Map<string, Map<string, ObjectMatrix<ICellHyperLink>>> = new Map();+ private _linkPositionMap: Map<string, Map<string, Map<string, { row: number; column: number; link: ICellHyperLink }>>> = new Map();++ constructor() {+ super();+ this.disposeWithMe({+ dispose: () => {+ this._linkUpdate$.complete();+ },+ });+ }++ private _ensureMap(unitId: string, subUnitId: string) {+ let unitMap = this._linkMap.get(unitId);++ if (!unitMap) {+ unitMap = new Map();+ this._linkMap.set(unitId, unitMap);+ }+ let matrix = unitMap.get(subUnitId);+ if (!matrix) {+ matrix = new ObjectMatrix();+ unitMap.set(subUnitId, matrix);+ }++ let positionUnitMap = this._linkPositionMap.get(unitId);+ if (!positionUnitMap) {+ positionUnitMap = new Map();+ this._linkPositionMap.set(unitId, positionUnitMap);+ }++ let positionSubUnitMap = positionUnitMap.get(subUnitId);+ if (!positionSubUnitMap) {+ positionSubUnitMap = new Map();+ positionUnitMap.set(subUnitId, positionSubUnitMap);+ }+ return {+ matrix,+ positionMap: positionSubUnitMap,+ };+ }++ addHyperLink(unitId: string, subUnitId: string, link: ICellHyperLink) {+ const { matrix, positionMap } = this._ensureMap(unitId, subUnitId);+ matrix.setValue(link.row, link.column, link);+ positionMap.set(link.id, { row: link.row, column: link.column, link });+ this._linkUpdate$.next({+ unitId,+ subUnitId,+ payload: link,+ type: 'add',+ });+ return true;+ }++ updateHyperLink(unitId: string, subUnitId: string, id: string, payload: Partial<ICellLinkContent>, silent?: boolean) {+ const { matrix, positionMap } = this._ensureMap(unitId, subUnitId);+ // const current = matrix.getValue();+ const position = positionMap.get(id);+ if (!position) {+ return false;+ }+ const link = matrix.getValue(position.row, position.column);+ if (!link) {+ return false;+ }+ Object.assign(link, payload);+ if (!silent) {+ this._linkUpdate$.next({+ unitId,+ subUnitId,+ payload: {+ display: link.display,+ payload: link.payload,+ },+ id,+ type: 'update',+ });+ }+ return true;+ }++ updateHyperLinkRef(unitId: string, subUnitId: string, id: string, payload: { row: number; column: number }) {+ const { matrix, positionMap } = this._ensureMap(unitId, subUnitId);+ // const current = matrix.getValue();+ const position = positionMap.get(id);+ if (!position) {+ return false;+ }++ let link = matrix.getValue(position.row, position.column);+ if (!link || link.id !== id) {+ link = position.link;+ } else {+ matrix.realDeleteValue(position.row, position.column);+ }+ Object.assign(link, payload);+ positionMap.set(id, { ...payload, link });+ matrix.setValue(payload.row, payload.column, link);+ this._linkUpdate$.next({+ unitId,+ subUnitId,+ payload,+ id,+ type: 'updateRef',+ });+ return true;+ }++ removeHyperLink(unitId: string, subUnitId: string, id: string) {+ const { matrix, positionMap } = this._ensureMap(unitId, subUnitId);+ const position = positionMap.get(id);+ if (!position) {+ return false;+ }+ positionMap.delete(id);+ const link = matrix.getValue(position.row, position.column);+ if (link && link.id === id) {+ matrix.realDeleteValue(position.row, position.column);+ }++ this._linkUpdate$.next({+ unitId,+ subUnitId,+ payload: link,+ type: 'remove',+ });+ return true;+ }++ getHyperLink(unitId: string, subUnitId: string, id: string) {+ const { matrix, positionMap } = this._ensureMap(unitId, subUnitId);+ const position = positionMap.get(id);+ if (!position) {+ return undefined;+ }+ return matrix.getValue(position.row, position.column);+ }++ getHyperLinkByLocation(unitId: string, subUnitId: string, row: number, column: number): ICellHyperLink | undefined {+ const { matrix } = this._ensureMap(unitId, subUnitId);++ return matrix.getValue(row, column);+ }++ getSubUnit(unitId: string, subUnitId: string) {+ const { matrix } = this._ensureMap(unitId, subUnitId);++ const links: ICellHyperLink[] = [];+ matrix.forValue((row, col, value) => {+ if (value) {+ links.push(value);+ }+ });++ return links;+ }++ getUnit(unitId: string) {+ const unitMap = this._linkMap.get(unitId);+ if (!unitMap) {+ return [];+ }++ return Array.from(unitMap.keys()).map((subUnitId) => {+ const links = this.getSubUnit(unitId, subUnitId);+ return {+ unitId,+ subUnitId,+ links,+ };+ });+ }++ deleteUnit(unitId: string) {+ const links = this.getUnit(unitId);+ this._linkMap.delete(unitId);+ this._linkPositionMap.delete(unitId);++ this._linkUpdate$.next({+ type: 'unload',+ unitId,+ unitLinks: links,+ });+ }++ getAll() {+ const unitIds = Array.from(this._linkMap.keys());+ return unitIds.map((unitId) => this.getUnit(unitId));+ }+}diff --git a/packages/sheets-hyper-link/src/plugin.ts b/packages/sheets-hyper-link/src/plugin.tsnew file mode 100644index 0000000000..aed422e77b--- /dev/null+++ b/packages/sheets-hyper-link/src/plugin.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Plugin, UniverInstanceType } from '@univerjs/core';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import { 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';++export class UniverSheetsHyperLinkPlugin extends Plugin {+ static override pluginName = SHEET_HYPER_LINK_PLUGIN;+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ config: unknown,+ @Inject(Injector) protected _injector: Injector+ ) {+ super();+ }++ override onStarting(_injector: Injector): void {+ ([+ [SheetsHyperLinkResourceController],+ [SheetsHyperLinkController],+ [HyperLinkModel],+ ] as Dependency[]).forEach((dep) => {+ _injector.add(dep);+ });+ }+}diff --git a/packages/sheets-hyper-link/src/types/const.ts b/packages/sheets-hyper-link/src/types/const.tsnew file mode 100644index 0000000000..b99fdfaa82--- /dev/null+++ b/packages/sheets-hyper-link/src/types/const.ts@@ -0,0 +1,17 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export const SHEET_HYPER_LINK_PLUGIN = 'SHEET_HYPER_LINK_PLUGIN';diff --git a/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts b/packages/sheets-hyper-link/src/types/enums/hyper-link-type.tsnew file mode 100644index 0000000000..461c51e190--- /dev/null+++ b/packages/sheets-hyper-link/src/types/enums/hyper-link-type.ts@@ -0,0 +1,20 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export enum HyperLinkType {+ range = 0,+ link = 1,+}diff --git a/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts b/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.tsnew file mode 100644index 0000000000..e6f12e2748--- /dev/null+++ b/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts@@ -0,0 +1,33 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export interface ICellLinkContent {+ /**+ * #gid=sheet1&range=A1+ * sub sheet: #gid=sheet1+ * namedRange: #rangeid=123+ * http: https://baidu.com+ * file: file://a.xlsx+ */+ payload: string;+ display: string;+}++export interface ICellHyperLink extends ICellLinkContent {+ id: string;+ row: number;+ column: number;+}diff --git a/packages/sheets-hyper-link/tsconfig.json b/packages/sheets-hyper-link/tsconfig.jsonnew file mode 100644index 0000000000..d676ad2a20--- /dev/null+++ b/packages/sheets-hyper-link/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [{ "path": "./tsconfig.node.json" }],+ "include": ["src"]+}diff --git a/packages/sheets-hyper-link/tsconfig.node.json b/packages/sheets-hyper-link/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages/sheets-hyper-link/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages/sheets-hyper-link/vite.config.ts b/packages/sheets-hyper-link/vite.config.tsnew file mode 100644index 0000000000..e38cd8530b--- /dev/null+++ b/packages/sheets-hyper-link/vite.config.ts@@ -0,0 +1,12 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+ features: {+ react: true,+ css: true,+ dom: true,+ },+});diff --git a/packages/sheets-numfmt/package.json b/packages/sheets-numfmt/package.jsonindex 43fbf50069..147d3c605b 100644--- a/packages/sheets-numfmt/package.json+++ b/packages/sheets-numfmt/package.json@@ -80,7 +80,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52"+ "@univerjs/icons": "^0.1.54"},"devDependencies": {"@types/react": "^18.2.79",diff --git a/packages/sheets-thread-comment/package.json b/packages/sheets-thread-comment/package.jsonindex 202cd70f47..92204b467a 100644--- a/packages/sheets-thread-comment/package.json+++ b/packages/sheets-thread-comment/package.json@@ -72,7 +72,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","@univerjs/thread-comment": "workspace:*","@univerjs/thread-comment-ui": "workspace:*"},diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-hover.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-hover.controller.tsindex fda44e348d..dff71a43ee 100644--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-hover.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-hover.controller.ts@@ -17,6 +17,7 @@import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';import { HoverManagerService } from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';+import { debounceTime } from 'rxjs';import { SheetsThreadCommentPopupService } from '../services/sheets-thread-comment-popup.service';import { SheetsThreadCommentModel } from '../models/sheets-thread-comment.model';@@ -32,31 +33,33 @@ export class SheetsThreadCommentHoverController extends Disposable {}private _initHoverEvent() {- this._hoverManagerService.currentCell$.subscribe((cell) => {- const currentPopup = this._sheetsThreadCommentPopupService.activePopup;- if (cell && ((currentPopup && currentPopup.temp) || !currentPopup)) {- const { location } = cell;- const { unitId, subUnitId, row, col } = location;- const commentId = this._sheetsThreadCommentModel.getByLocation(unitId, subUnitId, row, col);+ this.disposeWithMe(+ this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cell) => {+ const currentPopup = this._sheetsThreadCommentPopupService.activePopup;+ if (cell && ((currentPopup && currentPopup.temp) || !currentPopup)) {+ const { location } = cell;+ const { unitId, subUnitId, row, col } = location;+ const commentId = this._sheetsThreadCommentModel.getByLocation(unitId, subUnitId, row, col);- if (commentId) {- const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);- if (comment && !comment.resolved) {- this._sheetsThreadCommentPopupService.showPopup({- unitId,- subUnitId,- row,- col,- commentId,- temp: true,- });- }- } else {- if (currentPopup) {- this._sheetsThreadCommentPopupService.hidePopup();+ if (commentId) {+ const comment = this._sheetsThreadCommentModel.getComment(unitId, subUnitId, commentId);+ if (comment && !comment.resolved) {+ this._sheetsThreadCommentPopupService.showPopup({+ unitId,+ subUnitId,+ row,+ col,+ commentId,+ temp: true,+ });+ }+ } else {+ if (currentPopup) {+ this._sheetsThreadCommentPopupService.hidePopup();+ }}}- }- });+ })+ );}}diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.tsindex 5dac49f186..cb38246216 100644--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts@@ -39,7 +39,6 @@ import type {import {AddMergeUndoMutationFactory,AddWorksheetMergeMutation,- ClearSelectionContentCommand,getAddMergeMutationRangeByType,InsertColMutation,InsertRowMutation,@@ -707,6 +706,7 @@ export class AutoFillController extends Disposable {}// auto fill entry+ // eslint-disable-next-line max-lines-per-functionprivate _fillData(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) {const undos: IMutationInfo[] = [];const redos: IMutationInfo[] = [];@@ -858,9 +858,9 @@ export class AutoFillController extends Disposable {clearMutationParams);- const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });- redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams }, ...intercepted.redos);- undos.push(...intercepted.undos, { id: SetRangeValuesMutation.id, params: undoClearMutationParams });+ // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });+ redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams });+ undos.push({ id: SetRangeValuesMutation.id, params: undoClearMutationParams });// set range valueconst cellValue = new ObjectMatrix<ICellData>();diff --git a/packages/sheets-ui/src/controllers/hover-render.controller.ts b/packages/sheets-ui/src/controllers/hover-render.controller.tsindex bf8e1fad38..b35d4720c8 100644--- a/packages/sheets-ui/src/controllers/hover-render.controller.ts+++ b/packages/sheets-ui/src/controllers/hover-render.controller.ts@@ -22,6 +22,7 @@ import { Inject } from '@wendellhu/redi';import { HoverManagerService } from '../services/hover-manager.service';import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';+import { ScrollManagerService } from '../services/scroll-manager.service';@OnLifecycle(LifecycleStages.Rendered, HoverRenderController)export class HoverRenderController extends Disposable implements IRenderController {@@ -29,11 +30,13 @@ export class HoverRenderController extends Disposable implements IRenderControllprivate readonly _context: IRenderContext<Workbook>,@IRenderManagerService private _renderManagerService: IRenderManagerService,@Inject(HoverManagerService) private _hoverManagerService: HoverManagerService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService+ @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @Inject(ScrollManagerService) private _scrollManagerService: ScrollManagerService) {super();this._initPointerEvent();+ this._initScrollEvent();}private _initPointerEvent() {@@ -67,4 +70,12 @@ export class HoverRenderController extends Disposable implements IRenderControllhandleSkeletonChange(skeletonParam);}));}++ private _initScrollEvent() {+ this.disposeWithMe(+ this._scrollManagerService.scrollInfo$.subscribe(() => {+ this._hoverManagerService.onScroll();+ })+ );+ }}diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.tsindex 0e7b091a5b..72f408b580 100644--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts@@ -20,6 +20,7 @@ import {Disposable,ICommandService,IUniverInstanceService,+ RANGE_TYPE,toDisposable,} from '@univerjs/core';import type { IRenderContext, IRenderController } from '@univerjs/engine-render';@@ -57,8 +58,23 @@ export class SheetsScrollRenderController extends Disposable implements IRenderC}scrollToRange(range: IRange): boolean {- const { startRow, startColumn } = range;- return this._scrollToCell(startRow, startColumn);+ let { endRow, endColumn, startColumn, startRow } = range;+ const bounding = this._getViewportBounding();+ if (range.rangeType === RANGE_TYPE.ROW) {+ startColumn = 0;+ endColumn = 0;+ } else if (range.rangeType === RANGE_TYPE.COLUMN) {+ startRow = 0;+ endRow = 0;+ }++ if (bounding) {+ const row = bounding.startRow > endRow ? startRow : endRow;+ const col = bounding.startColumn > endColumn ? startColumn : endColumn;+ return this._scrollToCell(row, col);+ } else {+ return this._scrollToCell(startRow, startColumn);+ }}private _init() {diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.tsindex b7ed2cc2a9..5b1bff50ab 100644--- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts+++ b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts@@ -312,7 +312,6 @@ export class AutoFillService extends Disposable implements IAutoFillService {redos.push(...hookRedos);}});-const result = redos.every((m) => this._commandService.syncExecuteCommand(m.id, m.params));if (result) {// add to undo redo servicesdiff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.tsindex 31f13e1242..c3ee3dc7a0 100644--- a/packages/sheets-ui/src/services/hover-manager.service.ts+++ b/packages/sheets-ui/src/services/hover-manager.service.ts@@ -111,11 +111,7 @@ export class HoverManagerService extends Disposable {this._calcActiveCell();}- onScrollStart() {+ onScroll() {this._currentCell$.next(null);}-- onScrollEnd() {- this._calcActiveCell();- }}diff --git a/packages/sheets-zen-editor/package.json b/packages/sheets-zen-editor/package.jsonindex db1e12b78e..5b4cf07cb4 100644--- a/packages/sheets-zen-editor/package.json+++ b/packages/sheets-zen-editor/package.json@@ -80,7 +80,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","@univerjs/sheets": "workspace:*"},"devDependencies": {diff --git a/packages/sheets/src/commands/utils/handle-range-mutation.ts b/packages/sheets/src/commands/utils/handle-range-mutation.tsindex fc5cb5d4ae..981304989e 100644--- a/packages/sheets/src/commands/utils/handle-range-mutation.ts+++ b/packages/sheets/src/commands/utils/handle-range-mutation.ts@@ -179,6 +179,7 @@ export function getInsertRangeMutations(accessor: IAccessor, params: IInsertRang};}+// eslint-disable-next-line max-lines-per-functionexport function getRemoveRangeMutations(accessor: IAccessor, params: IDeleteRangeMutationParams) {const redo: IMutationInfo[] = [];const undo: IMutationInfo[] = [];diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.tsindex c79100137b..b27eee8440 100644--- a/packages/sheets/src/services/ref-range/ref-range.service.ts+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts@@ -55,7 +55,8 @@ class WatchRange extends Disposable {private readonly _unitId: string,private readonly _subUnitId: string,private _range: Nullable<IRange>,- private readonly _callback: WatchRangeCallback+ private readonly _callback: WatchRangeCallback,+ private readonly _skipIntersects: boolean = false) {super();}@@ -106,7 +107,7 @@ export class RefRangeService extends Disposable {});}- watchRange(unitId: string, subUnitId: string, range: IRange, callback: WatchRangeCallback): IDisposable {+ watchRange(unitId: string, subUnitId: string, range: IRange, callback: WatchRangeCallback, skipIntersects?: boolean): IDisposable {let watchRangesListener: Nullable<IDisposable>;if (this._watchRanges.size === 0) {watchRangesListener = this._commandService.onCommandExecuted((command) => {@@ -118,7 +119,7 @@ export class RefRangeService extends Disposable {});}- const watchRange = new WatchRange(unitId, subUnitId, range, callback);+ const watchRange = new WatchRange(unitId, subUnitId, range, callback, skipIntersects);this._watchRanges.add(watchRange);const teardownWatching = toDisposable(() => {@@ -142,12 +143,15 @@ export class RefRangeService extends Disposable {private _serializer = createRangeSerializer();+ // eslint-disable-next-line max-lines-per-functionprivate _onRefRangeChange = () => {this._sheetInterceptorService.interceptCommand({+ // eslint-disable-next-line max-lines-per-functiongetMutations: (command: EffectRefRangeParams) => {const worksheet = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();const unitId = getUnitId(this._univerInstanceService);const subUnitId = getSubUnitId(this._univerInstanceService);+ // eslint-disable-next-line max-lines-per-functionconst getEffectsCbList = () => {switch (command.id) {case EffectRefRangId.MoveColsCommandId: {@@ -306,9 +310,17 @@ export class RefRangeService extends Disposable {keyList.forEach((key) => {const cbList = manager.get(key);+const range = this._serializer.deserialize(key);+ const realRange: IRange = {+ ...range,+ startRow: +range.startRow,+ endRow: +range.endRow,+ startColumn: +range.startColumn,+ endColumn: +range.endColumn,+ };// Todo@Gggpound : How to reduce this calculation- if (effectRanges.some((item) => Rectangle.intersects(item, range))) {+ if (effectRanges.some((item) => Rectangle.intersects(item, realRange))) {cbList &&cbList.forEach((callback) => {callbackSet.add(callback);diff --git a/packages/sheets/src/services/ref-range/util.ts b/packages/sheets/src/services/ref-range/util.tsindex 4caa79b40c..f89bfe8984 100644--- a/packages/sheets/src/services/ref-range/util.ts+++ b/packages/sheets/src/services/ref-range/util.ts@@ -24,7 +24,9 @@ import { RemoveSheetMutation } from '../../commands/mutations/remove-sheet.mutatimport { RemoveColMutation, RemoveRowMutation } from '../../commands/mutations/remove-row-col.mutation';import { InsertColMutation, InsertRowMutation } from '../../commands/mutations/insert-row-col.mutation';import type { ISheetCommandSharedParams } from '../../commands/utils/interface';+import type { SelectionManagerService } from '../selection-manager.service';import type {+ EffectRefRangeParams,IDeleteRangeMoveLeftCommand,IDeleteRangeMoveUpCommand,IInsertColCommand,@@ -42,11 +44,13 @@ import { EffectRefRangId, OperatorType } from './type';const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;export const handleRangeTypeInput = (range: IRange) => {const _range = { ...range };- if (_range.rangeType === RANGE_TYPE.COLUMN) {+ const isColumn = Number.isNaN(_range.startRow) && Number.isNaN(_range.endRow) && !Number.isNaN(_range.startColumn) && !Number.isNaN(_range.endColumn);+ const isRow = Number.isNaN(_range.startColumn) && Number.isNaN(_range.endColumn) && !Number.isNaN(_range.startRow) && !Number.isNaN(_range.endRow);+ if (_range.rangeType === RANGE_TYPE.COLUMN || isColumn) {_range.startRow = 0;_range.endRow = MAX_SAFE_INTEGER;}- if (_range.rangeType === RANGE_TYPE.ROW) {+ if (_range.rangeType === RANGE_TYPE.ROW || isRow) {_range.startColumn = 0;_range.endColumn = MAX_SAFE_INTEGER;}@@ -83,11 +87,18 @@ export const handleRangeTypeOutput = (range: IRange, maxRow: number, maxCol: numexport const rotateRange = (range: IRange): IRange => {// rotate {startRow:2,endRow:3,startCol:3,endCol:10} to// {startRow:3,endRow:10,startCol:2,endRow:3}+ let rangeType = range.rangeType;+ if (range.rangeType === RANGE_TYPE.COLUMN) {+ rangeType = RANGE_TYPE.ROW;+ } else if (range.rangeType === RANGE_TYPE.ROW) {+ rangeType = RANGE_TYPE.COLUMN;+ }return {startRow: range.startColumn,endRow: range.endColumn,startColumn: range.startRow,endColumn: range.endRow,+ rangeType,};};interface ILine {@@ -1033,3 +1044,168 @@ export function adjustRangeOnMutation(range: Readonly<IRange>, mutation: IMutatireturn range;}}++const MAX_BOUND = Math.floor(Number.MAX_SAFE_INTEGER / 10);++// eslint-disable-next-line max-lines-per-function+export function getEffectedRangesOnCommand(command: EffectRefRangeParams, deps: { selectionManagerService: SelectionManagerService }) {+ const { selectionManagerService } = deps;+ switch (command.id) {+ case EffectRefRangId.MoveColsCommandId: {+ const params = command.params!;+ const startColumn = Math.min(params.fromRange.startColumn, params.toRange.startColumn);+ return [{ ...params.fromRange, startColumn, endColumn: MAX_BOUND }];+ }+ case EffectRefRangId.MoveRowsCommandId: {+ const params = command.params!;+ const startRow = Math.min(params.fromRange.startRow, params.toRange.startRow);++ return [{ ...params.fromRange, startRow, endRow: MAX_BOUND }];+ }+ case EffectRefRangId.MoveRangeCommandId: {+ const params = command;+ return [params.params!.fromRange, params.params!.toRange];+ }+ case EffectRefRangId.InsertRowCommandId: {+ const params = command;+ const rowStart = params.params!.range.startRow;+ const range: IRange = {+ startRow: rowStart,+ endRow: MAX_BOUND,+ startColumn: 0,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case EffectRefRangId.InsertColCommandId: {+ const params = command;+ const colStart = params.params!.range.startColumn;+ const range: IRange = {+ startRow: 0,+ endRow: MAX_BOUND,+ startColumn: colStart,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case EffectRefRangId.RemoveRowCommandId: {+ const params = command;++ const rowStart = params.params!.range.startRow;+ const range: IRange = {+ startRow: rowStart,+ endRow: MAX_BOUND,+ startColumn: 0,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case EffectRefRangId.RemoveColCommandId: {+ const params = command;+ const colStart = params.params!.range.startColumn;+ const range: IRange = {+ startRow: 0,+ endRow: MAX_BOUND,+ startColumn: colStart,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case EffectRefRangId.DeleteRangeMoveUpCommandId:+ case EffectRefRangId.InsertRangeMoveDownCommandId: {+ const params = command;+ const range = params.params?.range || selectionManagerService.getSelectionRanges()?.[0];+ if (!range) {+ return [];+ }+ const effectRange = {+ startRow: range.startRow,+ startColumn: range.startColumn,+ endColumn: range.endColumn,+ endRow: MAX_BOUND,+ };+ return [effectRange];+ }+ case EffectRefRangId.DeleteRangeMoveLeftCommandId:+ case EffectRefRangId.InsertRangeMoveRightCommandId: {+ const params = command;+ const range = params.params?.range || selectionManagerService.getSelectionRanges()?.[0];+ if (!range) {+ return [];+ }+ const effectRange = {+ startRow: range.startRow,+ startColumn: range.startColumn,+ endColumn: MAX_BOUND,+ endRow: range.endRow,+ };+ return [effectRange];+ }+ }+}++export function getEffectedRangesOnMutation(mutation: IMutationInfo<MutationsAffectRange>) {+ switch (mutation.id) {+ case MoveColsMutation.id: {+ const params = mutation.params as IMoveColumnsMutationParams;+ const startColumn = Math.min(params.sourceRange.startColumn, params.targetRange.startColumn);+ return [{ ...params.sourceRange, startColumn, endColumn: MAX_BOUND }];+ }+ case MoveRowsMutation.id: {+ const params = mutation.params as IMoveRowsMutationParams;+ const startRow = Math.min(params.sourceRange.startRow, params.targetRange.startRow);+ return [{ ...params.sourceRange, startRow, endRow: MAX_BOUND }];+ }++ case MoveRangeMutation.id: {+ const params = mutation.params as IMoveRangeMutationParams;+ return [new ObjectMatrix(params.from).getRange(), new ObjectMatrix(params.to).getRange()];+ }+ case InsertColMutation.id: {+ const params = mutation.params as IInsertColMutationParams;+ const colStart = params.range.startColumn;+ const range: IRange = {+ startRow: 0,+ endRow: MAX_BOUND,+ startColumn: colStart,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case InsertRowMutation.id: {+ const params = mutation.params as IInsertRowMutationParams;+ const rowStart = params.range.startRow;+ const range: IRange = {+ startRow: rowStart,+ endRow: MAX_BOUND,+ startColumn: 0,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case RemoveColMutation.id: {+ const params = mutation.params as IRemoveColMutationParams;+ const colStart = params.range.startColumn;+ const range: IRange = {+ startRow: 0,+ endRow: MAX_BOUND,+ startColumn: colStart,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ case RemoveRowMutation.id: {+ const params = mutation.params as IRemoveRowsMutationParams;+ const rowStart = params.range.startRow;+ const range: IRange = {+ startRow: rowStart,+ endRow: MAX_BOUND,+ startColumn: 0,+ endColumn: MAX_BOUND,+ };+ return [range];+ }+ default:+ break;+ }+}diff --git a/packages/thread-comment-ui/package.json b/packages/thread-comment-ui/package.jsonindex de5f832f80..aeae461e97 100644--- a/packages/thread-comment-ui/package.json+++ b/packages/thread-comment-ui/package.json@@ -73,7 +73,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","@univerjs/protocol": "^0.1.34","@univerjs/thread-comment": "workspace:*"},diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 11109e5519..b7f41bf95c 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -79,7 +79,7 @@"rxjs": ">=7.0.0"},"dependencies": {- "@univerjs/icons": "^0.1.52",+ "@univerjs/icons": "^0.1.54","localforage": "^1.10.0","rc-notification": "^5.5.0","rc-util": "^5.39.3"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d5c7b2d25e..df2a1dc6af 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -59,6 +59,9 @@ importers:eslint-plugin-no-barrel-import:specifier: ^0.0.2version: 0.0.2([email protected])+ eslint-plugin-no-penetrating-import:+ specifier: ^0.0.1+ version: 0.0.1([email protected])eslint-plugin-react:specifier: ^7.34.1version: 7.34.1([email protected])@@ -239,7 +242,7 @@ importers:version: link:../packages/find-replace'@univerjs/icons':specifier: ^0.1.52'@univerjs/rpc':specifier: workspace:*version: link:../packages/rpc@@ -270,6 +273,12 @@ importers:'@univerjs/sheets-formula':specifier: workspace:*version: link:../packages/sheets-formula+ '@univerjs/sheets-hyper-link':+ specifier: workspace:*+ version: link:../packages/sheets-hyper-link+ '@univerjs/sheets-hyper-link-ui':+ specifier: workspace:*+ version: link:../packages/sheets-hyper-link-ui'@univerjs/sheets-numfmt':specifier: workspace:*version: link:../packages/sheets-numfmt@@ -489,8 +498,8 @@ importers:specifier: ^4.1.13version: 4.1.13'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54rc-dialog:specifier: ^9.4.0@@ -613,8 +622,8 @@ importers:packages/docs-drawing-ui:dependencies:'@univerjs/icons':- specifier: ^0.1.46+ specifier: ^0.1.54devDependencies:'@univerjs/core':specifier: workspace:*@@ -652,8 +661,11 @@ importers:less:specifier: ^4.2.0version: 4.2.0+ ot-json1:+ specifier: ^1.0.2+ version: 1.0.2react:- specifier: ^18.2.0+ specifier: 18.2.0version: 18.2.0rxjs:specifier: ^7.8.1@@ -720,7 +732,7 @@ importers:version: link:../engine-render'@univerjs/icons':specifier: ^0.1.52ot-json1:specifier: ^1.0.2version: 1.0.2@@ -760,7 +772,7 @@ importers:dependencies:'@univerjs/icons':specifier: ^0.1.52devDependencies:'@univerjs/core':specifier: workspace:*@@ -958,8 +970,8 @@ importers:packages/find-replace:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54devDependencies:'@types/react':specifier: ^18.2.79@@ -1141,8 +1153,8 @@ importers:packages/sheets-conditional-formatting-ui:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54'@univerjs/protocol':specifier: ^0.1.34version: 0.1.34(@grpc/[email protected])([email protected])@@ -1229,8 +1241,8 @@ importers:packages/sheets-data-validation:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54devDependencies:'@univerjs/core':specifier: workspace:*@@ -1378,8 +1390,8 @@ importers:packages/sheets-filter-ui:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54rc-virtual-list:specifier: ^3.11.5@@ -1481,8 +1493,8 @@ importers:packages/sheets-formula:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54devDependencies:'@types/react':specifier: ^18.2.79@@ -1542,11 +1554,99 @@ importers:specifier: ^1.6.0version: 1.6.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ packages/sheets-hyper-link:+ devDependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: link:../core+ '@univerjs/protocol':+ specifier: ^0.1.32+ version: 0.1.34(@grpc/[email protected])([email protected])+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/sheets':+ specifier: workspace:*+ version: link:../sheets+ '@wendellhu/redi':+ specifier: ^0.15.2+ version: 0.15.2+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.4.5+ vite:+ specifier: ^5.2.11+ version: 5.2.11(@types/[email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^1.6.0+ version: 1.6.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ packages/sheets-hyper-link-ui:+ dependencies:+ '@univerjs/design':+ specifier: workspace:*+ version: link:../design+ '@univerjs/sheets-hyper-link':+ specifier: workspace:*+ version: link:../sheets-hyper-link+ react:+ specifier: ^16.9.0 || ^17.0.0 || ^18.0.0+ version: 18.2.0+ devDependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: link:../core+ '@univerjs/engine-formula':+ specifier: workspace:*+ version: link:../engine-formula+ '@univerjs/engine-render':+ specifier: workspace:*+ version: link:../engine-render+ '@univerjs/icons':+ specifier: ^0.1.54+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/sheets':+ specifier: workspace:*+ version: link:../sheets+ '@univerjs/sheets-formula':+ specifier: workspace:*+ version: link:../sheets-formula+ '@univerjs/sheets-ui':+ specifier: workspace:*+ version: link:../sheets-ui+ '@univerjs/ui':+ specifier: workspace:*+ version: link:../ui+ '@wendellhu/redi':+ specifier: ^0.15.2+ version: 0.15.2+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.4.5+ vite:+ specifier: ^5.2.11+ version: 5.2.11(@types/[email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^1.6.0+ version: 1.6.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+packages/sheets-numfmt:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54devDependencies:'@types/react':specifier: ^18.2.79@@ -1685,8 +1785,8 @@ importers:specifier: workspace:*version: link:../engine-render'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54'@univerjs/sheets':specifier: workspace:*version: link:../sheets@@ -1813,8 +1913,8 @@ importers:packages/sheets-zen-editor:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54'@univerjs/sheets':specifier: workspace:*version: link:../sheets@@ -1977,8 +2077,8 @@ importers:packages/thread-comment-ui:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54'@univerjs/protocol':specifier: ^0.1.34version: 0.1.34(@grpc/[email protected])([email protected])@@ -2029,8 +2129,8 @@ importers:packages/ui:dependencies:'@univerjs/icons':- specifier: ^0.1.52+ specifier: ^0.1.54localforage:specifier: ^1.10.0version: 1.10.0@@ -4872,12 +4972,6 @@ packages:react: '*'react-dom: '*'- '@univerjs/[email protected]':- resolution: {integrity: sha512-VDg4jc1yLgNCOCZGLwcmAo5lGy/Jp/2c34QO+fClQzx2Qih6EWqxHyJfdjFILfNwWdJvrlFEIG4zMYtNM1Z2TQ==}- peerDependencies:- react: '*'- react-dom: '*'-'@univerjs/[email protected]':resolution: {integrity: sha512-s82L8pDlOJsx3UJZM/uBhzZp7w/Kg7MiVoLIDS2upowQwkNprlZJNTrVz2nKxwtl2WdMtfLeQIW0f07n9oyChw==}peerDependencies:@@ -6613,6 +6707,12 @@ packages:resolution: {integrity: sha512-Lf4YW/bL6Un1R6A76pRZyE1dl1vr31G/ev8UzIc/geCgFWyrKil8hVjYqWVKGB/UIGmb6Slzs9T0wNezdSVegw==}engines: {node: '>=5.0.0'}+ resolution: {integrity: sha512-uFe2sOCiGM1WB7nrHdv8yr7su8MtJqE3b0x+ayil7UmPqbRXzDr0h2l3OCKv1bz5r2+MiJG5A25fQ+V5Q5qnIg==}+ engines: {node: ^14.17.0 || ^16.0.0 || >= 18.0.0}+ peerDependencies:+ eslint: '>=7'+resolution: {integrity: sha512-P+tdrkHeMWBc55+DZsoDOAftV1WCsEoHaKm6JC7zajFus/syfT4vUPBFb3atGFSuyaVnGQGHlcKpP9X3Q0gH/w==}peerDependencies:@@ -13940,11 +14040,6 @@ snapshots:react: 18.2.0react-dom: 18.2.0([email protected])- dependencies:- react: 18.2.0- react-dom: 18.2.0([email protected])-dependencies:react: 18.2.0@@ -15910,6 +16005,11 @@ snapshots:+ dependencies:+ eslint: 8.57.0+ requireindex: 1.2.0+dependencies:'@typescript-eslint/utils': 7.9.0([email protected])([email protected])