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(uni): init uni mode (#2793)
Wenzhao Hu8228c5a62516
diff --git a/examples/esbuild.config.mjs b/examples/esbuild.config.mjsindex 206ffc9513..4dd75f3927 100644--- a/examples/esbuild.config.mjs+++ b/examples/esbuild.config.mjs@@ -92,6 +92,8 @@ const ctx = await esbuild[args.watch ? 'context' : 'build']({// uni'./src/uni/main.ts',+ './src/uni/worker.ts',+ './src/uni/lazy.ts',// mobile sheet'./src/mobile-s/main.ts',diff --git a/examples/package.json b/examples/package.jsonindex c7749174e0..810a792117 100644--- a/examples/package.json+++ b/examples/package.json@@ -56,7 +56,9 @@"@univerjs/thread-comment": "workspace:*","@univerjs/thread-comment-ui": "workspace:*","@univerjs/ui": "workspace:*",+ "@univerjs/uni-formula": "workspace:*","@univerjs/uniscript": "workspace:*",+ "@univerjs/uniui": "workspace:*","@wendellhu/redi": "0.16.0","clsx": "^2.1.1","monaco-editor": "0.50.0",diff --git a/examples/src/data/sheets/default-workbook-data.ts b/examples/src/data/sheets/default-workbook-data.tsindex 7ade0db68a..a7943c8b3d 100644--- a/examples/src/data/sheets/default-workbook-data.ts+++ b/examples/src/data/sheets/default-workbook-data.ts@@ -243,7 +243,7 @@ const richTextTest: IDocumentData = {* Default workbook data*/export const DEFAULT_WORKBOOK_DATA: IWorkbookData = {- id: 'workbook-01',+ id: 'workbook-left',locale: LocaleType.ZH_CN,name: 'universheet',sheetOrder: ['sheet-01', 'sheet-02', 'sheet-03', 'sheet-04', 'sheet-05', 'sheet-06'],diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo1.ts b/examples/src/data/sheets/demo/default-workbook-data-demo1.tsindex ac7a98ee86..412aea7e51 100644--- a/examples/src/data/sheets/demo/default-workbook-data-demo1.ts+++ b/examples/src/data/sheets/demo/default-workbook-data-demo1.ts@@ -18,7 +18,7 @@ import type { IWorkbookData } from '@univerjs/core';import { BooleanNumber, BorderStyleTypes, LocaleType } from '@univerjs/core';export const DEFAULT_WORKBOOK_DATA_DEMO1: IWorkbookData = {- id: 'workbook-01',+ id: 'workbook-right',locale: LocaleType.ZH_CN,name: 'universheet',sheetOrder: ['sheet-0003'],diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex 7f0616f683..5af8ae88f4 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -16,27 +16,20 @@import type { Nullable } from '@univerjs/core';import { LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';-import { UniverRenderEnginePlugin } from '@univerjs/engine-render';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';-import { defaultTheme } from '@univerjs/design';import { UniverUIPlugin } from '@univerjs/ui';-import { UniverDocsPlugin } from '@univerjs/docs';import { UniverDocsUIPlugin } from '@univerjs/docs-ui';import { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';-import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';-import { UniverDebuggerPlugin } from '@univerjs/debugger';import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';-import type { IThreadCommentMentionDataSource } from '@univerjs/thread-comment-ui';import { IThreadCommentMentionDataService, UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';-import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';@@ -47,6 +40,7 @@ import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';+import { enUS, ruRU, viVN, zhCN, zhTW } from '../locales';import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';/* eslint-disable-next-line node/prefer-global/process */diff --git a/examples/src/uni/lazy.ts b/examples/src/uni/lazy.tsindex f642604d63..f609227f1b 100644--- a/examples/src/uni/lazy.ts+++ b/examples/src/uni/lazy.ts@@ -16,22 +16,22 @@import type { Plugin, PluginCtor } from '@univerjs/core';import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';-import { UniverUniscriptPlugin } from '@univerjs/uniscript';+// import { UniverUniscriptPlugin } from '@univerjs/uniscript';export default function getLazyPlugins(): Array<[PluginCtor<Plugin>] | [PluginCtor<Plugin>, unknown]> {return [- [- UniverUniscriptPlugin,- {- getWorkerUrl(moduleID: string, label: string) {- if (label === 'typescript' || label === 'javascript') {- return './vs/language/typescript/ts.worker.js';- }+ // [+ // UniverUniscriptPlugin,+ // {+ // getWorkerUrl(moduleID: string, label: string) {+ // if (label === 'typescript' || label === 'javascript') {+ // return './vs/language/typescript/ts.worker.js';+ // }- return './vs/editor/editor.worker.js';- },- },- ],+ // return './vs/editor/editor.worker.js';+ // },+ // },+ // ],[UniverSheetsFilterUIPlugin],];}diff --git a/examples/src/uni/main.ts b/examples/src/uni/main.tsindex 05ddd25a71..0071709d2b 100644--- a/examples/src/uni/main.ts+++ b/examples/src/uni/main.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';@@ -24,13 +25,25 @@ import { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';-import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';-import { UniverUIPlugin } from '@univerjs/ui';+import { UniverUniUIPlugin } from '@univerjs/uniui';import { UniverDebuggerPlugin } from '@univerjs/debugger';import { FUniver } from '@univerjs/facade';import { UniverDrawingPlugin } from '@univerjs/drawing';-import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';+import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';+import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';+import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';+import type { IThreadCommentMentionDataSource } from '@univerjs/thread-comment-ui';+import { IThreadCommentMentionDataService, UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';+import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';+import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';+import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';+import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';+import { UniverDocUniFormulaPlugin } from '@univerjs/uni-formula';++import { DEFAULT_DOCUMENT_DATA_CN } from '../data';import { enUS } from '../locales';+import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';/* eslint-disable-next-line node/prefer-global/process */const IS_E2E: boolean = !!process.env.IS_E2E;@@ -50,9 +63,11 @@ const univer = new Univer({univer.registerPlugin(UniverDocsPlugin, {hasScroll: false,});-univer.registerPlugin(UniverFormulaEnginePlugin);+univer.registerPlugin(UniverFormulaEnginePlugin, {+ notExecuteFormula: true,+});univer.registerPlugin(UniverRenderEnginePlugin);-univer.registerPlugin(UniverUIPlugin, {+univer.registerPlugin(UniverUniUIPlugin, {container: 'app',});@@ -64,12 +79,61 @@ univer.registerPlugin(UniverSheetsPlugin);univer.registerPlugin(UniverSheetsUIPlugin);univer.registerPlugin(UniverSheetsNumfmtPlugin);-univer.registerPlugin(UniverSheetsZenEditorPlugin);univer.registerPlugin(UniverSheetsFormulaPlugin);+univer.registerPlugin(UniverRPCMainThreadPlugin, {+ workerURL: './worker.js',+} as IUniverRPCMainThreadConfig);++univer.registerPlugin(UniverSheetsFindReplacePlugin);+univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);+// univer.registerPlugin(UniverSheetsDataValidationPlugin);+univer.registerPlugin(UniverSheetsSortUIPlugin);++univer.registerPlugin(UniverDocUniFormulaPlugin);++const mockUser = {+ userID: 'Owner_qxVnhPbQ',+ name: 'Owner',+ avatar: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAInSURBVHgBtZU9TxtBEIbfWRzFSIdkikhBSqRQkJqkCKTCFkqVInSUSaT0wC8w/gXxD4gU2nRJkXQWhAZowDUUWKIwEgWWbEEB3mVmx3dn4DA2nB/ppNuPeWd29mMIPXDr+RxwtgRHeW6+guNPRxogqnL7Dwz9psJ27S4NShaeZTH3kwXy6I81dlRKcmRui88swdq9AcSFL7Buz1Vmlns64MiLsCjzwnIYHLH57tbfFbs7KRaXyEU8FVZofqccOfA5l7Q8LPIkGrwnb2RPNEXWFVMUF3L+kDCk0btDDAMzOm5YfAHDwp4tG74wnzAsiOYMnJ3GoDybA7IT98/jm5+JNnfiIzAS6LlqHQBN/i6b2t/cV1Hh6BfwYlHnHP4AXi5q/8kmMMpOs8+BixZw/Fd6xUEHEbnkgclvQP2fGp7uShRKnQ3G32rkjV1th8JhIGG7tR/JyjGteSOZELwGMmNqIIigRCLRh2OZIE6BjItdd7pCW6Uhm1zzkUtungSxwEUzNpQ+GQumtH1ej1MqgmNT6vwmhCq5yuwq56EYTbgeQUz3yvrpV1b4ok3nYJ+eYhgYmjRUqErx2EDq0Fr8FhG++iqVGqxlUJI/70Ar0UgJaWHj6hYVHJrfKssAHot1JfqwE9WVWzXZVd5z2Ws/4PnmtEjkXeKJDvxUecLbWOXH/DP6QQ4J72NS0adedp1aseBfXP8odlZFfPvBF7SN/8hky1TYuPOAXAEipMx15u5ToAAAAABJRU5ErkJggg==',+ anonymous: false,+ canBindAnonymous: false,+};++class CustomMentionDataService implements IThreadCommentMentionDataService {+ dataSource: Nullable<IThreadCommentMentionDataSource>;+ trigger: string = '@';++ async getMentions() {+ return [+ {+ id: mockUser.userID,+ label: mockUser.name,+ type: 'user',+ icon: mockUser.avatar,+ },+ {+ id: '2',+ label: 'User2',+ type: 'user',+ icon: mockUser.avatar,+ },+ ];+ }+}++univer.registerPlugin(UniverThreadCommentUIPlugin, {+ overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],+});+univer.registerPlugin(UniverSheetsThreadCommentPlugin);+univer.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);++univer.registerPlugin(UniverSheetsDrawingUIPlugin);// create univer sheet instanceif (!IS_E2E) {univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);+ // univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO1);+ univer.createUnit(UniverInstanceType.UNIVER_DOC, DEFAULT_DOCUMENT_DATA_CN);}// debugger plugindiff --git a/examples/src/uni/worker.ts b/examples/src/uni/worker.tsindex 98f821ce65..c2c0ccb551 100644--- a/examples/src/uni/worker.ts+++ b/examples/src/uni/worker.ts@@ -14,21 +14,19 @@* limitations under the License.*/-import { LocaleType, Univer } from '@univerjs/core';+import { LocaleType, LogLevel, Univer } from '@univerjs/core';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';import { UniverSheetsPlugin } from '@univerjs/sheets';-import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';-// Univer web worker is also a univer application.const univer = new Univer({locale: LocaleType.ZH_CN,+ logLevel: LogLevel.VERBOSE,});univer.registerPlugin(UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true });univer.registerPlugin(UniverFormulaEnginePlugin);univer.registerPlugin(UniverRPCWorkerThreadPlugin);-univer.registerPlugin(UniverSheetsFilterPlugin);declare let self: WorkerGlobalScope & typeof globalThis & { univer: Univer };self.univer = univer;diff --git a/packages-experimental/README.md b/packages-experimental/README.mdnew file mode 100644index 0000000000..269364b78e--- /dev/null+++ b/packages-experimental/README.md@@ -0,0 +1,3 @@+# Experimental Packages++Experimental packages in development. These packages are not meant to be published to npm or used in production.diff --git a/packages-experimental/uni-formula-ui/README.md b/packages-experimental/uni-formula-ui/README.mdnew file mode 100644index 0000000000..953e36f3d2--- /dev/null+++ b/packages-experimental/uni-formula-ui/README.md@@ -0,0 +1,16 @@+# @univerjs/uni-formula-ui++[](https://npmjs.org/packages/@univerjs/uni-formula-ui)+[](https://img.shields.io/npm/l/@univerjs/uni-formula-ui)++## Introduction++> TODO: Introduction++## Usage++### Installation++```shell+npm i @univerjs/uni-formula-ui+```diff --git a/packages-experimental/uni-formula-ui/package.json b/packages-experimental/uni-formula-ui/package.jsonnew file mode 100644index 0000000000..524785114b--- /dev/null+++ b/packages-experimental/uni-formula-ui/package.json@@ -0,0 +1,76 @@+{+ "name": "@univerjs/uni-formula-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/uni-formula": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {},+ "devDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/shared": "workspace:*",+ "@univerjs/uni-formula": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.3.4",+ "vitest": "^2.0.3"+ }+}diff --git a/packages-experimental/uni-formula-ui/src/const.ts b/packages-experimental/uni-formula-ui/src/const.tsnew file mode 100644index 0000000000..4071a01e10--- /dev/null+++ b/packages-experimental/uni-formula-ui/src/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 DOC_FORMULA_UI_PLUGIN_NAME = 'DOC_FORMULA_UI_PLUGIN';diff --git a/packages-experimental/uni-formula-ui/src/index.ts b/packages-experimental/uni-formula-ui/src/index.tsnew file mode 100644index 0000000000..64ff0daf1c--- /dev/null+++ b/packages-experimental/uni-formula-ui/src/index.ts@@ -0,0 +1,17 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export { UniverDocUniFormulaUIPlugin } from './uni-formula-ui.plugin';diff --git a/packages-experimental/uni-formula-ui/src/uni-formula-ui.plugin.ts b/packages-experimental/uni-formula-ui/src/uni-formula-ui.plugin.tsnew file mode 100644index 0000000000..a71a108153--- /dev/null+++ b/packages-experimental/uni-formula-ui/src/uni-formula-ui.plugin.ts@@ -0,0 +1,36 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';+import { UniverDocUniFormulaPlugin } from '@univerjs/uni-formula';+import { DOC_FORMULA_UI_PLUGIN_NAME } from './const';++@DependentOn(UniverDocUniFormulaPlugin)+export class UniverDocUniFormulaUIPlugin extends Plugin {+ static override pluginName: string = DOC_FORMULA_UI_PLUGIN_NAME;+ static override type: UniverInstanceType = UniverInstanceType.UNIVER_DOC;++ constructor(+ config: unknown,+ @Inject(Injector) protected readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(injector: Injector): void {+ }+}diff --git a/packages-experimental/uni-formula-ui/src/vite-env.d.ts b/packages-experimental/uni-formula-ui/src/vite-env.d.tsnew file mode 100644index 0000000000..11f02fe2a0--- /dev/null+++ b/packages-experimental/uni-formula-ui/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/packages-experimental/uni-formula-ui/tsconfig.json b/packages-experimental/uni-formula-ui/tsconfig.jsonnew file mode 100644index 0000000000..e8df90d34b--- /dev/null+++ b/packages-experimental/uni-formula-ui/tsconfig.json@@ -0,0 +1,15 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [+ {+ "path": "./tsconfig.node.json"+ }+ ],+ "include": [+ "src"+ ]+}diff --git a/packages-experimental/uni-formula-ui/tsconfig.node.json b/packages-experimental/uni-formula-ui/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages-experimental/uni-formula-ui/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages-experimental/uni-formula-ui/vite.config.ts b/packages-experimental/uni-formula-ui/vite.config.tsnew file mode 100644index 0000000000..67b2fff8f2--- /dev/null+++ b/packages-experimental/uni-formula-ui/vite.config.ts@@ -0,0 +1,7 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+});diff --git a/packages-experimental/uni-formula/README.md b/packages-experimental/uni-formula/README.mdnew file mode 100644index 0000000000..d22aa2342d--- /dev/null+++ b/packages-experimental/uni-formula/README.md@@ -0,0 +1,16 @@+# @univerjs/uni-formula++[](https://npmjs.org/packages/@univerjs/uni-formula)+[](https://img.shields.io/npm/l/@univerjs/uni-formula)++## Introduction++Provide formula feature in Univer Docs. Univer Slides would be supported in the future.++## Usage++### Installation++```shell+npm i @univerjs/uni-formula+```diff --git a/packages-experimental/uni-formula/package.json b/packages-experimental/uni-formula/package.jsonnew file mode 100644index 0000000000..2ec7a202da--- /dev/null+++ b/packages-experimental/uni-formula/package.json@@ -0,0 +1,97 @@+{+ "name": "@univerjs/uni-formula",+ "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": [],+ "sideEffects": [+ "**/*.css"+ ],+ "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": {+ "@univerjs/sheets-formula": "workspace:*",+ "lib": "lib"+ },+ "files": [+ "lib"+ ],+ "scripts": {+ "test": "vitest run",+ "test:watch": "vitest",+ "coverage": "vitest run --coverage",+ "lint:types": "tsc --noEmit",+ "build": "tsc && vite build"+ },+ "peerDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/design": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/engine-formula": "workspace:*",+ "@univerjs/rpc": "workspace:*",+ "@univerjs/sheets-formula": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "clsx": ">=2.0.0",+ "react": ">=16.9.0",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {+ "@univerjs/icons": "^0.1.46"+ },+ "devDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/design": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/engine-formula": "workspace:*",+ "@univerjs/rpc": "workspace:*",+ "@univerjs/shared": "workspace:*",+ "@univerjs/sheets-formula": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "clsx": "^2.1.1",+ "less": "^4.2.0",+ "react": "18.2.0",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.3.4",+ "vitest": "^2.0.3"+ }+}diff --git a/packages-experimental/uni-formula/src/commands/command.ts b/packages-experimental/uni-formula/src/commands/command.tsnew file mode 100644index 0000000000..9b940a3979--- /dev/null+++ b/packages-experimental/uni-formula/src/commands/command.ts@@ -0,0 +1,84 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CommandType, CustomRangeType, generateRandomId, type ICommand, ICommandService, type IMutationInfo, sequenceExecute } from '@univerjs/core';+import { addCustomRangeBySelectionFactory } from '@univerjs/docs';++import type { IAddDocUniFormulaMutationParams, IRemoveDocUniFormulaMutationParams, IUpdateDocUniFormulaMutationParams } from './mutation';+import { AddDocUniFormulaMutation, RemoveDocUniFormulaMutation, UpdateDocUniFormulaMutation } from './mutation';++export interface IAddDocUniFormulaCommandParams {+ unitId: string;+ f: string;+}++export const AddDocUniFormulaCommand: ICommand<IAddDocUniFormulaCommandParams> = {+ type: CommandType.COMMAND,+ id: 'doc.command.add-uni-formula',+ async handler(accessor, params: IAddDocUniFormulaCommandParams) {+ const { f, unitId } = params;+ const commandService = accessor.get(ICommandService);+ const rangeId = generateRandomId();+ const redoMutation = addCustomRangeBySelectionFactory(accessor, {+ rangeId,+ rangeType: CustomRangeType.CUSTOM,+ });++ if (redoMutation) {+ const addFormulaResourceMutation: IMutationInfo<IAddDocUniFormulaMutationParams> = {+ id: AddDocUniFormulaMutation.id,+ params: { unitId, rangeId, f },+ };++ return sequenceExecute([addFormulaResourceMutation, redoMutation], commandService).result;+ }++ return false;+ },+};++export interface IUpdateDocUniFormulaCommandParams {+ unitId: string;+ rangeId: string;+ f: string;+}++// TODO: implement update & remove command++export const UpdateDocUniFormulaCommand: ICommand<IUpdateDocUniFormulaCommandParams> = {+ type: CommandType.COMMAND,+ id: 'doc.command.add-uni-formula',+ handler: (accessor, params: IUpdateDocUniFormulaCommandParams) => {+ const commandService = accessor.get(ICommandService);+ return commandService.syncExecuteCommand(UpdateDocUniFormulaMutation.id, params as IUpdateDocUniFormulaMutationParams);+ },+};++export interface IRemoveDocUniFormulaCommandParams {+ unitId: string;+ rangeId: string;+}++export const RemoveDocUniFormulaCommand: ICommand<IRemoveDocUniFormulaCommandParams> = {+ type: CommandType.COMMAND,+ id: 'doc.command.remove-uni-formula',+ handler: (accessor, params: IRemoveDocUniFormulaCommandParams) => {+ const commandService = accessor.get(ICommandService);+ // TODO: maybed remove formula under selection?+ return commandService.syncExecuteCommand(RemoveDocUniFormulaMutation.id, params as IRemoveDocUniFormulaMutationParams);+ },+};+diff --git a/packages-experimental/uni-formula/src/commands/mutation.ts b/packages-experimental/uni-formula/src/commands/mutation.tsnew file mode 100644index 0000000000..9c33882260--- /dev/null+++ b/packages-experimental/uni-formula/src/commands/mutation.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 { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import { UniFormulaService } from '../services/uni-formula.service';++export interface IAddDocUniFormulaMutationParams {+ unitId: string;++ f: string;++ /** Range id. It is also used as the formula id. */+ rangeId: string;+}++export const AddDocUniFormulaMutation: IMutation<IAddDocUniFormulaMutationParams> = {+ type: CommandType.MUTATION,+ id: 'doc.mutation.add-doc-uni-formula',+ handler(accesstor, params: IAddDocUniFormulaMutationParams) {+ const { unitId, f, rangeId: id } = params;+ const uniFormulaService = accesstor.get(UniFormulaService);++ uniFormulaService.registerDocFormula(unitId, id, f);++ return true;+ },+};++export interface IUpdateDocUniFormulaMutationParams extends IAddDocUniFormulaMutationParams {+}++export const UpdateDocUniFormulaMutation: IMutation<IUpdateDocUniFormulaMutationParams> = {+ type: CommandType.MUTATION,+ id: 'doc.mutation.update-doc-uni-formula',+ handler(accessor, params: IUpdateDocUniFormulaMutationParams) {+ const { unitId, f, rangeId: id } = params;+ const uniFormulaService = accessor.get(UniFormulaService);++ if (!uniFormulaService.hasFocFormula(unitId, id)) {+ return false;+ }++ uniFormulaService.unregisterDocFormula(unitId, id);+ uniFormulaService.registerDocFormula(unitId, id, f);+ return true;+ },+};++export interface IRemoveDocUniFormulaMutationParams {+ unitId: string;+ rangeId: string;+}++export const RemoveDocUniFormulaMutation: IMutation<IRemoveDocUniFormulaMutationParams> = {+ type: CommandType.MUTATION,+ id: 'doc.mutation.remove-doc-uni-formula',+ handler(accessor, params: IRemoveDocUniFormulaMutationParams) {+ const { unitId, rangeId: id } = params;+ const uniFormulaService = accessor.get(UniFormulaService);++ if (!uniFormulaService.hasFocFormula(unitId, id)) {+ return false;+ }++ uniFormulaService.unregisterDocFormula(unitId, id);+ return true;+ },+};diff --git a/packages-experimental/uni-formula/src/const.ts b/packages-experimental/uni-formula/src/const.tsnew file mode 100644index 0000000000..f64cf70de9--- /dev/null+++ b/packages-experimental/uni-formula/src/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 DOC_FORMULA_PLUGIN_NAME = 'DOC_FORMULA_PLUGIN';diff --git a/packages-experimental/uni-formula/src/controllers/doc-formula-input.controller.ts b/packages-experimental/uni-formula/src/controllers/doc-formula-input.controller.tsnew file mode 100644index 0000000000..a3d6e36270--- /dev/null+++ b/packages-experimental/uni-formula/src/controllers/doc-formula-input.controller.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 class DocFormulaInputController {++}+diff --git a/packages-experimental/uni-formula/src/controllers/uni-formula.controller.ts b/packages-experimental/uni-formula/src/controllers/uni-formula.controller.tsnew file mode 100644index 0000000000..5a982a2baf--- /dev/null+++ b/packages-experimental/uni-formula/src/controllers/uni-formula.controller.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.+ */++import { IUniverInstanceService } from '@univerjs/core';++/**+ * This controller is responsible for registering formulas into `UniFormulaService`,+ * when a doc is loaded or a new formula is created. It is also responsible for un-registering+ * formula at current time.+ */+export class UniFormulaController {+ constructor(+ @IUniverInstanceService private readonly _univerInstanceSrv: IUniverInstanceService+ ) {++ }+}+diff --git a/packages-experimental/uni-formula/src/index.ts b/packages-experimental/uni-formula/src/index.tsnew file mode 100644index 0000000000..b21bca0091--- /dev/null+++ b/packages-experimental/uni-formula/src/index.ts@@ -0,0 +1,18 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export { UniverDocUniFormulaPlugin } from './uni-formula.plugin';+export { DOC_FORMULA_PLUGIN_NAME } from './const';diff --git a/packages-experimental/uni-formula/src/models/doc-formula.ts b/packages-experimental/uni-formula/src/models/doc-formula.tsnew file mode 100644index 0000000000..0b292dffdb--- /dev/null+++ b/packages-experimental/uni-formula/src/models/doc-formula.ts@@ -0,0 +1,56 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICellData } from '@univerjs/core';++export const DOC_FORMULA_RESOURCE_KEY = 'DOC_FORMULA_RESOURCE';++/**+ * This interface represents a single formula entity in a Univer Doc.+ */+export interface IDocFormulaData {+ /** Id of this formula. It should be unique in a single document, and bound to the custom range's id. */+ rangeId: string;++ /**+ * Raw formula string. For example `=SUM(A1:B4)`.+ */+ f: string;++ /**+ * Formula calculation result.+ */+ v?: ICellData['v'];++ /**+ * Formula calculation format.+ */+ t?: ICellData['t'];+}++export interface IDocFormulaReference extends IDocFormulaData {+ unitId: string;++ /** Formula id assigned by the formula engine. It should not be written to snapshot. */+ formulaId: string;+}++export interface IDocFormulaCache extends Pick<ICellData, 'v' | 't'> { }++export function toJson(formulas: IDocFormulaReference[]): string {+ return JSON.stringify(formulas.map((f) => ({ rangeId: f.rangeId, f: f.f, v: f.v, t: f.t })));+}+diff --git a/packages-experimental/uni-formula/src/services/uni-formula.service.ts b/packages-experimental/uni-formula/src/services/uni-formula.service.tsnew file mode 100644index 0000000000..e7a8348760--- /dev/null+++ b/packages-experimental/uni-formula/src/services/uni-formula.service.ts@@ -0,0 +1,250 @@+/**+ * 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 { ICellData, IMutation, Nullable } from '@univerjs/core';+import { CommandType, Disposable, ICommandService, IUniverInstanceService, LifecycleService, LifecycleStages, OnLifecycle, RCDisposable, ResourceManagerService, toDisposable, UniverInstanceType } from '@univerjs/core';+import { DataSyncPrimaryController } from '@univerjs/rpc';+import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';+import type { IDisposable } from '@wendellhu/redi';+import { Inject, Optional } from '@wendellhu/redi';++import { type IDocFormulaCache, type IDocFormulaData, type IDocFormulaReference, toJson } from '../models/doc-formula';+import { DOC_FORMULA_PLUGIN_NAME } from '../const';++const DOC_PSEUDO_SUBUNIT = 'DOC_PSEUDO_SUBUNIT';++/**+ * Update calculating result in a batch.+ */+export interface IUpdateDocUniFormulaCacheMutationParams {+ unitId: string;+ ids: string[];+ cache: IDocFormulaCache[];+}++export const UpdateDocUniFormulaCacheMutation: IMutation<IUpdateDocUniFormulaCacheMutationParams> = {+ type: CommandType.MUTATION,+ id: 'doc.mutation.update-doc-uni-formula-cache',+ handler(accessor, params: IUpdateDocUniFormulaCacheMutationParams) {+ const { unitId, ids, cache } = params;+ const uniFormulaService = accessor.get(UniFormulaService);+ return uniFormulaService.updateFormulaResults(unitId, ids, cache);+ },+};++/**+ * This service provides methods for docs and slides to register a formula into+ * Univer's formula system.+ */+@OnLifecycle(LifecycleStages.Starting, UniFormulaService)+export class UniFormulaService extends Disposable {+ /** This data maps doc formula key to the formula id in the formula system. */+ private readonly _docFormulas = new Map<string, IDocFormulaReference>();+ private readonly _formulaIdToKey = new Map<string, string>();++ constructor(+ @Inject(ResourceManagerService) resoureManagerService: ResourceManagerService,+ @Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,+ // TODO: wzhudev We may need to register the doc formulas to formula service in later lifecycle stages.+ @ICommandService private readonly _commandSrv: ICommandService,+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,+ @Inject(RegisterOtherFormulaService) private readonly _registerOtherFormulaSrv: RegisterOtherFormulaService,+ @Optional(DataSyncPrimaryController) private readonly _dataSyncPrimaryController?: DataSyncPrimaryController+ ) {+ super();++ this.disposeWithMe(this._commandSrv.registerCommand(UpdateDocUniFormulaCacheMutation));++ this._initDocFormulaResources(resoureManagerService);+ this._initDocDisposingListener();+ this._debugInitFormula();+ }++ override dispose(): void {+ super.dispose();++ // TODO: wzhudev: concrete disposing methods+ }++ /**+ * Remove all formulas under a doc.+ */+ private _unregisterDoc(unitId: string): void {+ const existingsFormulas = Array.from(this._docFormulas.entries());+ existingsFormulas.forEach(([_, value]) => {+ if (value.unitId === unitId) this.unregisterDocFormula(unitId, value.rangeId);+ });+ }++ /**+ * Register a doc formula into the formula system.+ */+ registerDocFormula(unitId: string, rangeId: string, f: string, v: ICellData['v'], t: ICellData['t']): IDisposable {+ const key = getDocFormulaKey(unitId, rangeId);+ if (this._docFormulas.has(key)) {+ throw new Error(`[UniFormulaService]: cannot register formula ${key} when it is already registered!`);+ }++ const pseudoId = getPseudoUnitKey(unitId);+ this._checkResultSubscription();+ this._checkSyncingUnit(pseudoId);++ const id = this._registerOtherFormulaSrv.registerFormula(pseudoId, DOC_PSEUDO_SUBUNIT, f);+ this._docFormulas.set(key, { unitId, rangeId, f, formulaId: id, v, t });+ this._formulaIdToKey.set(id, key);++ return toDisposable(() => this.unregisterDocFormula(unitId, rangeId));+ }++ unregisterDocFormula(unitId: string, rangeId: string): void {+ const key = getDocFormulaKey(unitId, rangeId);+ const item = this._docFormulas.get(key);+ if (!item) {+ return;+ }++ const pseudoId = getPseudoUnitKey(unitId);+ this._checkDisposingResultSubscription();+ this._dataSyncDisposables.get(pseudoId)?.dec();++ this._registerOtherFormulaSrv.deleteFormula(pseudoId, DOC_PSEUDO_SUBUNIT, [item.formulaId]);+ this._docFormulas.delete(key);+ this._formulaIdToKey.delete(item.formulaId);+ }++ hasFocFormula(unitId: string, formulaId: string): boolean {+ return this._docFormulas.has(getDocFormulaKey(unitId, formulaId));+ }++ updateFormulaResults(unitId: string, formulaIds: string[], v: IDocFormulaCache[]): boolean {+ // TODO: @wzhudev: should trigger re-render+ return formulaIds.every((id, index) => {+ const formulaData = this._docFormulas.get(getDocFormulaKey(unitId, id));+ if (!formulaData) return false;++ formulaData.v = v[index].v;+ formulaData.t = v[index].t;+ return true;+ });+ }++ private _dataSyncDisposables = new Map<string, RCDisposable>();+ private _checkSyncingUnit(unitId: string): void {+ if (!this._dataSyncPrimaryController) return;++ if (!this._dataSyncDisposables.has(unitId)) {+ this._dataSyncPrimaryController.syncUnit(unitId);+ this._dataSyncDisposables.set(unitId, new RCDisposable(toDisposable(() => this._dataSyncDisposables.delete(unitId))));+ }++ this._dataSyncDisposables.get(unitId)!.inc();+ }++ private _resultSubscription: Nullable<IDisposable>;+ private _checkResultSubscription(): void {+ if (this._resultSubscription) return;++ this._resultSubscription = toDisposable(this._registerOtherFormulaSrv.formulaResult$.subscribe((resultMap) => {+ for (const resultOfUnit in resultMap) {+ const results = resultMap[resultOfUnit][DOC_PSEUDO_SUBUNIT];+ if (results) {+ const mutationParam = results.map((result) => {+ const formulaId = result.formulaId;+ const key = this._formulaIdToKey.get(formulaId);+ if (!key) return null;++ const item = this._docFormulas.get(key);+ if (!item) return null;++ const r = result.result?.[0][0];+ if (item.v === r?.v && item.t === r?.t) return null;++ return { id: item.rangeId, unitId: item.unitId, cache: r };+ }).reduce((previous, curr) => {+ if (!curr || !curr.cache) return previous;++ if (!previous.unitId) previous.unitId = curr.unitId;+ previous.ids.push(curr.id);+ previous.cache.push(curr.cache);++ return previous;+ }, {+ unitId: '',+ ids: [] as string[],+ cache: [] as Pick<ICellData, 'v' | 't'>[],+ });++ if (mutationParam.ids.length === 0) return;++ this._commandSrv.executeCommand(UpdateDocUniFormulaCacheMutation.id, mutationParam as IUpdateDocUniFormulaCacheMutationParams);+ }+ }+ }));+ }++ private _checkDisposingResultSubscription(): void {+ if (this._docFormulas.size === 0 && this._resultSubscription) {+ this._resultSubscription.dispose();+ this._resultSubscription = null;+ }+ }++ private _debugInitFormula(): void {+ this.registerDocFormula('test_doc', 'test_formula_id', '=\'[workbook-01]工作表11\'!A13');+ }++ private _initDocFormulaResources(resourceManagerService: ResourceManagerService): void {+ resourceManagerService.registerPluginResource({+ pluginName: DOC_FORMULA_PLUGIN_NAME,+ businesses: [UniverInstanceType.UNIVER_DOC],+ toJson: (unitId: string) => {+ const formulas = this._getAllFormulasOfUnit(unitId);+ return toJson(formulas.map((f) => f[1]));+ },+ parseJson: (json: string) => {+ const formulas = JSON.parse(json) as IDocFormulaData[];+ return formulas;+ },+ onLoad: (unitId, formulas) => {+ // NOTE: Should wait for lifecycle?+ formulas.forEach((f) => this.registerDocFormula(unitId, f.rangeId, f.f, f.v, f.t));+ },+ onUnLoad: (unitId) => {+ this._unregisterDoc(unitId);+ },+ });+ }++ private _initDocDisposingListener(): void {+ this._instanceSrv.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_DOC).subscribe((doc) => {+ this._unregisterDoc(doc.getUnitId());+ });+ }++ private _getAllFormulasOfUnit(unitId: string) {+ const formulas = Array.from(this._docFormulas.entries()).filter((v) => v[1].unitId === unitId);+ return formulas;+ }+}++function getPseudoUnitKey(unitId: string): string {+ return `pseudo-${unitId}`;+}++function getDocFormulaKey(unitId: string, formulaId: string): string {+ return `pseudo-${unitId}-${formulaId}`;+}+diff --git a/packages-experimental/uni-formula/src/uni-formula.plugin.ts b/packages-experimental/uni-formula/src/uni-formula.plugin.tsnew file mode 100644index 0000000000..3840076b99--- /dev/null+++ b/packages-experimental/uni-formula/src/uni-formula.plugin.ts@@ -0,0 +1,38 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import { Inject, Injector } from '@wendellhu/redi';+import { UniFormulaService } from './services/uni-formula.service';+import { DOC_FORMULA_PLUGIN_NAME } from './const';++@DependentOn(UniverFormulaEnginePlugin)+export class UniverDocUniFormulaPlugin extends Plugin {+ static override pluginName: string = DOC_FORMULA_PLUGIN_NAME;+ static override type: UniverInstanceType = UniverInstanceType.UNIVER_DOC;++ constructor(+ config: unknown,+ @Inject(Injector) protected readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(injector: Injector): void {+ injector.add([UniFormulaService]);+ }+}diff --git a/packages-experimental/uni-formula/src/vite-env.d.ts b/packages-experimental/uni-formula/src/vite-env.d.tsnew file mode 100644index 0000000000..11f02fe2a0--- /dev/null+++ b/packages-experimental/uni-formula/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/packages-experimental/uni-formula/tsconfig.json b/packages-experimental/uni-formula/tsconfig.jsonnew file mode 100644index 0000000000..e8df90d34b--- /dev/null+++ b/packages-experimental/uni-formula/tsconfig.json@@ -0,0 +1,15 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [+ {+ "path": "./tsconfig.node.json"+ }+ ],+ "include": [+ "src"+ ]+}diff --git a/packages-experimental/uni-formula/tsconfig.node.json b/packages-experimental/uni-formula/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages-experimental/uni-formula/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages-experimental/uni-formula/vite.config.ts b/packages-experimental/uni-formula/vite.config.tsnew file mode 100644index 0000000000..925b530b4d--- /dev/null+++ b/packages-experimental/uni-formula/vite.config.ts@@ -0,0 +1,12 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+ features: {+ react: false,+ css: true,+ dom: true,+ },+});diff --git a/packages-experimental/uniui/README.md b/packages-experimental/uniui/README.mdnew file mode 100644index 0000000000..fb7f05dcb9--- /dev/null+++ b/packages-experimental/uniui/README.md@@ -0,0 +1,16 @@+# @univerjs/uniui++[](https://npmjs.org/packages/@univerjs/uniui)+[](https://img.shields.io/npm/l/@univerjs/uniui)++## Introduction++> TODO: Introduction++## Usage++### Installation++```shell+npm i @univerjs/uniui+```diff --git a/packages-experimental/uniui/package.json b/packages-experimental/uniui/package.jsonnew file mode 100644index 0000000000..fcb15d2a19--- /dev/null+++ b/packages-experimental/uniui/package.json@@ -0,0 +1,95 @@+{+ "name": "@univerjs/uniui",+ "version": "0.2.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": [],+ "sideEffects": [+ "**/*.css"+ ],+ "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-render": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "clsx": ">=2.0.0",+ "react": ">=16.9.0",+ "react-dom": "18.3.1",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {+ "@univerjs/icons": "^0.1.46",+ "rc-util": "^5.43.0"+ },+ "devDependencies": {+ "@types/react": "^18.3.3",+ "@types/react-dom": "^18.3.0",+ "@univerjs/core": "workspace:*",+ "@univerjs/design": "workspace:*",+ "@univerjs/engine-render": "workspace:*",+ "@univerjs/shared": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.16.0",+ "clsx": "^2.1.1",+ "less": "^4.2.0",+ "react": "18.3.1",+ "react-dom": "18.3.1",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.3.4",+ "vitest": "^2.0.3"+ }+}diff --git a/packages-experimental/uniui/src/controllers/uniui-desktop.controller.tsx b/packages-experimental/uniui/src/controllers/uniui-desktop.controller.tsxnew file mode 100644index 0000000000..d75e6d720f--- /dev/null+++ b/packages-experimental/uniui/src/controllers/uniui-desktop.controller.tsx@@ -0,0 +1,111 @@+/**+ * 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, LifecycleService, LifecycleStages, toDisposable } from '@univerjs/core';+import type { IUniverUIConfig, IWorkbenchOptions } from '@univerjs/ui';+import { BuiltInUIPart, CanvasPopup, FloatDom, IUIPartsService } from '@univerjs/ui';+import type { IDisposable } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import { connectInjector } from '@wendellhu/redi/react-bindings';+import React from 'react';+import { delay, filter, take } from 'rxjs';+import { render as createRoot, unmount } from 'rc-util/lib/React/render';++import { UniWorkbench } from '../views/workbench/UniWorkbench';++const STEADY_TIMEOUT = 3000;++export class UniverUniUIController extends Disposable {+ constructor(+ private readonly _config: IUniverUIConfig,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,+ @IUIPartsService private readonly _uiPartsService: IUIPartsService+ ) {+ super();++ this._initBuiltinComponents();++ Promise.resolve().then(() => this._bootstrapWorkbench());+ }++ private _bootstrapWorkbench(): void {+ this.disposeWithMe(+ bootstrap(this._injector, this._config, () => {+ this._lifecycleService.lifecycle$.pipe(+ filter((lifecycle) => lifecycle === LifecycleStages.Ready),+ delay(300),+ take(1)+ ).subscribe(() => {+ this._lifecycleService.stage = LifecycleStages.Rendered;+ setTimeout(() => this._lifecycleService.stage = LifecycleStages.Steady, STEADY_TIMEOUT);+ });+ })+ );+ }++ private _initBuiltinComponents() {+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FLOATING, () => connectInjector(CanvasPopup, this._injector)));+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(FloatDom, this._injector)));+ }+}++function bootstrap(+ injector: Injector,+ options: IWorkbenchOptions,+ callback: () => void+): IDisposable {+ let mountContainer: HTMLElement;++ const container = options.container;+ if (typeof container === 'string') {+ const containerElement = document.getElementById(container);+ if (!containerElement) {+ mountContainer = createContainer(container);+ } else {+ mountContainer = containerElement;+ }+ } else if (container instanceof HTMLElement) {+ mountContainer = container;+ } else {+ mountContainer = createContainer('univer');+ }++ const ConnectedApp = connectInjector(UniWorkbench, injector);+ function render() {+ createRoot(+ <ConnectedApp+ {...options}+ mountContainer={mountContainer}+ onRendered={callback}+ />,+ mountContainer+ );+ }++ render();++ return toDisposable(() => {+ unmount(mountContainer);+ });+}++function createContainer(id: string): HTMLElement {+ const element = document.createElement('div');+ element.id = id;+ // FIXME: the element is not append to the DOM tree. So it won't be rendered.+ return element;+}diff --git a/packages-experimental/uniui/src/index.ts b/packages-experimental/uniui/src/index.tsnew file mode 100644index 0000000000..30056d30d9--- /dev/null+++ b/packages-experimental/uniui/src/index.ts@@ -0,0 +1,17 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export { UniverUniUIPlugin } from './plugin';diff --git a/packages-experimental/uniui/src/plugin.ts b/packages-experimental/uniui/src/plugin.tsnew file mode 100644index 0000000000..afda4382d8--- /dev/null+++ b/packages-experimental/uniui/src/plugin.ts@@ -0,0 +1,139 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DependentOn, IContextService, ILocalStorageService, mergeOverrideWithDependencies, Plugin, Tools } from '@univerjs/core';+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import type { IUniverUIConfig } from '@univerjs/ui';+import {+ BrowserClipboardService,+ CanvasFloatDomService,+ CanvasPopupService,+ ComponentManager,+ ContextMenuService,+ DesktopBeforeCloseService,+ DesktopConfirmService,+ DesktopDialogService,+ DesktopGlobalZoneService,+ DesktopLayoutService,+ DesktopLocalStorageService,+ DesktopMessageService,+ DesktopNotificationService,+ DesktopSidebarService,+ DesktopZenZoneService,+ DISABLE_AUTO_FOCUS_KEY,+ EditorService,+ ErrorController,+ IBeforeCloseService,+ ICanvasPopupService,+ IClipboardInterfaceService,+ IConfirmService,+ IContextMenuService,+ IDialogService,+ IEditorService,+ IGlobalZoneService,+ ILayoutService,+ IMenuService,+ IMessageService,+ INotificationService,+ IPlatformService,+ IProgressService,+ IRangeSelectorService,+ IShortcutService,+ ISidebarService,+ IUIController,+ IUIPartsService,+ IZenZoneService,+ MenuService,+ PlatformService,+ ProgressService,+ RangeSelectorService,+ SharedController,+ ShortcutPanelController,+ ShortcutPanelService,+ ShortcutService,+ UIPartsService,+ UNIVER_UI_PLUGIN_NAME,+ ZIndexManager,+} from '@univerjs/ui';+import { UniverUniUIController } from './controllers/uniui-desktop.controller';+import { UnitGridService } from './services/unit-grid/unit-grid.service';++const UI_BOOTSTRAP_DELAY = 16;++/**+ * This plugin enables the Uni Mode of Univer. It should replace+ * `UniverUIPlugin` when registered.+ */+@DependentOn(UniverRenderEnginePlugin)+export class UniverUniUIPlugin extends Plugin {+ static override pluginName: string = UNIVER_UI_PLUGIN_NAME;++ constructor(+ private _config: Partial<IUniverUIConfig> = {},+ @Inject(Injector) protected readonly _injector: Injector,+ @IContextService private readonly _contextService: IContextService+ ) {+ super();++ this._config = Tools.deepMerge({}, this._config);+ if (this._config.disableAutoFocus) {+ this._contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);+ }+ }++ override onStarting(injector: Injector): void {+ const dependencies: Dependency[] = mergeOverrideWithDependencies([+ [ComponentManager],+ [ZIndexManager],+ [ShortcutPanelService],+ [UnitGridService],+ [IUIPartsService, { useClass: UIPartsService }],+ [ILayoutService, { useClass: DesktopLayoutService }],+ [IShortcutService, { useClass: ShortcutService }],+ [IPlatformService, { useClass: PlatformService }],+ [IMenuService, { useClass: MenuService }],+ [IContextMenuService, { useClass: ContextMenuService }],+ [IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }],+ [INotificationService, { useClass: DesktopNotificationService, lazy: true }],+ [IDialogService, { useClass: DesktopDialogService, lazy: true }],+ [IConfirmService, { useClass: DesktopConfirmService, lazy: true }],+ [ISidebarService, { useClass: DesktopSidebarService, lazy: true }],+ [IZenZoneService, { useClass: DesktopZenZoneService, lazy: true }],+ [IGlobalZoneService, { useClass: DesktopGlobalZoneService, lazy: true }],+ [IMessageService, { useClass: DesktopMessageService, lazy: true }],+ [ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],+ [IBeforeCloseService, { useClass: DesktopBeforeCloseService }],+ [IEditorService, { useClass: EditorService }],+ [IRangeSelectorService, { useClass: RangeSelectorService }],+ [ICanvasPopupService, { useClass: CanvasPopupService }],+ [IProgressService, { useClass: ProgressService }],+ [CanvasFloatDomService],+ [IUIController, {+ useFactory: () => this._injector.createInstance(UniverUniUIController, this._config),+ }],+ [SharedController, {+ useFactory: () => this._injector.createInstance(SharedController, this._config),+ }],+ [ErrorController],+ [ShortcutPanelController, {+ useFactory: () => this._injector.createInstance(ShortcutPanelController, this._config),+ }],+ ], this._config.override);+ dependencies.forEach((dependency) => injector.add(dependency));+ }+}diff --git a/packages-experimental/uniui/src/services/unit-grid/unit-grid.service.ts b/packages-experimental/uniui/src/services/unit-grid/unit-grid.service.tsnew file mode 100644index 0000000000..f234c12396--- /dev/null+++ b/packages-experimental/uniui/src/services/unit-grid/unit-grid.service.ts@@ -0,0 +1,79 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, isInternalEditorID } from '@univerjs/core';+import type { IRender } from '@univerjs/engine-render';+import { IRenderManagerService } from '@univerjs/engine-render';+import { BehaviorSubject } from 'rxjs';++export type IUnitGrid = string[];++/**+ * This services decides which (now at maximum two) units are going to be rendered in the browser.+ */+export class UnitGridService extends Disposable {+ // TODO@wzhudev: currently we only support at maximum 2 units rendered side by side.+ // In the future we would introduce a grid system (very much like vscode's) to support more+ // units and more complex layout.+ private _unitGrid: IUnitGrid = [];+ private readonly _unitGrid$ = new BehaviorSubject<IUnitGrid>(this._unitGrid);+ readonly unitGrid$ = this._unitGrid$.asObservable();++ constructor(+ @IRenderManagerService private readonly _renderSrv: IRenderManagerService+ ) {+ super();++ this._init();+ }++ setContainerForRender(unitId: string, element: HTMLElement) {+ this._renderSrv.getRenderById(unitId)?.engine.setContainer(element);+ }++ override dispose(): void {+ super.dispose();++ this._unitGrid$.complete();+ }++ private _init(): void {+ this._renderSrv.getRenderAll().forEach((renderer) => this._onRendererCreated(renderer));+ this.disposeWithMe(this._renderSrv.created$.subscribe((renderer) => this._onRendererCreated(renderer)));+ this.disposeWithMe(this._renderSrv.disposed$.subscribe((unitId) => this._onRenderedDisposed(unitId)));+ }++ private _onRendererCreated(renderer: IRender): void {+ if (isInternalEditorID(renderer.unitId)) {+ return;+ }++ this._unitGrid.push(renderer.unitId);+ this._emitLayoutChange();+ }++ private _onRenderedDisposed(unitId: string): void {+ const idx = this._unitGrid.indexOf(unitId);+ if (idx !== -1) {+ this._unitGrid.splice(idx, 1);+ this._emitLayoutChange();+ }+ }++ private _emitLayoutChange(): void {+ this._unitGrid$.next(this._unitGrid);+ }+}diff --git a/packages-experimental/uniui/src/views/workbench/UniWorkbench.tsx b/packages-experimental/uniui/src/views/workbench/UniWorkbench.tsxnew file mode 100644index 0000000000..e2b1eddcb9--- /dev/null+++ b/packages-experimental/uniui/src/views/workbench/UniWorkbench.tsx@@ -0,0 +1,245 @@+/**+ * 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.+ */++// Refer to packages/ui/src/views/App.tsx++import { IContextService, IUniverInstanceService, LocaleService, ThemeService } from '@univerjs/core';+import { ConfigContext, ConfigProvider, defaultTheme, themeInstance } from '@univerjs/design';+import type { ILocale } from '@univerjs/design';+import {+ builtInGlobalComponents,+ BuiltInUIPart,+ ComponentContainer,+ ContextMenu,+ IMessageService,+ type IWorkbenchOptions,+ Sidebar,+ Toolbar,+ UNI_DISABLE_CHANGING_FOCUS_KEY,+ useComponentsOfPart,+ useObservable,+ ZenZone,+} from '@univerjs/ui';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import clsx from 'clsx';+import { UnitGridService } from '../../services/unit-grid/unit-grid.service';+import styles from './workbench.module.less';++// Refer to packages/ui/src/views/workbench/Workbench.tsx++export interface IUniWorkbenchProps extends IWorkbenchOptions {+ mountContainer: HTMLElement;++ onRendered: () => void;+}++export function UniWorkbench(props: IUniWorkbenchProps) {+ const {+ header = true,+ footer = true,+ contextMenu = true,+ mountContainer,+ onRendered,+ } = props;++ const localeService = useDependency(LocaleService);+ const themeService = useDependency(ThemeService);+ const messageService = useDependency(IMessageService);+ const unitGridService = useDependency(UnitGridService);+ const instanceService = useDependency(IUniverInstanceService);++ const contentRef = useRef<HTMLDivElement>(null);++ const footerComponents = useComponentsOfPart(BuiltInUIPart.FOOTER);+ const headerComponents = useComponentsOfPart(BuiltInUIPart.HEADER);+ const headerMenuComponents = useComponentsOfPart(BuiltInUIPart.HEADER_MENU);+ const contentComponents = useComponentsOfPart(BuiltInUIPart.CONTENT);+ const leftSidebarComponents = useComponentsOfPart(BuiltInUIPart.LEFT_SIDEBAR);+ const globalComponents = useComponentsOfPart(BuiltInUIPart.GLOBAL);++ const unitGrid = useObservable(unitGridService.unitGrid$, undefined, true);+ const focused = useObservable(instanceService.focused$);++ const focusUnit = useCallback((unitId: string) => {+ instanceService.focusUnit(unitId);+ instanceService.setCurrentUnitForType(unitId);+ }, [instanceService]);++ useEffect(() => {+ if (!themeService.getCurrentTheme()) {+ themeService.setTheme(defaultTheme);+ }++ onRendered();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const [locale, setLocale] = useState<ILocale>(localeService.getLocales() as unknown as ILocale);++ // Create a portal container for injecting global component themes.+ const portalContainer = useMemo<HTMLElement>(() => document.createElement('div'), []);++ useEffect(() => {+ document.body.appendChild(portalContainer);+ messageService.setContainer(portalContainer);++ const subscriptions = [+ localeService.localeChanged$.subscribe(() => {+ setLocale(localeService.getLocales() as unknown as ILocale);+ }),+ themeService.currentTheme$.subscribe((theme) => {+ themeInstance.setTheme(mountContainer, theme);+ portalContainer && themeInstance.setTheme(portalContainer, theme);+ }),+ ];++ return () => {+ // batch unsubscribe+ subscriptions.forEach((subscription) => subscription.unsubscribe());++ // cleanup+ document.body.removeChild(portalContainer);+ };+ }, [localeService, messageService, mountContainer, portalContainer, themeService.currentTheme$]);++ return (+ <ConfigProvider locale={locale?.design} mountContainer={portalContainer}>+ {/**+ * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch+ * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events+ * bubbled to this element and refocus the input element.+ */}+ <div className={styles.workbenchLayout} tabIndex={-1} onBlur={(e) => e.stopPropagation()}>+ {/* header */}+ {header && (+ <header className={styles.workbenchContainerHeader}>+ <Toolbar headerMenuComponents={headerMenuComponents} />+ </header>+ )}++ {/* content */}+ <section className={styles.workbenchContainer}>+ <div className={styles.workbenchContainerWrapper}>+ <aside className={styles.workbenchContainerLeftSidebar}>+ <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />+ </aside>++ <section className={styles.workbenchContainerContent}>+ <header>+ {header && <ComponentContainer key="header" components={headerComponents} />}+ </header>++ <section+ className={styles.workbenchContainerCanvasContainer}+ ref={contentRef}+ data-range-selector+ onContextMenu={(e) => e.preventDefault()}+ >+ {/* Render units. */}+ {unitGrid?.map((unitId) => (+ <UnitRenderer+ key={unitId}+ unitId={unitId}+ focused={focused === unitId}+ onFocus={focusUnit}+ gridService={unitGridService}+ instanceService={instanceService}+ />+ ))}+ <ComponentContainer key="content" components={contentComponents} />+ </section>+ </section>++ <aside className={styles.workbenchContainerSidebar}>+ <Sidebar />+ </aside>+ </div>++ {/* footer */}+ {footer && (+ <footer className={styles.workbenchFooter}>+ <ComponentContainer key="footer" components={footerComponents} />+ </footer>+ )}++ <ZenZone />+ </section>+ </div>+ <ComponentContainer key="global" components={globalComponents} />+ <ComponentContainer key="built-in-global" components={builtInGlobalComponents} />+ {contextMenu && <ContextMenu />}+ <FloatingContainer />+ </ConfigProvider>+ );+}++interface IUnitRendererProps {+ unitId: string;+ focused: boolean;++ gridService: UnitGridService;+ instanceService: IUniverInstanceService;++ onFocus: (unitId: string) => void;+}++function UnitRenderer(props: IUnitRendererProps) {+ const { unitId, gridService, focused, onFocus } = props;+ const mountRef = useRef<HTMLDivElement>(null);++ const contextService = useDependency(IContextService);+ const disableChangingUnitFocusing = useObservable(+ () => contextService.subscribeContextValue$(UNI_DISABLE_CHANGING_FOCUS_KEY),+ false,+ false,+ []+ );++ const focus = useCallback(() => {+ if (!disableChangingUnitFocusing && !focused) {+ onFocus(unitId);+ }+ }, [focused, onFocus, disableChangingUnitFocusing, unitId]);++ useEffect(() => {+ if (mountRef.current) {+ gridService.setContainerForRender(unitId, mountRef.current);+ }+ }, [gridService, unitId]);++ return (+ <div+ className={clsx(styles.workbenchContainerCanvas, {+ [styles.workbenchContainerCanvasFocused]: focused,+ })}+ ref={mountRef}+ // We bind these focusing events on capture phrase so the+ // other event handlers would have correct currently focused unit.+ onPointerUpCapture={focus}+ onWheelCapture={focus}+ >+ </div>+ );+}++function FloatingContainer() {+ const { mountContainer } = useContext(ConfigContext);+ const floatingComponents = useComponentsOfPart(BuiltInUIPart.FLOATING);++ return createPortal(<ComponentContainer key="floating" components={floatingComponents} />, mountContainer!);+}diff --git a/packages-experimental/uniui/src/views/workbench/workbench.module.less b/packages-experimental/uniui/src/views/workbench/workbench.module.lessnew file mode 100644index 0000000000..033a761ab2--- /dev/null+++ b/packages-experimental/uniui/src/views/workbench/workbench.module.less@@ -0,0 +1,76 @@+.workbench {+ &-layout {+ display: flex;+ flex-direction: column;+ height: 100%;+ background-color: rgb(var(--bg-color));+ min-height: 0;+ position: relative;+ }++ &-header {+ // height: 32px;+ }++ &-container {+ position: relative;+ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;++ &-header {+ position: relative;+ z-index: 10;+ width: 100%;+ }++ &-wrapper {+ display: grid;+ grid-template-columns: auto 1fr auto;+ grid-template-rows: 100%;+ height: 100%;+ overflow: hidden;+ }++ &-content {+ position: relative;++ overflow: hidden;+ display: grid;+ grid-template-rows: auto 1fr;+ flex: 1;++ background-color: rgb(var(--bg-color-secondary));+ border-bottom: 1px solid rgb(var(--border-color));+ }++ &-canvas-container {+ position: relative;+ display: flex;+ }++ &-canvas {+ flex: 1;+ position: relative;+ overflow: hidden;+ border: 1px solid transparent;++ &-focused {+ border: 1px solid rgb(var(--primary-color));+ }+ }++ &-left-sidebar {+ height: 100%;+ }++ &-sidebar {+ height: 100%;+ }+ }++ &-footer {+ // height: 36px;+ }+}diff --git a/packages-experimental/uniui/src/vite-env.d.ts b/packages-experimental/uniui/src/vite-env.d.tsnew file mode 100644index 0000000000..11f02fe2a0--- /dev/null+++ b/packages-experimental/uniui/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/packages-experimental/uniui/tsconfig.json b/packages-experimental/uniui/tsconfig.jsonnew file mode 100644index 0000000000..e8df90d34b--- /dev/null+++ b/packages-experimental/uniui/tsconfig.json@@ -0,0 +1,15 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [+ {+ "path": "./tsconfig.node.json"+ }+ ],+ "include": [+ "src"+ ]+}diff --git a/packages-experimental/uniui/tsconfig.node.json b/packages-experimental/uniui/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages-experimental/uniui/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages-experimental/uniui/vite.config.ts b/packages-experimental/uniui/vite.config.tsnew file mode 100644index 0000000000..925b530b4d--- /dev/null+++ b/packages-experimental/uniui/vite.config.ts@@ -0,0 +1,12 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+ features: {+ react: false,+ css: true,+ dom: true,+ },+});diff --git a/packages/core/src/shared/lifecycle.ts b/packages/core/src/shared/lifecycle.tsindex e8be30e3ad..db7b723891 100644--- a/packages/core/src/shared/lifecycle.ts+++ b/packages/core/src/shared/lifecycle.ts@@ -122,3 +122,27 @@ export class RxDisposable extends Disposable implements IDisposable {this.dispose$.complete();}}++export class RCDisposable extends Disposable {+ private _ref = 0;++ constructor(private readonly _rootDisposable: IDisposable) {+ super();+ }++ inc(): void {+ if (this._disposed) {+ throw new Error('[RCDisposable]: should not ref to a disposed.');+ }+ this._ref += 1;+ }++ dec(): void {+ this._ref -= 1;++ if (this._ref === 0) {+ this._rootDisposable.dispose();+ this.dispose();+ }+ }+}diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.tsindex 022310bba2..e3b98a0b87 100644--- a/packages/core/src/shared/tools.ts+++ b/packages/core/src/shared/tools.ts@@ -167,11 +167,13 @@ export class Tools {return 'Unknown browser';}+ /**+ * Use this method without `Tools`.+ *+ * @deprecated+ */static generateRandomId(n: number = 21, alphabet?: string): string {- if (alphabet) {- return customAlphabet(alphabet, n)();- }- return nanoid(n);+ return generateRandomId(n, alphabet);}static getClassName(instance: object): string {@@ -709,3 +711,11 @@ export class Tools {return Math.max(min, Math.min(max, value));}}++export function generateRandomId(n: number = 21, alphabet?: string): string {+ if (alphabet) {+ return customAlphabet(alphabet, n)();+ }++ return nanoid(n);+}diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 23493c3993..8bd6256f85 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -283,6 +283,12 @@ export interface ICustomRange {wholeEntity?: boolean;}+// TODO: @weird94 this range should not be built-in. It makes custom ranges not+// extensible for community users.++/**+ * @deprecated+ */export enum CustomRangeType {HYPERLINK,FIELD, // 17.16 Fields and Hyperlinks@@ -291,6 +297,7 @@ export enum CustomRangeType {COMMENT,CUSTOM,MENTION,+ UNI_FORMULA,}/**diff --git a/packages/core/src/types/interfaces/i-range.ts b/packages/core/src/types/interfaces/i-range.tsindex a6cf9f917a..9c136fa803 100644--- a/packages/core/src/types/interfaces/i-range.ts+++ b/packages/core/src/types/interfaces/i-range.ts@@ -34,7 +34,21 @@ export enum AbsoluteRefType {ALL,}-export interface IRowRange {+interface IRangeLocation {+ /**+ * Id of the Workbook the range belongs to.+ * When this field is not defined, it should be considered as the range in the currently activated worksheet.+ */+ unitId?: string;++ /**+ * Id of the Worksheet the range belongs to.+ * When this field is not defined, it should be considered as the range in the currently activated worksheet.+ */+ sheetId?: string;+}++export interface IRowRange extends IRangeLocation {/*** The start row (inclusive) of the range* startRow@@ -48,7 +62,7 @@ export interface IRowRange {endRow: number;}-export interface IColumnRange {+export interface IColumnRange extends IRangeLocation {/*** The start column (inclusive) of the range* startColumn@@ -78,7 +92,6 @@ export interface IColumnRange {* means "A1:B2"*/export interface IRange extends IRowRange, IColumnRange {-rangeType?: RANGE_TYPE;startAbsoluteRefType?: AbsoluteRefType;diff --git a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.tsindex 4cfd79e5bc..a90137b34e 100644--- a/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts+++ b/packages/docs-hyper-link-ui/src/commands/commands/add-link.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { CommandType, CustomRangeType, type ICommand, ICommandService, sequenceExecute, Tools } from '@univerjs/core';+import { CommandType, CustomRangeType, generateRandomId, type ICommand, ICommandService, sequenceExecuteAsync } from '@univerjs/core';import { addCustomRangeBySelectionFactory } from '@univerjs/docs';import { AddDocHyperLinkMutation } from '@univerjs/docs-hyper-link';@@ -30,9 +30,10 @@ export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {if (!params) {return false;}+const { payload, unitId } = params;const commandService = accessor.get(ICommandService);- const id = Tools.generateRandomId();+ const id = generateRandomId();const doMutation = addCustomRangeBySelectionFactory(accessor,{@@ -41,18 +42,12 @@ export const AddDocHyperLinkCommand: ICommand<IAddDocHyperLinkCommandParams> = {});if (doMutation) {- const commentMutation = {+ const hyperLinkMutation = {id: AddDocHyperLinkMutation.id,- params: {- unitId,- link: {- payload,- id,- },- },+ params: { unitId, link: { payload, id } },};- return (await sequenceExecute([commentMutation, doMutation], commandService)).result;+ return (await sequenceExecuteAsync([hyperLinkMutation, doMutation], commandService)).result;}return false;diff --git a/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts b/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.tsindex 25cceeed2b..9bba6790f6 100644--- a/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts+++ b/packages/docs-hyper-link/src/commands/mutations/add-link.mutation.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { CommandType, type ICommand } from '@univerjs/core';+import { CommandType, type IMutation } from '@univerjs/core';import type { IDocHyperLink } from '../../types/interfaces/i-doc-hyper-link';import { DocHyperLinkModel } from '../../models/hyper-link.model';@@ -23,13 +23,14 @@ export interface IAddDocHyperLinkMutationParams {link: IDocHyperLink;}-export const AddDocHyperLinkMutation: ICommand<IAddDocHyperLinkMutationParams> = {+export const AddDocHyperLinkMutation: IMutation<IAddDocHyperLinkMutationParams> = {type: CommandType.MUTATION,id: 'docs.mutation.add-hyper-link',- handler(accessor, params) {+ handler(accessor, params: IAddDocHyperLinkMutationParams) {if (!params) {return false;}+const docHyperLinkModel = accessor.get(DocHyperLinkModel);return docHyperLinkModel.addLink(params.unitId, params.link);},diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex 42bce87985..99501db49b 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -14,13 +14,11 @@* limitations under the License.*/-import type { DocumentDataModel } from '@univerjs/core';-import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import { Disposable, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';import type { IMenuItemFactory } from '@univerjs/ui';-import { BuiltInUIPart, ComponentManager, IEditorService, ILayoutService, IMenuService, IUIPartsService } from '@univerjs/ui';+import { ComponentManager, ILayoutService, IMenuService } from '@univerjs/ui';import { Inject, Injector } from '@wendellhu/redi';-import { connectInjector } from '@wendellhu/redi/react-bindings';import { ITextSelectionRenderManager } from '@univerjs/engine-render';import { COLOR_PICKER_COMPONENT, ColorPicker } from '../components/color-picker';import {@@ -30,7 +28,6 @@ import {FontFamilyItem,} from '../components/font-family';import { FONT_SIZE_COMPONENT, FontSize } from '../components/font-size';-import { DocBackground } from '../views/doc-background/DocBackground';import type { IUniverDocsUIConfig } from '../basics';import {AlignCenterMenuItemFactory,@@ -61,10 +58,7 @@ export class DocUIController extends Disposable {@Inject(Injector) private readonly _injector: Injector,@Inject(ComponentManager) private readonly _componentManager: ComponentManager,@ILayoutService private readonly _layoutService: ILayoutService,- @IEditorService private readonly _editorService: IEditorService,- @IMenuService private readonly _menuService: IMenuService,- @IUIPartsService private readonly _uiPartsService: IUIPartsService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ @IMenuService private readonly _menuService: IMenuService) {super();@@ -112,24 +106,9 @@ export class DocUIController extends Disposable {private _init(): void {this._initCustomComponents();this._initMenus();- this._initDocBackground();this._initFocusHandler();}- private _initDocBackground() {- const firstDocUnitId = this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)[0].getUnitId();- if (firstDocUnitId == null) {- return;- }-- const embedded = this._editorService.isEditor(firstDocUnitId);- if (!embedded) {- this.disposeWithMe(- this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(DocBackground, this._injector))- );- }- }-private _initFocusHandler(): void {this.disposeWithMe(this._layoutService.registerFocusHandler(UniverInstanceType.UNIVER_DOC, () => {diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 7d5e19d7a9..dfdacf42fc 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -23,9 +23,7 @@ import {} from '@univerjs/core';import type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';-import { IEditorService, IShortcutService } from '@univerjs/ui';-import { IRenderManagerService } from '@univerjs/engine-render';import { DocInterceptorService, DocSkeletonManagerService } from '@univerjs/docs';import {@@ -44,7 +42,6 @@ import { DefaultDocUiConfig } from './basics';import { DOC_UI_PLUGIN_NAME } from './basics/const/plugin-name';import { AppUIController } from './controllers';import { DocUIController } from './controllers/doc-ui.controller';-import { BreakLineShortcut, DeleteLeftShortcut, DeleteRightShortcut } from './shortcuts/core-editing.shortcut';import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';import { DocClipboardController } from './controllers/clipboard.controller';diff --git a/packages/docs-ui/src/views/doc-background/index.module.less b/packages/docs-ui/src/views/doc-background/index.module.lessdeleted file mode 100644index f9d6c50294..0000000000--- a/packages/docs-ui/src/views/doc-background/index.module.less+++ /dev/null@@ -1,11 +0,0 @@-@size: 100%;--.docs-ui-canvas-background {- position: relative;- width: @size;- height: @size;- background: rgb(var(--grey-50)); //rgb(233,238,242)- z-index: 1;- user-select: none;- pointer-events: none;-}diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.tsindex 1f8a3ca3d1..8f32df1999 100644--- a/packages/docs/src/commands/commands/delete.command.ts+++ b/packages/docs/src/commands/commands/delete.command.ts@@ -142,7 +142,6 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {id: 'doc.command.merge-two-paragraph',type: CommandType.COMMAND,-// eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: IMergeTwoParagraphParams) => {const textSelectionManagerService = accessor.get(TextSelectionManagerService);diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.tsindex 134e86d72f..21fb4e18c3 100644--- a/packages/docs/src/services/doc-skeleton-manager.service.ts+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts@@ -51,7 +51,7 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMothis._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentModel) => {- if (documentModel?.getUnitId() === this._context.unitId) {+ if (documentModel && documentModel.getUnitId() === this._context.unitId) {this._update(documentModel);}});diff --git a/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.tsindex 590206aecf..4f97ef3d11 100644--- a/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts+++ b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts@@ -29,6 +29,9 @@ export interface IRemoveOtherFormulaMutationParams {subUnitId: string;formulaIdList: string[];};++// TODO: remove these two mutations to use RPC instead.+/*** In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.* It requires setting local to true during execution.diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.tsindex 232221935e..1b7a44dcdb 100644--- a/packages/engine-formula/src/controller/calculate.controller.ts+++ b/packages/engine-formula/src/controller/calculate.controller.ts@@ -163,24 +163,6 @@ export class CalculateController extends Disposable {* Assignment operation after formula calculation.*/this._calculateFormulaService.executionInProgressListener$.subscribe((data) => {- const {- totalFormulasToCalculate,- completedFormulasCount,- totalArrayFormulasToCalculate,- completedArrayFormulasCount,- stage,- } = data;-- if (totalArrayFormulasToCalculate > 0) {- // console.log(- // `Stage ${stage} Array formula.There are ${totalArrayFormulasToCalculate} functions to be executed, ${completedArrayFormulasCount} complete.`- // );- } else {- // console.log(- // `Stage ${stage} .There are ${totalFormulasToCalculate} functions to be executed, ${completedFormulasCount} complete.`- // );- }-this._commandService.executeCommand(SetFormulaCalculationNotificationMutation.id,{diff --git a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.tsindex 6a0475ea21..1df78e2e8d 100644--- a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts+++ b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts@@ -168,7 +168,7 @@ export interface IEditorInputConfig {}export class TextSelectionRenderManager extends RxDisposable implements ITextSelectionRenderManager {- private readonly _onInputBefore$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);+ private readonly _onInputBefore$ = new Subject<Nullable<IEditorInputConfig>>();readonly onInputBefore$ = this._onInputBefore$.asObservable();private readonly _onKeydown$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);@@ -819,6 +819,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel}private _getCanvasOffset() {+ // This is quiet ambiguous, when did the engine's canvas offset changes?const engine = this._scene?.getEngine() as Engine;return getCanvasOffsetByEngine(engine);}diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.tsindex 7dffce97ac..da92b3cc10 100644--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts@@ -245,7 +245,8 @@ export class SpreadsheetSkeleton extends Skeleton {private _renderRawFormula = false;constructor(- private _worksheet: Worksheet | undefined,+ readonly worksheet: Worksheet,+/*** @deprecated avoid use `IWorksheetData` directly, use API provided by `Worksheet`, otherwise* `ViewModel` will be not working.@@ -322,31 +323,6 @@ export class SpreadsheetSkeleton extends Skeleton {return this.columnHeaderHeight + this._marginTop;}- get worksheet() {- return this._worksheet;- }-- // get dataMergeCacheAll() {- // return this._dataMergeCacheAll;- // }-- /**- * @deprecated- */- static create(- worksheet: Worksheet | undefined,- config: IWorksheetData,- cellData: ObjectMatrix<Nullable<ICellData>>,- styles: Styles,- localeService: LocaleService,- contextService: IContextService- ) {- return new SpreadsheetSkeleton(worksheet, config, cellData, styles, localeService, contextService);- }-- /**- * TODO: DR-Univer, fix as unknown as- */override dispose(): void {super.dispose();@@ -362,7 +338,6 @@ export class SpreadsheetSkeleton extends Skeleton {this._renderedCellCache = null as unknown as ObjectMatrix<boolean>;this._overflowCache = null as unknown as ObjectMatrix<IRange>;- this._worksheet = null as unknown as Worksheet;this._worksheetData = null as unknown as IWorksheetData;this._cellData = null as unknown as ObjectMatrix<Nullable<ICellData>>;this._styles = null as unknown as Styles;@@ -371,15 +346,16 @@ export class SpreadsheetSkeleton extends Skeleton {/*** @deprecated should never expose a property that is provided by another module!*/- getCellData() {- return this._cellData;+ getsStyles() {+ return this._styles;}/**- * @deprecated should never expose a property that is provided by another module!+ * Get which Workbook and Worksheet this skeleton is attached to.+ * @returns [unitId, sheetId]*/- getsStyles() {- return this._styles;+ getLocation(): [string, string] {+ return [this.worksheet.getUnitId(), this.worksheet.getSheetId()];}private _initContextListener() {@@ -491,7 +467,7 @@ export class SpreadsheetSkeleton extends Skeleton {const { columnCount, columnData, mergeData, defaultRowHeight, defaultColumnWidth } = this._worksheetData;let height = defaultRowHeight;- const worksheet = this._worksheet;+ const worksheet = this.worksheet;if (!worksheet) {return height;}@@ -603,7 +579,7 @@ export class SpreadsheetSkeleton extends Skeleton {private _dynamicallyUpdateRowHeaderWidth(rowHeader: { width: number }): number {const SIZE_BY_EACH_CHARACTER = 8;- const widthByComputation = (`${this._worksheet?.getRowCount()}`.length * SIZE_BY_EACH_CHARACTER);+ const widthByComputation = (`${this.worksheet.getRowCount()}`.length * SIZE_BY_EACH_CHARACTER);return Math.max(rowHeader.width, widthByComputation);}@@ -873,16 +849,6 @@ export class SpreadsheetSkeleton extends Skeleton {}}- // if (column === -1) {- // const columnLength = columnWidthAccumulation.length - 1;- // const lastColumnValue = columnWidthAccumulation[columnLength];- // if (lastColumnValue <= offsetX) {- // column = columnWidthAccumulation.length - 1;- // } else {- // column = 0;- // }- // }-return column;}@@ -913,15 +879,6 @@ export class SpreadsheetSkeleton extends Skeleton {row = row + 1;}}- // if (row === -1) {- // const rowLength = rowHeightAccumulation.length - 1;- // const lastRowValue = rowHeightAccumulation[rowLength];- // if (lastRowValue <= offsetY) {- // row = rowHeightAccumulation.length - 1;- // } else {- // row = 0;- // }- // }return row;}@@ -1441,7 +1398,7 @@ export class SpreadsheetSkeleton extends Skeleton {for (let r = 0; r < rowCount; r++) {let rowHeight = defaultRowHeight;- if (this._worksheet?.getRowFiltered(r)) {+ if (this.worksheet.getRowFiltered(r)) {rowHeight = 0;} else if (data[r] != null) {const rowDataItem = data[r];@@ -1524,7 +1481,7 @@ export class SpreadsheetSkeleton extends Skeleton {const columnCount = this._columnWidthAccumulation.length - 1;for (let i = startColumn; i >= endColumn; i--) {const column = i;- const cell = this._worksheet?.getCell(row, column);+ const cell = this.worksheet.getCell(row, column);if ((!isCellCoverable(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {if (column === startColumn) {return column;@@ -1553,7 +1510,7 @@ export class SpreadsheetSkeleton extends Skeleton {}for (let i = startColumn; i <= endColumn; i++) {const column = i;- const cell = this._worksheet?.getCell(row, column);+ const cell = this.worksheet.getCell(row, column);if ((!isCellCoverable(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {if (column === startColumn) {return column;@@ -1698,19 +1655,15 @@ export class SpreadsheetSkeleton extends Skeleton {return true;}- if (!this._worksheet) {- return true;- }-/*** TODO: DR-Univer getCellRaw for slide demo, the implementation approach will be changed in the future.*/- const cell = this._worksheet.getCell(r, c) || this._worksheet.getCellRaw(r, c);+ const cell = this.worksheet.getCell(r, c) || this.worksheet.getCellRaw(r, c);if (!cell) {return true;}- const hidden = this._worksheet.getColVisible(c) === false || this._worksheet.getRowVisible(r) === false;+ const hidden = this.worksheet.getColVisible(c) === false || this.worksheet.getRowVisible(r) === false;if (hidden) {const { isMerged, isMergedMainCell } = getCellInfoInMergeData(r,@@ -1934,7 +1887,7 @@ export class SpreadsheetSkeleton extends Skeleton {* In Excel, for the border rendering of merged cells to take effect, the outermost cells need to have the same border style.*/private _setMergeBorderProps(type: BORDER_TYPE, cache: IStylesCache, mergeRange: IRange) {- if (!this._worksheet || !cache.border) {+ if (!this.worksheet || !cache.border) {return;}@@ -1977,7 +1930,7 @@ export class SpreadsheetSkeleton extends Skeleton {row = i;}- const cell = this._worksheet.getCell(row, column);+ const cell = this.worksheet.getCell(row, column);if (!cell) {isAddBorders = false;break;diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.tsindex 2c5fb869c7..3a3c6d1ac2 100644--- a/packages/engine-render/src/engine.ts+++ b/packages/engine-render/src/engine.ts@@ -189,6 +189,10 @@ export class Engine extends ThinEngine<Scene> {}setContainer(elem: HTMLElement, resize = true) {+ if (this._container === elem) {+ return;+ }+this._container = elem;this._container.appendChild(this.getCanvasElement());diff --git a/packages/engine-render/src/render-manager/render-manager.service.ts b/packages/engine-render/src/render-manager/render-manager.service.tsindex 490e32e734..5d2dc6a5fe 100644--- a/packages/engine-render/src/render-manager/render-manager.service.ts+++ b/packages/engine-render/src/render-manager/render-manager.service.ts@@ -34,11 +34,13 @@ export type RenderComponentType = SheetComponent | DocComponent | Slide | BaseObexport interface IRenderManagerService extends IDisposable {/** @deprecated */currentRender$: Observable<Nullable<string>>;+addRender(unitId: string, renderer: IRender): void;createRender(unitId: string): IRender;removeRender(unitId: string): void;setCurrent(unitId: string): void;getRenderById(unitId: string): Nullable<IRender>;+ getAllRenderersOfType(type: UniverInstanceType): RenderUnit[];getCurrentTypeOfRenderer(type: UniverInstanceType): Nullable<RenderUnit>;getRenderAll(): Map<string, IRender>;defaultEngine: Engine;@@ -53,6 +55,9 @@ export interface IRenderManagerService extends IDisposable {/** @deprecated this design is very very weird! Remove it. */create(unitId: string): void;+ created$: Observable<IRender>;+ disposed$: Observable<string>;+/** @deprecated There will be multi units to render at the same time, so there is no *current*. */getCurrent(): Nullable<IRender>;/** @deprecated There will be multi units to render at the same time, so there is no *first*. */@@ -60,6 +65,7 @@ export interface IRenderManagerService extends IDisposable {has(unitId: string): boolean;withCurrentTypeOfUnit<T>(type: UniverInstanceType, id: DependencyIdentifier<T>): Nullable<T>;+registerRenderModule<T extends UnitModel>(type: UnitType, dep: Dependency<T>): IDisposable;}@@ -81,6 +87,12 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe/** @deprecated */readonly createRender$ = this._createRender$.asObservable();+ private readonly _renderCreated$ = new Subject<IRender>();+ readonly created$ = this._renderCreated$.asObservable();++ private readonly _renderDisposed$ = new Subject<string>();+ readonly disposed$ = this._renderDisposed$.asObservable();+get defaultEngine() {if (!this._defaultEngine) {this._defaultEngine = new Engine();@@ -104,6 +116,9 @@ export class RenderManagerService extends Disposable implements IRenderManagerSethis._renderDependencies.clear();this._renderMap.clear();this._currentRender$.complete();++ this._renderCreated$.complete();+ this._renderDisposed$.complete();}registerRenderModules(type: UnitType, deps: Dependency[]): IDisposable {@@ -153,7 +168,21 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe}createRender(unitId: string): IRender {- return this._createRender(unitId, new Engine());+ const renderer = this._createRender(unitId, new Engine());+ this._renderCreated$.next(renderer);+ return renderer;+ }++ getAllRenderersOfType(type: UniverInstanceType): RenderUnit[] {+ const renderUnits: RenderUnit[] = [];+ for (const [unitId, render] of this._renderMap) {+ const renderType = this._univerInstanceService.getUnitType(unitId);+ if (renderType === type) {+ renderUnits.push(render as RenderUnit);+ }+ }++ return renderUnits;}getCurrentTypeOfRenderer(type: UniverInstanceType): Nullable<RenderUnit> {@@ -196,7 +225,7 @@ export class RenderManagerService extends Disposable implements IRenderManagerSeif (unit) {const type = this._univerInstanceService.getUnitType(unitId);const ctors = this._getRenderControllersForType(type);- renderUnit = new RenderUnit(this._injector, {+ renderUnit = this._injector.createInstance(RenderUnit, {unit,engine,scene,@@ -285,6 +314,8 @@ export class RenderManagerService extends Disposable implements IRenderManagerSeif (shouldDestroyEngine) {engine.dispose();}++ this._renderDisposed$.next(item.unitId);}}diff --git a/packages/engine-render/src/render-manager/render-unit.ts b/packages/engine-render/src/render-manager/render-unit.tsindex d4b60e15e7..1612a9d7f9 100644--- a/packages/engine-render/src/render-manager/render-unit.ts+++ b/packages/engine-render/src/render-manager/render-unit.ts@@ -16,7 +16,7 @@import type { Nullable, UnitModel, UnitType } from '@univerjs/core';import { Disposable } from '@univerjs/core';-import { type Dependency, type DependencyIdentifier, type IDisposable, type Injector, isClassDependencyItem } from '@wendellhu/redi';+import { type Dependency, type DependencyIdentifier, type IDisposable, Inject, Injector, isClassDependencyItem } from '@wendellhu/redi';import type { Engine } from '../engine';import type { Scene } from '../scene';import type { RenderComponentType } from './render-manager.service';@@ -66,15 +66,14 @@ export class RenderUnit extends Disposable implements IRender {get components() { return this._renderContext.components; }constructor(- parentInjector: Injector,- init: Pick<IRenderContext, 'engine' | 'scene' | 'isMainScene' | 'unit' >+ init: Pick<IRenderContext, 'engine' | 'scene' | 'isMainScene' | 'unit' >,+ @Inject(Injector) parentInjector: Injector) {super();this._injector = parentInjector.createChild();-this._renderContext = {- unit: init.unit, // model+ unit: init.unit,unitId: init.unit.getUnitId(),type: init.unit.type,components: new Map(),@@ -87,7 +86,6 @@ export class RenderUnit extends Disposable implements IRender {override dispose() {this._injector.dispose();-super.dispose();}diff --git a/packages/facade/package.json b/packages/facade/package.jsonindex 64d4dff0f0..2c8f8f397d 100644--- a/packages/facade/package.json+++ b/packages/facade/package.json@@ -62,6 +62,7 @@"peerDependencies": {"@univerjs/core": "workspace:*","@univerjs/docs": "workspace:*",+ "@univerjs/docs-ui": "workspace:*","@univerjs/engine-formula": "workspace:*","@univerjs/engine-render": "workspace:*","@univerjs/network": "workspace:*",diff --git a/packages/find-replace/src/services/find-replace.service.ts b/packages/find-replace/src/services/find-replace.service.tsindex 65d9f85d3f..76a4c114d0 100644--- a/packages/find-replace/src/services/find-replace.service.ts+++ b/packages/find-replace/src/services/find-replace.service.ts@@ -45,6 +45,9 @@ export interface IFindMoveParams {/** If the the selection is on the match and then should stay on the match. */stayIfOnMatch?: boolean;+ /** Go the next selection ignoring the current selection's position. */+ ignoreSelection?: boolean;+/*** If this param is true, we should only change matching position without performing focusing.* This usually happens when "moving" is triggered when a document's content changes.@@ -278,11 +281,8 @@ export class FindReplaceModel extends Disposable {return { results: [] };}- const index = this._moveToInitialMatch(findModels, newMatches);- this._state.changeState({- matchesCount: newMatches.length,- matchesPosition: index + 1, // the matches position start from 1- });+ this._moveToInitialMatch(findModels);+ this._state.changeState({ matchesCount: newMatches.length });return { results: newMatches };}@@ -315,8 +315,8 @@ export class FindReplaceModel extends Disposable {.subscribe(([...allMatches]) => {const newMatches = this._matches = allMatches.flat();if (newMatches.length) {- const index = this._moveToInitialMatch(this._findModels, newMatches, true);- this._state.changeState({ matchesCount: newMatches.length, matchesPosition: index + 1 });+ this._moveToInitialMatch(this._findModels, true);+ this._state.changeState({ matchesCount: newMatches.length });this.replaceables$.next(newMatches.filter((m) => m.replaceable) as IReplaceableMatch[]);} else {this._state.changeState({ matchesCount: 0, matchesPosition: 0 });@@ -359,6 +359,12 @@ export class FindReplaceModel extends Disposable {return this._state.matchesPosition > 0 ? this._matches[this._state.matchesPosition - 1] : null;}+ private _markMatch(match: IFindMatch): void {+ const index = this._matches.findIndex((value) => value === match);+ this.currentMatch$.next(match);+ this._state.changeState({ matchesPosition: index + 1 });+ }+moveToNextMatch(): void {if (!this._matchingModel) {return;@@ -367,22 +373,30 @@ export class FindReplaceModel extends Disposable {const loopInCurrentUnit = this._findModels.length === 1;const nextMatch = this._matchingModel.moveToNextMatch({ loop: loopInCurrentUnit });if (nextMatch) {- const index = this._matches.findIndex((value) => value === nextMatch);- this.currentMatch$.next(nextMatch);- this._state.changeState({- matchesPosition: index + 1,- });+ this._markMatch(nextMatch);} else {- // search in the next find model- const indexOfPositionModel = this._findModels.findIndex((m) => m === this._matchingModel);- const nextPositionModel = this._findModels[(indexOfPositionModel + 1) % this._findModels.length]; // TODO: always loop or not- const nextMatch = nextPositionModel.moveToNextMatch();- const index = this._matches.findIndex((value) => value === nextMatch);- this.currentMatch$.next(nextMatch);- this._matchingModel = nextPositionModel;- this._state.changeState({- matchesPosition: index + 1,- });+ const currentModelIndex = this._findModels.findIndex((m) => m === this._matchingModel);+ this._moveToNextUnitMatch(currentModelIndex);+ }+ }++ private _moveToNextUnitMatch(startingIndex: number): void {+ const l = this._findModels.length;+ for (let i = (startingIndex + 1) % l; i !== startingIndex;) {+ const nextPositionModel = this._findModels[i];+ const nextMatch = nextPositionModel.moveToNextMatch({ ignoreSelection: true });+ if (nextMatch) {+ this._matchingModel = nextPositionModel;+ this._markMatch(nextMatch);+ return;+ }++ i = (i + 1) % l;+ }++ if (this._matchingModel) {+ const nextMatch = this._matchingModel.moveToNextMatch({ ignoreSelection: true });+ if (nextMatch) this._markMatch(nextMatch);}}@@ -396,44 +410,45 @@ export class FindReplaceModel extends Disposable {if (nextMatch) {const index = this._matches.findIndex((value) => value === nextMatch);this.currentMatch$.next(nextMatch);- this._state.changeState({- matchesPosition: index + 1,- });+ this._state.changeState({ matchesPosition: index + 1 });} else {- const indexOfPositionModel = this._findModels.findIndex((m) => m === this._matchingModel);- const nextPositionModel =- this._findModels[(indexOfPositionModel - 1 + this._findModels.length) % this._findModels.length];- const nextMatch = nextPositionModel.moveToPreviousMatch();- const index = this._matches.findIndex((value) => value === nextMatch);- this.currentMatch$.next(nextMatch);- this._matchingModel = nextPositionModel;- this._state.changeState({- matchesPosition: index + 1,- });+ const l = this._findModels.length;+ const currentModelIndex = this._findModels.findIndex((m) => m === this._matchingModel);+ for (let i = (currentModelIndex - 1 + l) % l; i !== currentModelIndex;) {+ const nextPositionModel = this._findModels[i];+ const nextMatch = nextPositionModel.moveToPreviousMatch({ ignoreSelection: true });+ if (nextMatch) {+ this._matchingModel = nextPositionModel;+ this._markMatch(nextMatch);+ return;+ }++ i = (i - 1) % l;+ }++ const nextMatch = this._matchingModel.moveToPreviousMatch({ ignoreSelection: true });+ if (nextMatch) this._markMatch(nextMatch);}}- private _moveToInitialMatch(findModels: FindModel[], results: IFindMatch[], noFocus = false): number {+ private _moveToInitialMatch(findModels: FindModel[], noFocus = false): number {const focusedUnitId = this._univerInstanceService.getFocusedUnit()?.getUnitId();if (!focusedUnitId) {return -1;}- const findModelOnFocusUnit = findModels.find((model) => model.unitId === focusedUnitId);- if (findModelOnFocusUnit) {- this._matchingModel = findModelOnFocusUnit;- const nextMatch = findModelOnFocusUnit.moveToNextMatch({ stayIfOnMatch: true, noFocus });- const index = results.findIndex((value) => value === nextMatch);- this.currentMatch$.next(nextMatch);- return index;+ const i = findModels.findIndex((model) => model.unitId === focusedUnitId);+ if (i !== -1) {+ this._matchingModel = findModels[i];+ const nextMatch = this._matchingModel.moveToNextMatch({ stayIfOnMatch: true, noFocus });+ if (nextMatch) {+ this._markMatch(nextMatch);+ return i;+ }}- // otherwise we just simply match the first result- this._matchingModel = findModels[0];- const nextMatch = this._matchingModel.moveToNextMatch({ noFocus });- const matchPosition = this._matches.findIndex((m) => m === nextMatch);- this.currentMatch$.next(nextMatch);- return matchPosition;+ this._moveToNextUnitMatch(i);+ return 0;}}@@ -542,6 +557,7 @@ export class FindReplaceState {get findBy(): FindBy { return this._findBy; }get findCompleted(): boolean { return this._findCompleted; }+ // eslint-disable-next-line max-lines-per-function, complexitychangeState(changes: Partial<IFindReplaceState>): void {let changed = false;const changedState: Partial<IFindReplaceState> = {};diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.tsindex ae87da74bf..48ccffac78 100644--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts@@ -22,8 +22,10 @@ import {LifecycleStages,OnLifecycle,RxDisposable,+ toDisposable,UniverInstanceType,} from '@univerjs/core';+import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { takeUntil } from 'rxjs/operators';@@ -40,6 +42,8 @@ import { fromModule, toModule } from '../../services/rpc/rpc.service';/*** This controller is responsible for syncing data from the primary thread to* the worker thread.+ *+ * Note that only spreadsheets will be synced to the remote calculation instance by default.*/@OnLifecycle(LifecycleStages.Starting, DataSyncPrimaryController)export class DataSyncPrimaryController extends RxDisposable {@@ -66,6 +70,15 @@ export class DataSyncPrimaryController extends RxDisposable {this._syncingMutations.add(mutation.id);}+ /**+ * Only spreadsheets would be synced to the web worker in normal situations. If you would like to+ * sync other types of documents, you should manually call this method with that document's id.+ */+ syncUnit(unitId: string): IDisposable {+ this._syncingUnits.add(unitId);+ return toDisposable(() => this._syncingUnits.delete(unitId));+ }+private _initRPCChannels(): void {// for the worker to callthis._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService));@@ -102,6 +115,7 @@ export class DataSyncPrimaryController extends RxDisposable {this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {const { type, params, id } = commandInfo;const unitId = (params as { unitId: string })?.unitId || '';+if (type === CommandType.MUTATION &&// only sync mutations to the worker thread(!unitId || this._syncingUnits.has(unitId)) &&diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsxindex 2212441e22..380c32a3ef 100644--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx@@ -16,6 +16,7 @@import React, { useEffect, useRef, useState } from 'react';import { Select, Tooltip } from '@univerjs/design';+import { useObservable } from '@univerjs/ui';import { useHighlightRange } from '@univerjs/sheets-ui';import { useDependency } from '@wendellhu/redi/react-bindings';@@ -115,7 +116,7 @@ export const RuleList = (props: IRuleListProps) => {const localeService = useDependency(LocaleService);const conditionalFormattingI18nController = useDependency(ConditionalFormattingI18nController);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const workbook = useObservable(univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET))!;const unitId = workbook.getUnitId();const worksheet = workbook.getActiveSheet();if (!worksheet) {diff --git a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx b/packages/sheets-data-validation/src/views/list-dropdown/index.tsxindex 0be2f5c1b3..61c9587d9d 100644--- a/packages/sheets-data-validation/src/views/list-dropdown/index.tsx+++ b/packages/sheets-data-validation/src/views/list-dropdown/index.tsx@@ -159,6 +159,7 @@ export function ListDropDown(props: IDropdownComponentProps) {visible: false,keycode: KeyCode.ESC,eventType: DeviceInputEventType.Keyboard,+ unitId,});}diff --git a/packages/sheets-drawing-ui/src/basics/transform-position.ts b/packages/sheets-drawing-ui/src/basics/transform-position.tsindex 813dc1ce37..127ea9b306 100644--- a/packages/sheets-drawing-ui/src/basics/transform-position.ts+++ b/packages/sheets-drawing-ui/src/basics/transform-position.ts@@ -68,7 +68,7 @@ export function drawingPositionToTransform(height = 0;}- const skeleton = sheetSkeletonManagerService.getCurrentSkeleton();+ const skeleton = sheetSkeletonManagerService.getCurrentSkeleton()!;const sheetWidth = skeleton.rowHeaderWidth + skeleton.columnTotalWidth;const sheetHeight = skeleton.columnHeaderHeight + skeleton.rowTotalHeight;diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.tsindex 61b8022895..6d65ae312c 100644--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts@@ -14,12 +14,12 @@* limitations under the License.*/-import { ColorKit, CommandType, Disposable, EDITOR_ACTIVATED, fromCallback, groupBy, ICommandService, IContextService, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, replaceInDocumentBody, rotate, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';+import { ColorKit, CommandType, Disposable, EDITOR_ACTIVATED, fromCallback, groupBy, ICommandService, IContextService, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, replaceInDocumentBody, rotate, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService, RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';import type { IFindComplete, IFindMatch, IFindMoveParams, IFindQuery, IFindReplaceProvider, IReplaceAllResult } from '@univerjs/find-replace';import { FindBy, FindDirection, FindModel, FindReplaceController, FindScope, IFindReplaceService } from '@univerjs/find-replace';-import type { ISelectionWithStyle, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams } from '@univerjs/sheets';+import type { ISelectionWithStyle, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams, WorkbookSelections } from '@univerjs/sheets';import { SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';import type { IScrollToCellCommandParams } from '@univerjs/sheets-ui';import { getCoordByCell, getSheetObject, ScrollToCellCommand, SheetSkeletonManagerService } from '@univerjs/sheets-ui';@@ -118,6 +118,8 @@ export class SheetFindModel extends FindModel {get matchesPosition(): number { return this._matchesPosition; }get currentMatch(): Nullable<ISheetCellMatch> { return this._matchesPosition > 0 ? this._matches[this._matchesPosition - 1] : null; }+ private _workbookSelections: WorkbookSelections;+constructor(private readonly _workbook: Workbook,private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@@ -126,9 +128,11 @@ export class SheetFindModel extends FindModel {@ICommandService private readonly _commandService: ICommandService,@IContextService private readonly _contextService: IContextService,@Inject(ThemeService) private readonly _themeService: ThemeService,- @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService+ @Inject(SheetsSelectionsService) _selectionManagerService: SheetsSelectionsService) {super();++ this._workbookSelections = _selectionManagerService.getWorkbookSelections(this.unitId);}override dispose(): void {@@ -256,7 +260,7 @@ export class SheetFindModel extends FindModel {let globalIndex = 0;const matchesByWorksheet = this._matchesByWorksheet.get(activeSheet.getSheetId())!;- const selections = this._selectionManagerService.getCurrentSelections();+ const selections = this._workbookSelections.getCurrentSelections();if (!selections?.length) {match = matchesByWorksheet[0];index = 0;@@ -285,7 +289,7 @@ export class SheetFindModel extends FindModel {const checkShouldFindInSelections = (): boolean => {const currentWorksheet = this._workbook.getActiveSheet();if (!currentWorksheet) return false;- const currentSelections = this._selectionManagerService.getCurrentSelections();+ const currentSelections = this._workbookSelections.getCurrentSelections();const shouldFindInSelections = currentSelections?.some((selection) => !isSelectionSingleCell(selection, currentWorksheet)) ?? false;return shouldFindInSelections;};@@ -301,7 +305,7 @@ export class SheetFindModel extends FindModel {const lastMatch = this.currentMatch; // temporarily store the last match to restore the position after the model changesfindBySelections = checkShouldFindInSelections();- const currentSelections = this._selectionManagerService.getCurrentSelections();+ const currentSelections = this._workbookSelections.getCurrentSelections();const newComplete = findBySelections? this._findInSelections(currentWorksheet, currentSelections as ISelectionWithStyle[], query, unitId): this._findInWorksheet(currentWorksheet, query, unitId);@@ -461,16 +465,6 @@ export class SheetFindModel extends FindModel {return;}- const sheetObjects = this._getSheetObject();- if (!sheetObjects) {- return;- }-- const currentUnitId = this._univerInstanceService.getFocusedUnit()?.getUnitId();- if (currentUnitId !== this._workbook.getUnitId()) {- return;- }-const unitId = this._workbook.getUnitId();const currentRender = this._renderManagerService.getRenderById(unitId);if (currentRender == null) {@@ -545,13 +539,13 @@ export class SheetFindModel extends FindModel {private _focusMatch(match: ISheetCellMatch): void {const subUnitId = match.range.subUnitId;if (subUnitId !== this._workbook.getActiveSheet()?.getSheetId()) {- this._commandService.syncExecuteCommand(SetWorksheetActivateCommand.id,+ this._commandService.executeCommand(SetWorksheetActivateCommand.id,{ unitId: this._workbook.getUnitId(), subUnitId } as ISetWorksheetActivateCommandParams,{ fromFindReplace: true });}- this._commandService.syncExecuteCommand(+ this._commandService.executeCommand(ScrollToCellCommand.id,{ range: match.range.range } as IScrollToCellCommandParams,{ fromFindReplace: true }@@ -583,8 +577,9 @@ export class SheetFindModel extends FindModel {const loop = params?.loop ?? false;const stayIfOnMatch = params?.stayIfOnMatch ?? false;const noFocus = params?.noFocus ?? false;+ const ignoreSelection = params?.ignoreSelection ?? false;- const matchToMove = this._findNextMatch(loop, stayIfOnMatch);+ const matchToMove = this._findNextMatch(loop, stayIfOnMatch, ignoreSelection);if (matchToMove) {const [match, index] = matchToMove;this._matchesPosition = index + 1;@@ -616,8 +611,9 @@ export class SheetFindModel extends FindModel {const loop = params?.loop ?? false;const stayIfOnMatch = params?.stayIfOnMatch ?? false;const noFocus = params?.noFocus ?? false;+ const ignoreSelection = params?.ignoreSelection ?? false;- const matchToMove = this._findPreviousMatch(loop, stayIfOnMatch);+ const matchToMove = this._findPreviousMatch(loop, stayIfOnMatch, ignoreSelection);if (matchToMove) {const [match, index] = matchToMove;this._matchesPosition = index + 1;@@ -641,7 +637,7 @@ export class SheetFindModel extends FindModel {return null;}- private _findPreviousMatch(loop = false, stayIfOnMatch = false): [ISheetCellMatch, number] | null {+ private _findPreviousMatch(loop = false, stayIfOnMatch = false, ignoreSelection = false): [ISheetCellMatch, number] | null {// Technically speaking, there are eight different situations!// Case 1: if there is a current match and the process is very easyif (this.currentMatch) {@@ -660,15 +656,17 @@ export class SheetFindModel extends FindModel {return [this._matches[modded], modded];}- // Case 2: if there is no current match, we should find the next match that is closest to the user's current selection.- // Still need to handle `stayInOnMatch` here.- const selections = this._selectionManagerService.getCurrentSelections();- if (!selections?.length) {- return [this._matches[0], 0];+ // Case 2: ignore current selection or there is no selection+ const lastSelection = this._workbookSelections.getCurrentLastSelection();+ if (ignoreSelection || !lastSelection) {+ const lastIndex = this._matches.length - 1;+ return [this._matches[lastIndex], lastIndex];}+ // Case 3: if there is no current match, we should find the next match that is closest to the user's current selection.+ // Still need to handle `stayInOnMatch` here.if (this._query!.findScope !== FindScope.UNIT) {- return this._findPreviousMatchByRange(this._matches, selections[0].range);+ return this._findPreviousMatchByRange(this._matches, lastSelection.range);}const currentSheetId = this._workbook.getActiveSheet()?.getSheetId();@@ -681,10 +679,10 @@ export class SheetFindModel extends FindModel {return null;}- return this._findPreviousMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, selections[0].range);+ return this._findPreviousMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, lastSelection.range);}- private _findNextMatch(loop = false, stayIfOnMatch = false): [ISheetCellMatch, number] | null {+ private _findNextMatch(loop = false, stayIfOnMatch = false, ignoreSelection = false): [ISheetCellMatch, number] | null {// Technically speaking, there are eight different situations!// Case 1: if there is a current match and the process is very easyif (this.currentMatch) {@@ -703,15 +701,17 @@ export class SheetFindModel extends FindModel {return [this._matches[modded], modded];}- // Case 2: if there is no current match, we should find the next match that is closest to the user's current selection.+ // Case 2:++ // Case 3: if there is no current match, we should find the next match that is closest to the user's current selection.// Still need to handle `stayInOnMatch` here.- const selections = this._selectionManagerService.getCurrentSelections();- if (!selections?.length) {+ const last = this._workbookSelections.getCurrentLastSelection();+ if (ignoreSelection || !last) {return [this._matches[0], 0];}if (this._query!.findScope !== FindScope.UNIT) {- return this._findNextMatchByRange(this._matches, selections[0].range, stayIfOnMatch);+ return this._findNextMatchByRange(this._matches, last.range, stayIfOnMatch);}const currentSheetId = this._workbook.getActiveSheet()?.getSheetId();@@ -724,7 +724,7 @@ export class SheetFindModel extends FindModel {return null;}- return this._findNextMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, selections[0].range);+ return this._findNextMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, last.range);}private _findPreviousWorksheetThatHasAMatch(currentWorksheet: string, loop = false): string | null {@@ -924,20 +924,17 @@ class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvidasync find(query: IFindQuery): Promise<SheetFindModel[]> {this._terminate();- // TODO: If there are multi Workbook instances then we should create `SheetFindModel` for each of them.- // But we don't need to implement that in the foreseeable future.- const currentWorkbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const skeletonManagerService = this._renderManagerService.getRenderById(currentWorkbook.getUnitId())!.with(SheetSkeletonManagerService);-- if (currentWorkbook) {- const sheetFind = this._injector.createInstance(SheetFindModel, currentWorkbook, skeletonManagerService);- this._findModelsByUnitId.set(currentWorkbook.getUnitId(), sheetFind);- const parsedQuery = this._preprocessQuery(query);+ const allWorkbooks = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const parsedQuery = this._preprocessQuery(query);+ const findModels = allWorkbooks.map((workbook) => {+ const skeletonManagerService = this._renderManagerService.getRenderById(workbook.getUnitId())!.with(SheetSkeletonManagerService);+ const sheetFind = this._injector.createInstance(SheetFindModel, workbook, skeletonManagerService);+ this._findModelsByUnitId.set(workbook.getUnitId(), sheetFind);sheetFind.start(parsedQuery);- return [sheetFind];- }+ return sheetFind;+ });- return [];+ return findModels;}terminate(): void {diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex 63b56dc519..a7012de2bc 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -14,6 +14,8 @@* limitations under the License.*/+// FIXME: why so many calling to close the editor here?+import type {DocumentDataModel,ICommandInfo,@@ -41,7 +43,6 @@ import {RANGE_TYPE,Rectangle,ThemeService,- toDisposable,Tools,UniverInstanceType,} from '@univerjs/core';@@ -91,7 +92,7 @@ import {MoveSelectionCommand,SheetSkeletonManagerService,} from '@univerjs/sheets-ui';-import { IContextMenuService, IEditorService, KeyCode, MetaKeys, SetEditorResizeOperation } from '@univerjs/ui';+import { IContextMenuService, IEditorService, KeyCode, MetaKeys, SetEditorResizeOperation, UNI_DISABLE_CHANGING_FOCUS_KEY } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';@@ -166,6 +167,14 @@ export class PromptController extends Disposable {)!.with(RefSelectionsRenderService);}+ /**+ * If there are multiple sheet instances, we should enable or disable all of them.+ */+ private get _allSelectionRenderServices(): RefSelectionsRenderService[] {+ return this._renderManagerService.getAllRenderersOfType(UniverInstanceType.UNIVER_SHEET)+ .map((renderer) => renderer.with(RefSelectionsRenderService));+ }+constructor(@ICommandService private readonly _commandService: ICommandService,@IContextService private readonly _contextService: IContextService,@@ -254,46 +263,44 @@ export class PromptController extends Disposable {private _initialCursorSync() {this.disposeWithMe(- toDisposable(- this._textSelectionManagerService.textSelection$.subscribe((params) => {- if (params?.unitId == null) {- return;- }+ this._textSelectionManagerService.textSelection$.subscribe((params) => {+ if (params?.unitId == null) {+ return;+ }- const editor = this._editorService.getEditor(params.unitId);- if (!editor- || editor.onlyInputContent()- || (editor.isSheetEditor() && this._editorBridgeService.isVisible().visible === false)- ) {- return;- }+ const editor = this._editorService.getEditor(params.unitId);+ if (!editor+ || editor.onlyInputContent()+ || (editor.isSheetEditor() && this._editorBridgeService.isVisible().visible === false)+ ) {+ return;+ }- const onlyInputRange = editor.onlyInputRange();+ const onlyInputRange = editor.onlyInputRange();- // @ts-ignore- if (params?.options?.fromSelection) {- return;- } else {- this._quitSelectingMode();- }+ // @ts-ignore+ if (params?.options?.fromSelection) {+ return;+ } else {+ this._quitSelectingMode();+ }- this._contextSwitch();- this._checkShouldEnterSelectingMode(onlyInputRange);+ this._contextSwitch();+ this._checkShouldEnterSelectingMode(onlyInputRange);- if (this._formulaPromptService.isLockedSelectionChange()) {- return;- }+ if (this._formulaPromptService.isLockedSelectionChange()) {+ return;+ }- this._highlightFormula();+ this._highlightFormula();- if (onlyInputRange) {- return;- }+ if (onlyInputRange) {+ return;+ }- // TODO@Dushusir: use real text info- this._changeFunctionPanelState();- })- )+ // TODO@Dushusir: use real text info+ this._changeFunctionPanelState();+ }));}@@ -378,6 +385,7 @@ export class PromptController extends Disposable {this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, false);+ this._contextService.setContextValue(UNI_DISABLE_CHANGING_FOCUS_KEY, false);this._quitSelectingMode();@@ -394,23 +402,21 @@ export class PromptController extends Disposable {if (selections.length === 0) return;- // Rebuild selections when the selection is changed from cache refs in the formula string (not current selections)!- this._updateRefSelectionStyle(this._isSelectionMovingRefSelections);+ // Update rendering in each selection render service.+ this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));- const selectionControls = this._selectionRenderService.getSelectionControls();+ const selectionControls = this._allSelectionRenderServices.map((s) => s.getSelectionControls()).flat();selectionControls.forEach((c) => {c.disableHelperSelection();-d.add(c.selectionMoving$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));d.add(c.selectionScaling$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));-d.add(c.selectionMoved$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));d.add(c.selectionScaled$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));});}));}- // #region - selecting mode - user can use cursor to select a range on the canvas and move the selection+ // #region - Selecting Mode: user can use cursor to select a range on the canvas and move the selection// with keyboard shortcutsprivate _updateSelecting(selectionsWithStyles: ISelectionWithStyle[], performInsertion: boolean = false) {@@ -425,21 +431,35 @@ export class PromptController extends Disposable {}}+ private _currentlyWorkingRefRenderer: Nullable<RefSelectionsRenderService> = null;private _selectionsChangeDisposables: Nullable<IDisposable>;private _enableRefSelectionsRenderService() {const d = this._selectionsChangeDisposables = new DisposableCollection();+ this._allSelectionRenderServices.forEach((renderer) => {+ d.add(renderer.enableSelectionChanging());- d.add(this._selectionRenderService.enableSelectionChanging());+ // When the current selections change, the ref string is updated without touch `IRefSelectionsService`.+ d.add(renderer.selectionMoving$.subscribe((selections) => {+ this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)));+ }));- // When the current selections change, the ref string is updated without touch `IRefSelectionsService`.+ // When the selection change begins, if other render service has last selection,+ // it should be removed.+ d.add(renderer.selectionMoveStart$.subscribe((selections) => {+ const performInsertion = this._checkClearingLastSelection(renderer);+ this._currentlyWorkingRefRenderer = renderer;+ this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)), performInsertion);+ }));+ });+ }- d.add(this._selectionRenderService.selectionMoving$.subscribe((selections) => {- this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)));- }));+ private _checkClearingLastSelection(renderer: RefSelectionsRenderService): boolean {+ if (this._currentlyWorkingRefRenderer && this._currentlyWorkingRefRenderer !== renderer) {+ this._currentlyWorkingRefRenderer.clearLastSelection();+ return false;+ }- d.add(this._selectionRenderService.selectionMoveStart$.subscribe((selections) => {- this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)), true);- }));+ return true;}private _disposeSelectionsChangeListeners(): void {@@ -478,7 +498,7 @@ export class PromptController extends Disposable {this._previousSequenceNodes = Tools.deepClone(insertNodes);this._formulaPromptService.setSequenceNodes(insertNodes);- const refString = this._getRefString(currentSelection);+ const refString = this._generateRefString(currentSelection);this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);this._selectionRenderService.setSkipLastEnabled(false);@@ -492,71 +512,69 @@ export class PromptController extends Disposable {private _initAcceptFormula() {this.disposeWithMe(- toDisposable(- this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {- const activeRange = this._textSelectionManagerService.getActiveRange();+ this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {+ const activeRange = this._textSelectionManagerService.getActiveRange();- if (activeRange == null) {- this._hideFunctionPanel();- return;- }+ if (activeRange == null) {+ this._hideFunctionPanel();+ return;+ }- const { startOffset } = activeRange;+ const { startOffset } = activeRange;- const lastSequenceNodes = this._formulaPromptService.getSequenceNodes();+ const lastSequenceNodes = this._formulaPromptService.getSequenceNodes();- const nodeIndex = this._formulaPromptService.getCurrentSequenceNodeIndex(startOffset - 2);+ const nodeIndex = this._formulaPromptService.getCurrentSequenceNodeIndex(startOffset - 2);- const node = lastSequenceNodes[nodeIndex];+ const node = lastSequenceNodes[nodeIndex];- if (node == null || typeof node === 'string') {- this._hideFunctionPanel();- return;- }+ if (node == null || typeof node === 'string') {+ this._hideFunctionPanel();+ return;+ }- const difference = formulaString.length - node.token.length;- const newNode = { ...node };+ const difference = formulaString.length - node.token.length;+ const newNode = { ...node };- newNode.token = formulaString;+ newNode.token = formulaString;- newNode.endIndex += difference;+ newNode.endIndex += difference;- lastSequenceNodes[nodeIndex] = newNode;+ lastSequenceNodes[nodeIndex] = newNode;- const isDefinedName = this._descriptionService.hasDefinedNameDescription(formulaString);+ const isDefinedName = this._descriptionService.hasDefinedNameDescription(formulaString);- const isFormulaDefinedName = this._descriptionService.isFormulaDefinedName(formulaString);+ const isFormulaDefinedName = this._descriptionService.isFormulaDefinedName(formulaString);- const formulaStringCount = formulaString.length + 1;+ const formulaStringCount = formulaString.length + 1;- const mustAddBracket = !isDefinedName || isFormulaDefinedName;+ const mustAddBracket = !isDefinedName || isFormulaDefinedName;- if (mustAddBracket) {- lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);- }+ if (mustAddBracket) {+ lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);+ }- for (let i = nodeIndex + 2, len = lastSequenceNodes.length; i < len; i++) {- const node = lastSequenceNodes[i];- if (typeof node === 'string') {- continue;- }+ for (let i = nodeIndex + 2, len = lastSequenceNodes.length; i < len; i++) {+ const node = lastSequenceNodes[i];+ if (typeof node === 'string') {+ continue;+ }- const newNode = { ...node };+ const newNode = { ...node };- newNode.startIndex += formulaStringCount;- newNode.endIndex += formulaStringCount;+ newNode.startIndex += formulaStringCount;+ newNode.endIndex += formulaStringCount;- lastSequenceNodes[i] = newNode;- }+ lastSequenceNodes[i] = newNode;+ }- let selectionIndex = newNode.endIndex + 1;- if (mustAddBracket) {- selectionIndex += 1;- }+ let selectionIndex = newNode.endIndex + 1;+ if (mustAddBracket) {+ selectionIndex += 1;+ }- this._syncToEditor(lastSequenceNodes, selectionIndex, undefined, true, false);- })- )+ this._syncToEditor(lastSequenceNodes, selectionIndex, undefined, true, false);+ }));}@@ -697,6 +715,7 @@ export class PromptController extends Disposable {// Maybe `enterSelectingMode` should be merged with `_enableRefSelectionsRenderService`.this._enableRefSelectionsRenderService();+ this._currentlyWorkingRefRenderer = null;// TODO: remain lastif (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {@@ -780,6 +799,7 @@ export class PromptController extends Disposable {if (config && isFormulaString(config.dataStream)) {this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, true);+ this._contextService.setContextValue(UNI_DISABLE_CHANGING_FOCUS_KEY, true);const lastSequenceNodes =this._lexerTreeBuilder.sequenceNodesBuilder(config.dataStream.replace(/\r/g, '').replace(/\n/g, '')) ||@@ -802,6 +822,7 @@ export class PromptController extends Disposable {this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, false);+ this._contextService.setContextValue(UNI_DISABLE_CHANGING_FOCUS_KEY, false);this._formulaPromptService.disableLockedSelectionChange();@@ -842,8 +863,7 @@ export class PromptController extends Disposable {this._existsSequenceNode = true;const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);bodyList.forEach((body) => (body!.textRuns = textRuns));-- this._refreshSelectionForReference(refSelections);+ this._allSelectionRenderServices.forEach((r) => this._refreshSelectionForReference(r, refSelections));}this._refreshFormulaAndCellEditor(unitIds);@@ -926,28 +946,28 @@ export class PromptController extends Disposable {* Draw the referenced selection text based on the style and token.* @param refSelections*/- private _refreshSelectionForReference(refSelections: IRefSelection[]) {- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();-- const selectionWithStyle: ISelectionWithStyle[] = [];+ private _refreshSelectionForReference(refSelectionRenderService: RefSelectionsRenderService, refSelections: IRefSelection[]) {+ const [unitId, sheetId] = refSelectionRenderService.getLocation();+ const { unitId: selfUnitId, sheetId: selfSheetId } = this._getCurrentUnitIdAndSheetId();+ const isSelf = unitId === selfUnitId && sheetId === selfSheetId;- const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);- const worksheet = workbook?.getSheetBySheetId(sheetId);-- if (worksheet == null) {- return;- }+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId)!;+ const worksheet = workbook.getSheetBySheetId(sheetId)!;let lastRange: Nullable<ISelectionWithStyle> = null;+ const selectionWithStyle: ISelectionWithStyle[] = [];for (let i = 0, len = refSelections.length; i < len; i++) {const refSelection = refSelections[i];const { themeColor, token, refIndex } = refSelection;const gridRange = deserializeRangeWithSheet(token);-const { unitId: refUnitId, sheetName, range: rawRange } = gridRange;+ if (!isSelf && (!refUnitId || !sheetName)) {+ continue;+ }+/*** pro/issues/436* When the range is an entire row or column, NaN values need to be corrected.@@ -998,11 +1018,9 @@ export class PromptController extends Disposable {selectionWithStyle.push(lastRange);}- if (selectionWithStyle.length === 0) {- return;+ if (selectionWithStyle.length) {+ this._refSelectionsService.addSelections(unitId, sheetId, selectionWithStyle);}-- this._refSelectionsService.addSelections(selectionWithStyle);}private _getPrimary(range: IRange, themeColor: string, refIndex: number) {@@ -1061,15 +1079,12 @@ export class PromptController extends Disposable {private _getSheetIdByName(unitId: string, sheetName: string) {const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);-return workbook?.getSheetBySheetName(normalizeSheetName(sheetName))?.getSheetId();}private _getSheetNameById(unitId: string, sheetId: string) {const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);-const sheetName = workbook?.getSheetBySheetId(sheetId)?.getName() || '';-return sheetName;}@@ -1085,11 +1100,13 @@ export class PromptController extends Disposable {};}- private _getOpenForCurrentSheet() {+ // FIXME@Jocs: this internal implementations should be exposed to callers.+ // This method should be moved to EditorService.+ private _getEditorOpenedForSheet() {const documentDataModel = this._univerInstanceService.getCurrentUniverDocInstance()!;const editorUnitId = documentDataModel.getUnitId();const editor = this._editorService.getEditor(editorUnitId);- if (editor == null) {+ if (!editor) {return {openUnitId: null,openSheetId: null,@@ -1106,30 +1123,23 @@ export class PromptController extends Disposable {* Convert the selection range to a ref string for the formula engine, such as A1:B1* @param currentSelection*/- private _getRefString(currentSelection: ISelectionWithStyle) {- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();-+ private _generateRefString(currentSelection: ISelectionWithStyle) {let refUnitId = '';let refSheetName = '';- const { openUnitId, openSheetId } = this._getOpenForCurrentSheet();+ const { unitId, sheetId } = currentSelection.range;+ const { openUnitId, openSheetId } = this._getEditorOpenedForSheet();- if (unitId === openUnitId) {- refUnitId = '';- } else {+ if (unitId !== openUnitId && unitId) {refUnitId = unitId;}- if (sheetId === openSheetId) {- refSheetName = '';- } else {+ if (sheetId !== openSheetId && unitId && sheetId) {refSheetName = this._getSheetNameById(unitId, sheetId);}const { range, primary } = currentSelection;-let { startRow, endRow, startColumn, endColumn } = range;-const { startAbsoluteRefType, endAbsoluteRefType, rangeType } = range;if (primary) {@@ -1266,10 +1276,7 @@ export class PromptController extends Disposable {*/setTimeout(() => {this._textSelectionRenderManager.focus();- this._setRemainCapture();}, 0);-- this._setRemainCapture();}private _fitEditorSize() {@@ -1333,7 +1340,7 @@ export class PromptController extends Disposable {return;}- const refString = this._getRefString(currentSelection);+ const refString = this._generateRefString(currentSelection);this._formulaPromptService.setSequenceNodes(insertNodes);@@ -1405,26 +1412,30 @@ export class PromptController extends Disposable {}}- private _updateRefSelectionStyle(refSelections: IRefSelection[]) {- const controls = this._selectionRenderService.getSelectionControls();- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();+ // FIXME: @wzhudev: this method could be merged with `_refreshSelectionForReference`.+ private _updateRefSelectionStyle(refSelectionRenderService: RefSelectionsRenderService, refSelections: IRefSelection[]) {+ const controls = refSelectionRenderService.getSelectionControls();+ const [unitId, sheetId] = refSelectionRenderService.getLocation();++ const matchedControls = new Set<SelectionShape>();for (let i = 0, len = refSelections.length; i < len; i++) {const refSelection = refSelections[i];const { refIndex, themeColor, token } = refSelection;const rangeWithSheet = deserializeRangeWithSheet(token);const { unitId: refUnitId, sheetName, range } = rangeWithSheet;- if (refUnitId != null && refUnitId.length > 0 && unitId !== refUnitId) {+ if (!refUnitId && refUnitId.length > 0 && unitId !== refUnitId) {continue;}const refSheetId = this._getSheetIdByName(unitId, sheetName.trim());- if (refSheetId != null && refSheetId !== sheetId) {+ if (refSheetId && refSheetId !== sheetId) {continue;}const control = controls.find((c) => {+ // 范围相等方法又写一遍!const { startRow, startColumn, endRow, endColumn, rangeType } = c.getRange();if (rangeType === RANGE_TYPE.COLUMN &&@@ -1458,17 +1469,18 @@ export class PromptController extends Disposable {return false;});- if (!control) {- continue;+ if (control) {+ const style = getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());+ control.updateStyle(style);+ matchedControls.add(control);}-- const style = getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());- control.updateStyle(style);}}private _onSelectionControlChange(toRange: IRangeWithCoord, selectionControl: SelectionShape) {+ // FIXME: change hereconst { skeleton } = this._getCurrentUnitIdAndSheetId();+ // const { unitId, sheetId } = toRange;this._formulaPromptService.enableLockedSelectionChange();const id = selectionControl.selectionStyle?.id;@@ -1480,9 +1492,13 @@ export class PromptController extends Disposable {const primary = getCellInfoInMergeData(startRow, startColumn, skeleton?.mergeData);if (primary) {- const { isMerged, isMergedMainCell, startRow: mergeStartRow,- endRow: mergeEndRow, startColumn: mergeStartColumn,- endColumn: mergeEndColumn,+ const {+ isMerged,+ isMergedMainCell,+ startRow: mergeStartRow,+ endRow: mergeEndRow,+ startColumn: mergeStartColumn,+ endColumn: mergeEndColumn,} = primary;if (@@ -1511,7 +1527,7 @@ export class PromptController extends Disposable {}}- const refString = this._getRefString({+ const refString = this._generateRefString({range: {startRow: Math.min(startRow, endRow),endRow: Math.max(startRow, endRow),@@ -1546,21 +1562,10 @@ export class PromptController extends Disposable {}documentComponent.getSkeleton()?.calculate();-documentComponent.makeDirty();}}- private _setRemainCapture() {- const { unitId } = this._getCurrentUnitIdAndSheetId();-- const editorObject = getEditorObject(unitId, this._renderManagerService);-- const engine = editorObject?.engine;-- engine?.setRemainCapture();- }-private _cursorStateListener() {/*** The user's operations follow the sequence of opening the editor and then moving the cursor.@@ -1594,10 +1599,13 @@ export class PromptController extends Disposable {return;}+ // FIXME: @Jocs: lots of code duplications here+this._editorBridgeService.changeVisible({visible: false,eventType: DeviceInputEventType.Keyboard,keycode,+ unitId: '',});}@@ -1616,6 +1624,7 @@ export class PromptController extends Disposable {visible: false,eventType: DeviceInputEventType.Keyboard,keycode,+ unitId: '',});}@@ -1627,6 +1636,7 @@ export class PromptController extends Disposable {visible: false,eventType: DeviceInputEventType.Keyboard,keycode,+ unitId: '',});}}@@ -1717,6 +1727,7 @@ export class PromptController extends Disposable {visible: false,eventType: DeviceInputEventType.Keyboard,keycode,+ unitId: '',});return;}@@ -1783,29 +1794,28 @@ export class PromptController extends Disposable {private _inputFormulaListener() {this.disposeWithMe(- toDisposable(- this._editorService.inputFormula$.subscribe((param) => {- const { formulaString, editorUnitId } = param;+ this._editorService.inputFormula$.subscribe((param) => {+ const { formulaString, editorUnitId } = param;- if (formulaString.substring(0, 1) !== compareToken.EQUALS) {- return;- }+ if (formulaString.substring(0, 1) !== compareToken.EQUALS) {+ return;+ }- const visibleState = this._editorBridgeService.isVisible();- if (visibleState.visible === false) {- this._editorBridgeService.changeVisible({- visible: true,- eventType: DeviceInputEventType.Dblclick,- });- }+ const visibleState = this._editorBridgeService.isVisible();+ if (visibleState.visible === false) {+ this._editorBridgeService.changeVisible({+ visible: true,+ eventType: DeviceInputEventType.Dblclick,+ unitId: '',+ });+ }- const lastSequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];+ const lastSequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];- this._formulaPromptService.setSequenceNodes(lastSequenceNodes);+ this._formulaPromptService.setSequenceNodes(lastSequenceNodes);- this._syncToEditor(lastSequenceNodes, formulaString.length - 1, editorUnitId);- })- )+ this._syncToEditor(lastSequenceNodes, formulaString.length - 1, editorUnitId);+ }));this.disposeWithMe(diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.tsindex 3830c04083..2c755115ff 100644--- a/packages/sheets-formula/src/formula-ui-plugin.ts+++ b/packages/sheets-formula/src/formula-ui-plugin.ts@@ -20,7 +20,7 @@ import { Inject, Injector } from '@wendellhu/redi';import { fromModule, IRPCChannelService, toModule } from '@univerjs/rpc';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';-import { IRefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';+import { IRefSelectionsService, RefSelectionsService } from '@univerjs/sheets';import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';import { ActiveDirtyController } from './controllers/active-dirty.controller';@@ -87,7 +87,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {const j = this._injector;const dependencies: Dependency[] = [[IFormulaPromptService, { useClass: FormulaPromptService }],- [IRefSelectionsService, { useClass: SheetsSelectionsService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],[IDescriptionService, { useFactory: () => j.createInstance(DescriptionService, this._config?.description) }],[IRegisterFunctionService, { useClass: RegisterFunctionService }],[FormulaRefRangeService],diff --git a/packages/sheets-formula/src/services/prompt.service.ts b/packages/sheets-formula/src/services/prompt.service.tsindex 08164cedac..ce55119585 100644--- a/packages/sheets-formula/src/services/prompt.service.ts+++ b/packages/sheets-formula/src/services/prompt.service.ts@@ -177,12 +177,8 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposableprivate _helping: boolean = false;- private _isInsertRefString: boolean = false;-private _sequenceNodes: Array<string | ISequenceNode> = [];- private _isSelectionMoving = false;-private _isLockedOnSelectionChangeRefString: boolean = false;private _isLockedOnSelectionInsertRefString: boolean = false;diff --git a/packages/sheets-formula/src/services/register-other-formula.service.ts b/packages/sheets-formula/src/services/register-other-formula.service.tsindex a00e3b626a..88010fb446 100644--- a/packages/sheets-formula/src/services/register-other-formula.service.ts+++ b/packages/sheets-formula/src/services/register-other-formula.service.ts@@ -29,6 +29,8 @@ export class RegisterOtherFormulaService extends Disposable {private _formulaChange$ = new Subject<{ unitId: string; subUnitId: string; formulaText: string; formulaId: string }>();public formulaChange$ = this._formulaChange$.asObservable();+ // FIXME: this design could be improved.+private _formulaResult$ = new Subject<Record<string, Record<string, IOtherFormulaResult[]>>>();public formulaResult$ = this._formulaResult$.asObservable();@@ -67,18 +69,20 @@ export class RegisterOtherFormulaService extends Disposable {}private _createFormulaId(unitId: string, subUnitId: string) {- return `sheet.dv_${unitId}_${subUnitId}_${Tools.generateRandomId(8)}`;+ return `formula.${unitId}_${subUnitId}_${Tools.generateRandomId(8)}`;}private _initFormulaRegister() {this._activeDirtyManagerService.register(OtherFormulaMarkDirty.id,- { commandId: OtherFormulaMarkDirty.id,- getDirtyData(commandInfo) {- const params = commandInfo.params as IOtherFormulaMarkDirtyParams;- return {- dirtyUnitOtherFormulaMap: params,- };- } });+ {+ commandId: OtherFormulaMarkDirty.id,+ getDirtyData(commandInfo) {+ const params = commandInfo.params as IOtherFormulaMarkDirtyParams;+ return {+ dirtyUnitOtherFormulaMap: params,+ };+ },+ });this.formulaChange$.pipe(bufferTime(16), filter((list) => !!list.length), map((list) => {return list.reduce((result, cur) => {diff --git a/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.tsindex 40ffe9a5da..5fe27394a2 100644--- a/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts+++ b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts@@ -62,6 +62,10 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService implethis._remainLastEnabled = true; // For ref range selections, we should always remain others.}+ getLocation(): [string, string] {+ return this._skeleton.getLocation();+ }+setRemainLastEnabled(enabled: boolean): void {this._remainLastEnabled = enabled;}@@ -70,6 +74,14 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService implethis._skipLastEnabled = enabled;}+ clearLastSelection(): void {+ const last = this._selectionControls[this._selectionControls.length - 1];+ if (last) {+ last.dispose();+ this._selectionControls.pop();+ }+ }+/*** Call this method and user will be able to select on the canvas to update selections.*/@@ -92,6 +104,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService impleconst listenerDisposables = new DisposableCollection();listenerDisposables.add(spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {+ console.warn('debug start dragging', this._skeleton.worksheet?.getUnitId());this._onPointerDown(evt, spreadsheet.zIndex + 1, RANGE_TYPE.NORMAL, this._getActiveViewport(evt));if (evt.button !== 2) {state.stopPropagation();@@ -167,6 +180,8 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple// Clear already existed selections.this._reset();+ // The selections' style would be colorful here. PromptController would change the color of+ // selections later.for (const selectionWithStyle of selectionsWithStyles) {const selectionData = this.attachSelectionWithCoord(selectionWithStyle);this._addSelectionControlBySelectionData(selectionData);diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.tsindex b6769638c0..974fdc505f 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts@@ -267,12 +267,14 @@ describe('Test auto fill rules in controller', () => {let commandService: ICommandService;let autoFillController: AutoFillController;let themeService: ThemeService;+let getValues: (startRow: number,startColumn: number,endRow: number,endColumn: number) => Array<Array<Nullable<ICellData>>> | undefined;+let getStyles: (startRow: number,startColumn: number,@@ -280,6 +282,7 @@ describe('Test auto fill rules in controller', () => {endColumn: number) => Array<Array<Nullable<IStyleData>>> | undefined;let selectionManagerService: SheetsSelectionsService;+beforeEach(() => {const testBed = createCommandTestBed(TEST_WORKBOOK_DATA, [[ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex f2a0b7f24e..b2368742ad 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -88,7 +88,11 @@ export interface ITestBed {sheet: Workbook;}-export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {+export function createCommandTestBed(+ workbookData?: IWorkbookData,+ dependencies?: Dependency[],+ renderDependencies?: Dependency[]+): ITestBed {const univer = new Univer();const injector = univer.__getInjector();diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.tsindex 9ce2c1a4bc..87b7b52e10 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts@@ -15,12 +15,11 @@*/import type { IWorkbookData } from '@univerjs/core';-import { ICommandService, LocaleType } from '@univerjs/core';+import { Disposable, DisposableCollection, ICommandService, LocaleType, UniverInstanceType } from '@univerjs/core';import { SetFrozenMutation, SetSelectionsOperation } from '@univerjs/sheets';-// FIXME: should not import from the inside of the package-import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { ScrollManagerService } from '../../../services/scroll-manager.service';++import { SheetScrollManagerService } from '../../../services/scroll-manager.service';import { ShortcutExperienceService } from '../../../services/shortcut-experience.service';import {CancelFrozenCommand,@@ -29,6 +28,7 @@ import {SetSelectionFrozenCommand,} from '../set-frozen.command';import { ExpandSelectionCommand, MoveSelectionCommand, SelectAllCommand } from '../set-selection.command';+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';import { createCommandTestBed } from './create-command-test-bed';export function createSelectionCommandTestBed(workbookData?: IWorkbookData) {@@ -50,8 +50,8 @@ export function createSelectionCommandTestBed(workbookData?: IWorkbookData) {export function createFrozenCommandTestBed(workbookData?: IWorkbookData) {const { univer, get, sheet } = createCommandTestBed(workbookData || SIMPLE_SELECTION_WORKBOOK_DATA, [+ [SheetScrollManagerService],[ShortcutExperienceService],- [ScrollManagerService],[IRenderManagerService, { useClass: RenderManagerService }],]);@@ -67,6 +67,33 @@ export function createFrozenCommandTestBed(workbookData?: IWorkbookData) {commandService.registerCommand(c);});+ const unitId = sheet.getUnitId();+ const injector = univer.__getInjector();++ // NOTE: this is a hack. Please refer to ./services/clipboard/__tests__/clipboard-test-bed.ts+ const fakeSheetSkeletonManagerService = new SheetSkeletonManagerService({+ unit: sheet,+ unitId,+ type: UniverInstanceType.UNIVER_SHEET,++ engine: null as any,+ scene: null as any,+ mainComponent: null as any,+ components: null as any,+ isMainScene: true,+ }, injector);++ injector.add([SheetSkeletonManagerService, { useValue: fakeSheetSkeletonManagerService }]);+ injector.get(IRenderManagerService).addRender(unitId, {+ unitId,+ engine: new Disposable() as any,+ scene: new DisposableCollection() as any,+ mainComponent: null as any,+ components: new Map(),+ isMainScene: true,+ with: injector.get.bind(injector),+ });+return {univer,get,diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.tsindex cf65c84813..a5b7fb2fbd 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts@@ -20,7 +20,7 @@ import { SheetsSelectionsService } from '@univerjs/sheets';import type { Injector } from '@wendellhu/redi';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { ScrollManagerService } from '../../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../../services/scroll-manager.service';import {CancelFrozenCommand,SetColumnFrozenCommand,@@ -34,7 +34,7 @@ describe('Test commands used for change selections', () => {let get: Injector['get'];let commandService: ICommandService;let selectionManagerService: SheetsSelectionsService;- let scrollManagerService: ScrollManagerService;+ let scrollManagerService: SheetScrollManagerService;const currentInfo = {unitId: 'test',@@ -98,7 +98,7 @@ describe('Test commands used for change selections', () => {commandService = get(ICommandService);selectionManagerService = get(SheetsSelectionsService);- scrollManagerService = get(ScrollManagerService);+ scrollManagerService = get(SheetScrollManagerService);scrollManagerService.setSearchParamAndRefresh({...currentInfo,});diff --git a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts b/packages/sheets-ui/src/commands/commands/set-frozen.command.tsindex 2c190a7e9b..0ecc8c6baf 100644--- a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts+++ b/packages/sheets-ui/src/commands/commands/set-frozen.command.ts@@ -19,7 +19,7 @@ import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService,import type { ISetFrozenMutationParams } from '@univerjs/sheets';import { getSheetCommandTarget, SetFrozenMutation, SetFrozenMutationFactory, SheetsSelectionsService } from '@univerjs/sheets';-import { ScrollManagerService } from '../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../services/scroll-manager.service';export enum SetSelectionFrozenType {RowColumn = 0,@@ -50,7 +50,7 @@ export const SetSelectionFrozenCommand: ICommand<ISetSelectionFrozenCommandParam}const currentSelection = selections[selections?.length - 1];const { range } = currentSelection;- const scrollManagerService = accessor.get(ScrollManagerService);+ const scrollManagerService = accessor.get(SheetScrollManagerService);const { sheetViewStartRow = 0, sheetViewStartColumn = 0 } = scrollManagerService.getCurrentScrollInfo() || {};let startRow;let startColumn;diff --git a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts b/packages/sheets-ui/src/commands/commands/set-scroll.command.tsindex afbf76dd1a..7d7a6200a0 100644--- a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts+++ b/packages/sheets-ui/src/commands/commands/set-scroll.command.ts@@ -20,7 +20,7 @@ import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceTypimport { getSheetCommandTarget } from '@univerjs/sheets';import { IRenderManagerService } from '@univerjs/engine-render';import type { IScrollManagerParam } from '../../services/scroll-manager.service';-import { ScrollManagerService } from '../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../services/scroll-manager.service';import { SetScrollOperation } from '../operations/scroll.operation';import { SheetsScrollRenderController } from '../../controllers/render-controllers/scroll.render-controller';@@ -47,14 +47,15 @@ export const SetScrollRelativeCommand: ICommand<ISetScrollRelativeCommandParams>// this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY });handler: async (accessor, params: ISetScrollRelativeCommandParams) => {const commandService = accessor.get(ICommandService);- const scrollManagerService = accessor.get(ScrollManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);+ const renderManagerSrv = accessor.get(IRenderManagerService);const target = getSheetCommandTarget(univerInstanceService);if (!target) return false;const { unitId, subUnitId, worksheet } = target;const { xSplit, ySplit } = worksheet.getConfig().freeze;+ const scrollManagerService = renderManagerSrv.getRenderById(unitId)!.with(SheetScrollManagerService);const currentScroll = scrollManagerService.getCurrentScrollInfo();const { offsetX = 0, offsetY = 0 } = params || {};const {@@ -89,12 +90,13 @@ export const ScrollCommand: ICommand<IScrollCommandParams> = {}const univerInstanceService = accessor.get(IUniverInstanceService);- const scrollManagerService = accessor.get(ScrollManagerService);+ const renderManagerSrv = accessor.get(IRenderManagerService);const target = getSheetCommandTarget(univerInstanceService);if (!target) return false;- const { workbook, worksheet } = target;+ const { workbook, worksheet, unitId } = target;+ const scrollManagerService = renderManagerSrv.getRenderById(unitId)!.with(SheetScrollManagerService);const currentScroll: Readonly<Nullable<IScrollManagerParam>> = scrollManagerService.getCurrentScrollInfo();if (!worksheet) {diff --git a/packages/sheets-ui/src/commands/operations/cell-edit.operation.ts b/packages/sheets-ui/src/commands/operations/cell-edit.operation.tsindex db8847c808..85c5afe610 100644--- a/packages/sheets-ui/src/commands/operations/cell-edit.operation.ts+++ b/packages/sheets-ui/src/commands/operations/cell-edit.operation.ts@@ -24,12 +24,11 @@ export const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisibleid: 'sheet.operation.set-cell-edit-visible',type: CommandType.OPERATION,handler: (accessor, params) => {- const editorBridgeService = accessor.get(IEditorBridgeService);-- if (params == null) {+ if (!params) {return false;}+ const editorBridgeService = accessor.get(IEditorBridgeService);editorBridgeService.changeVisible(params);return true;@@ -41,16 +40,18 @@ export const SetCellEditVisibleWithF2Operation: IOperation<IEditorBridgeServiceVtype: CommandType.OPERATION,handler: (accessor, params) => {const commandService = accessor.get(ICommandService);-commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, params);-return true;},};+// FIXME: should not use operation as an event+/*** When the editor is not clicked to change the cursor,* the arrow keys will exit editing and move the cell.+ *+ * @deprecated Should not use operation as an event.*/export const SetCellEditVisibleArrowOperation: IOperation<IEditorBridgeServiceVisibleParam> = {id: 'sheet.operation.set-cell-edit-visible-arrow',diff --git a/packages/sheets-ui/src/commands/operations/scroll.operation.ts b/packages/sheets-ui/src/commands/operations/scroll.operation.tsindex 17ad9ff61b..16f336a54f 100644--- a/packages/sheets-ui/src/commands/operations/scroll.operation.ts+++ b/packages/sheets-ui/src/commands/operations/scroll.operation.ts@@ -17,32 +17,36 @@import type { IOperation } from '@univerjs/core';import { CommandType, IUniverInstanceService } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';import type { IScrollManagerWithSearchParam } from '../../services/scroll-manager.service';-import { ScrollManagerService } from '../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../services/scroll-manager.service';export const SetScrollOperation: IOperation<IScrollManagerWithSearchParam> = {id: 'sheet.operation.set-scroll',type: CommandType.OPERATION,handler: (accessor, params: IScrollManagerWithSearchParam) => {- if (params == null) {+ if (!params) {return false;}- const scrollManagerService = accessor.get(ScrollManagerService);// freeze is handled by set-scroll.command.ts++ const { unitId, sheetId, offsetX, offsetY, sheetViewStartColumn, sheetViewStartRow } = params;const currentService = accessor.get(IUniverInstanceService);- const workbook = currentService.getUniverSheetInstance(params!.unitId);- const worksheet = workbook!.getSheetBySheetId(params!.sheetId);+ const renderManagerService = accessor.get(IRenderManagerService);+ const workbook = currentService.getUniverSheetInstance(unitId);+ const worksheet = workbook!.getSheetBySheetId(sheetId);+ const scrollManagerService = renderManagerService.getRenderById(unitId)!.with(SheetScrollManagerService);const { xSplit, ySplit } = worksheet!.getConfig().freeze;scrollManagerService.setScrollInfoAndEmitEvent({- unitId: params.unitId,- sheetId: params.sheetId,- offsetX: params.offsetX,- offsetY: params.offsetY,- sheetViewStartRow: params.sheetViewStartRow - ySplit,- sheetViewStartColumn: params.sheetViewStartColumn - xSplit,+ unitId,+ sheetId,+ offsetX,+ offsetY,+ sheetViewStartRow: sheetViewStartRow - ySplit,+ sheetViewStartColumn: sheetViewStartColumn - xSplit,});return true;diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.tsindex 6105390047..b7aa6f8758 100644--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts@@ -153,7 +153,7 @@ export class AutoFillController extends Disposable {}if (command.id === RemoveSheetMutation.id) {if ((command.params as IRemoveSheetMutationParams).unitId === this._currentLocation?.unitId &&- (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {+ (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {this._quit();}}@@ -172,11 +172,11 @@ export class AutoFillController extends Disposable {this._autoFillService.setShowMenu(false);}- // eslint-disable-next-line max-lines-per-function+ // eslint-disable-next-line max-lines-per-functionprivate _onSelectionControlFillChanged() {const disposableCollection = new DisposableCollection();const addListener = (disposableCollection: DisposableCollection) => {- // Each range change requires re-listening+ // Each range change requires re-listeningdisposableCollection.dispose();const currentRenderer = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET);@@ -190,10 +190,10 @@ export class AutoFillController extends Disposable {controlSelection.selectionFilled$.subscribe((filled) => {if (filled == null ||- filled.startColumn === -1 ||- filled.startRow === -1 ||- filled.endColumn === -1 ||- filled.endRow === -1+ filled.startColumn === -1 ||+ filled.startRow === -1 ||+ filled.endColumn === -1 ||+ filled.endRow === -1) {return;}@@ -215,8 +215,8 @@ export class AutoFillController extends Disposable {));- // double click to fill range, range length will align to left or right column.- // fill results will be as same as drag operation+ // double click to fill range, range length will align to left or right column.+ // fill results will be as same as drag operationdisposableCollection.add(toDisposable(controlSelection.fillControl.onDblclick$.subscribeEvent(() => {@@ -239,6 +239,7 @@ export class AutoFillController extends Disposable {this._editorBridgeService.changeVisible({visible: false,eventType: DeviceInputEventType.PointerDown,+ unitId: currentRenderer.unitId,});}})@@ -258,7 +259,7 @@ export class AutoFillController extends Disposable {);}- // refill when apply type changed+ // refill when apply type changedprivate _onApplyTypeChanged() {this.disposeWithMe(toDisposable(@@ -269,18 +270,18 @@ export class AutoFillController extends Disposable {);}- // eslint-disable-next-line max-lines-per-function+ // eslint-disable-next-line max-lines-per-functionprivate _triggerAutoFill(source: IRange, selection: IRange) {- // if source range === dest range, do nothing;+ // if source range === dest range, do nothing;if (source.startColumn === selection.startColumn &&- source.startRow === selection.startRow &&- source.endColumn === selection.endColumn &&- source.endRow === selection.endRow+ source.startRow === selection.startRow &&+ source.endColumn === selection.endColumn &&+ source.endRow === selection.endRow) {return;}- // situation 1: drag to smaller range, horizontally.+ // situation 1: drag to smaller range, horizontally.if (selection.endColumn < source.endColumn && selection.endColumn > source.startColumn) {this._commandService.executeCommand(AutoClearContentCommand.id, {clearRange: {@@ -293,7 +294,7 @@ export class AutoFillController extends Disposable {});return;}- // situation 2: drag to smaller range, vertically.+ // situation 2: drag to smaller range, vertically.if (selection.endRow < source.endRow && selection.endRow > source.startRow) {this._commandService.executeCommand(AutoClearContentCommand.id, {clearRange: {@@ -306,9 +307,9 @@ export class AutoFillController extends Disposable {});return;}- // situation 3: drag to larger range, expand to fill+ // situation 3: drag to larger range, expand to fill- // save ranges+ // save rangesconst target = {startRow: selection.startRow,endRow: selection.endRow,@@ -382,11 +383,11 @@ export class AutoFillController extends Disposable {private _handleDbClickFill(source: IRange) {const selection = this._detectFillRange(source);- // double click only works when dest range is longer than source range+ // double click only works when dest range is longer than source rangeif (selection.endRow <= source.endRow) {return;}- // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')+ // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')this._triggerAutoFill(source, selection);}@@ -400,7 +401,7 @@ export class AutoFillController extends Disposable {const maxRow = worksheet.getMaxRows() - 1;const maxColumn = worksheet.getMaxColumns() - 1;let detectEndRow = endRow;- // left column first, or consider right column.+ // left column first, or consider right column.if (startColumn > 0 && matrix.getValue(startRow, startColumn - 1)?.v != null) {let cur = startRow;while (matrix.getValue(cur, startColumn - 1)?.v != null && cur < maxRow) {@@ -439,7 +440,7 @@ export class AutoFillController extends Disposable {this._commandService.executeCommand(AutoFillCommand.id, { unitId: this._currentLocation?.unitId, subUnitId: this._currentLocation?.subUnitId });}- // calc apply data according to copy data and direction+ // calc apply data according to copy data and directionprivate _getApplyData(copyDataPiece: ICopyDataPiece,csLen: number,@@ -464,15 +465,15 @@ export class AutoFillController extends Disposable {applyDataInTypes[r.type] = [];});- // calc cell data to apply+ // calc cell data to applyrules.forEach((r) => {const { type, applyFunctions: customApplyFunctions = {} } = r;const copyDataInType = copyDataPiece[type];if (!copyDataInType) {return;}- // copyDataInType is an array of copy-squads in same types- // a copy-squad is an array of continuous cells that has the same type, e.g. [1, 3, 5] is a copy squad, but [1, 3, ab, 5] will be divided into two copy-squads+ // copyDataInType is an array of copy-squads in same types+ // a copy-squad is an array of continuous cells that has the same type, e.g. [1, 3, 5] is a copy squad, but [1, 3, ab, 5] will be divided into two copy-squadscopyDataInType.forEach((copySquad) => {const s = getLenS(copySquad.index, rsd);const len = copySquad.index.length * num + s;@@ -489,7 +490,7 @@ export class AutoFillController extends Disposable {});});- // calc index+ // calc indexfor (let x = 0; x < asLen; x++) {rules.forEach((r) => {const { type } = r;@@ -516,7 +517,7 @@ export class AutoFillController extends Disposable {const { data } = copySquad;const isReverse = direction === Direction.UP || direction === Direction.LEFT;- // according to applyType, apply functions. if customApplyFunctions is provided, use it instead of default apply functions+ // according to applyType, apply functions. if customApplyFunctions is provided, use it instead of default apply functionsif (applyType === APPLY_TYPE.COPY) {const custom = customApplyFunctions?.[APPLY_TYPE.COPY];if (custom) {@@ -531,7 +532,7 @@ export class AutoFillController extends Disposable {return custom(copySquad, len, direction, copyDataPiece);}isReverse && data.reverse();- // special rules, if not provide custom SERIES apply functions, will be applied as copy+ // special rules, if not provide custom SERIES apply functions, will be applied as copyif (customApplyFunctions?.[APPLY_TYPE.COPY]) {return customApplyFunctions[APPLY_TYPE.COPY](copySquad, len, direction, copyDataPiece);}@@ -574,7 +575,7 @@ export class AutoFillController extends Disposable {};aArray.forEach((a) => {- // a copyDataPiece is an array of original cells in same column or row, depending on direction (horizontal or vertical)+ // a copyDataPiece is an array of original cells in same column or row, depending on direction (horizontal or vertical)const copyDataPiece = this._getEmptyCopyDataPiece();const prevData: IRuleConfirmedData = {type: undefined,@@ -705,7 +706,7 @@ export class AutoFillController extends Disposable {private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) {const { source, target } = location;- // cache original data of apply range+ // cache original data of apply rangeconst worksheet = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();@@ -715,7 +716,7 @@ export class AutoFillController extends Disposable {}const currentCellDatas = worksheet.getCellMatrix();- // cache the original data in currentCellDatas in apply range for later use / refill+ // cache the original data in currentCellDatas in apply range for later use / refillconst applyData: Nullable<ICellData>[][] = [];target.rows.forEach((i) => {const row: Nullable<ICellData>[] = [];@@ -736,8 +737,8 @@ export class AutoFillController extends Disposable {return this._getPreferredApplyType(this._copyData);}- // auto fill entry- // eslint-disable-next-line max-lines-per-function+ // 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[] = [];@@ -809,7 +810,7 @@ export class AutoFillController extends Disposable {});}- // deal with styles+ // deal with styleslet applyMergeRanges: IRange[] = [];const style = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getStyles();if (hasStyle) {@@ -850,7 +851,7 @@ export class AutoFillController extends Disposable {const accessor = {get: this._injector.get.bind(this._injector),};- // delete cross merge+ // delete cross mergeconst deleteMergeRanges: IRange[] = [];const mergeData = this._univerInstanceService.getUniverSheetInstance(unitId)@@ -878,7 +879,7 @@ export class AutoFillController extends Disposable {undos.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });}- // clear range value+ // clear range valueconst clearMutationParams: ISetRangeValuesMutationParams = {subUnitId,unitId,@@ -889,11 +890,11 @@ export class AutoFillController extends Disposable {clearMutationParams);- // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });+ // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams });undos.push({ id: SetRangeValuesMutation.id, params: undoClearMutationParams });- // set range value+ // set range valueconst cellValue = new ObjectMatrix<ICellData>();targetRows.forEach((row, rowIndex) => {targetCols.forEach((col, colIndex) => {@@ -917,7 +918,7 @@ export class AutoFillController extends Disposable {undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });- // add worksheet merge+ // add worksheet mergeif (applyMergeRanges?.length) {const ranges = getAddMergeMutationRangeByType(applyMergeRanges);@@ -946,7 +947,7 @@ export class AutoFillController extends Disposable {return copyData.every((copyDataPiece) =>Object.keys(copyDataPiece).every((type) => (copyDataPiece[type as DATA_TYPE]?.length === 0- || [DATA_TYPE.OTHER, DATA_TYPE.FORMULA].includes(type as DATA_TYPE)+ || [DATA_TYPE.OTHER, DATA_TYPE.FORMULA].includes(type as DATA_TYPE))));@@ -957,9 +958,9 @@ export class AutoFillController extends Disposable {const preferCopy = copyData.every((copyDataPiece) =>Object.keys(copyDataPiece).every((type) => (copyDataPiece[type as DATA_TYPE]?.length === 0- || (copyDataPiece[type as DATA_TYPE]?.length === 1- && copyDataPiece[type as DATA_TYPE][0].data.length === 1- && DATA_TYPE.NUMBER === type as DATA_TYPE)+ || (copyDataPiece[type as DATA_TYPE]?.length === 1+ && copyDataPiece[type as DATA_TYPE][0].data.length === 1+ && DATA_TYPE.NUMBER === type as DATA_TYPE))));diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex 89cb43cc02..8f45067be0 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -18,12 +18,7 @@import type { DocumentDataModel, ICellData, ICommandInfo, IDocumentBody, IDocumentData, IPosition, Nullable, Workbook } from '@univerjs/core';import {- CellValueType,- DEFAULT_EMPTY_DOCUMENT_VALUE,- Direction,- Disposable,- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,- EDITOR_ACTIVATED,+ CellValueType, DEFAULT_EMPTY_DOCUMENT_VALUE, Direction, Disposable, DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, EDITOR_ACTIVATED,FOCUSING_EDITOR_BUT_HIDDEN,FOCUSING_EDITOR_INPUT_FORMULA,FOCUSING_EDITOR_STANDALONE,@@ -40,6 +35,7 @@ import {LocaleService,toDisposable,Tools,+ UniverInstanceType,VerticalAlign,WrapStrategy,} from '@univerjs/core';@@ -65,7 +61,9 @@ import {ScrollBar,} from '@univerjs/engine-render';import { IEditorService, KeyCode, SetEditorResizeOperation } from '@univerjs/ui';+import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';+import type { WorkbookSelections } from '@univerjs/sheets';import { ClearSelectionFormatCommand, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';import { distinctUntilChanged, filter } from 'rxjs';import { LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';@@ -103,17 +101,23 @@ export class EditingRenderController extends Disposable implements IRenderModule*/private _cursorChange: CursorChange = CursorChange.InitialState;+ /** If the corresponding unit is active and prepared for editing. */+ private _isUnitEditing = false;++ private _workbookSelections: WorkbookSelections;++ private _d: Nullable<IDisposable>;+constructor(private readonly _context: IRenderContext<Workbook>,+ @Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,@IContextService private readonly _contextService: IContextService,- /** @deprecated This controller should not directly use univerInstanceService. Instead, it should call editor service. */- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,- @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,@ICommandService private readonly _commandService: ICommandService,@@ -123,59 +127,91 @@ export class EditingRenderController extends Disposable implements IRenderModule) {super();- this._init();- }+ this._workbookSelections = selectionManagerService.getWorkbookSelections(this._context.unitId);- private _init() {- this._initialEditFocusListener();- this._initialKeyboardListener();- this._initialCursorSync();- this._listenEditorFocus();- this._commandExecutedListener();+ // EditingRenderController is per unit. It should only handle keyboard events when the unit is+ // the current of its type.+ this.disposeWithMe(this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {+ if (workbook?.getUnitId() === this._context.unitId) {+ this._d = this._init();+ } else {+ this._disposeCurrent();++ // Force ending editor when he switch to another workbook.+ if (this._isUnitEditing) {+ this._handleEditorInvisible({+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode: KeyCode.ESC,+ unitId: this._context.unitId,+ });++ this._isUnitEditing = false;+ }+ }+ }));this._initEditorVisibilityListener();- this._cursorStateListener();+ }++ override dispose(): void {+ super.dispose();++ this._disposeCurrent();+ }++ private _disposeCurrent(): void {+ this._d?.dispose();+ this._d = null;+ }++ private _init(): IDisposable {+ const d = new DisposableCollection();+ this._subscribeToCurrentCell(d);+ this._initialKeyboardListener(d);+ this._initialCursorSync(d);+ this._listenEditorFocus(d);+ this._commandExecutedListener(d);+ this._cursorStateListener(d);+ return d;}private _initEditorVisibilityListener(): void {this.disposeWithMe(this._editorBridgeService.visible$.pipe(distinctUntilChanged((prev, curr) => prev.visible === curr.visible)).subscribe((param) => {- param.visible ? this._handleEditorVisible(param) : this._handleEditorInvisible(param);+ if (param.unitId === this._context.unitId && param.visible) {+ this._isUnitEditing = true;+ this._handleEditorVisible(param);+ } else if (this._isUnitEditing) {+ this._handleEditorInvisible(param);+ this._isUnitEditing = false;+ }}));}- private _listenEditorFocus() {+ private _listenEditorFocus(d: DisposableCollection) {const renderConfig = this._getEditorObject();+ if (!renderConfig) return;- if (renderConfig == null) {- return;- }+ d.add(renderConfig.document.onPointerDown$.subscribeEvent(() => {+ // fix https://github.com/dream-num/univer/issues/628, need to recalculate the cell editor size after+ // it acquire focus.+ if (this._isUnitEditing && this._editorBridgeService.isVisible()) {+ const param = this._editorBridgeService.getEditCellState();+ const editorId = this._editorBridgeService.getCurrentEditorId();- this.disposeWithMe(- toDisposable(- renderConfig.document.onPointerDown$.subscribeEvent(() => {- // fix https://github.com/dream-num/univer/issues/628, need to recalculate the cell editor size after it acquire focus.- if (this._editorBridgeService.isVisible()) {- const param = this._editorBridgeService.getEditCellState();- const editorId = this._editorBridgeService.getCurrentEditorId();-- if (param == null || editorId == null || !this._editorService.isSheetEditor(editorId)) {- return;- }-- const skeleton = this._getEditorSkeleton(editorId);- if (!skeleton) {- return;- }-- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;-- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);- }- })- )- );+ if (!param || !editorId || !this._editorService.isSheetEditor(editorId)) {+ return;+ }++ const skeleton = this._getEditorSkeleton(editorId);+ if (!skeleton) return;++ const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;+ this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);+ }+ }));}private _getEditorSkeleton(editorId: string) {@@ -186,52 +222,50 @@ export class EditingRenderController extends Disposable implements IRenderModulereturn this._renderManagerService.getRenderById(editorId)?.with(DocSkeletonManagerService).getViewModel();}- private _initialCursorSync() {- this.disposeWithMe(- this._cellEditorManagerService.focus$.pipe(filter((f) => !!f)).subscribe(() => {- this._textSelectionRenderManager.sync();- })- );+ private _initialCursorSync(d: DisposableCollection) {+ d.add(this._cellEditorManagerService.focus$.pipe(filter((f) => !!f)).subscribe(() => {+ this._textSelectionRenderManager.sync();+ }));}- private _initialEditFocusListener() {- this.disposeWithMe(- // TODO: After the sheet dispose, recreate the sheet, the first cell edit may be unsuccessful,- // it should be the editor initialization late, and we need to pay attention to this problem in the future.- this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {- if (editCellState == null || this._editorBridgeService.isForceKeepVisible()) {- return;- }-- const { position, documentLayoutObject, scaleX, editorUnitId } = editCellState;- const editorObject = this._getEditorObject();- if (editorObject == null || this._contextService.getContextValue(FOCUSING_EDITOR_STANDALONE) === true || this._contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE) === true) {- return;- }-- const { startX, endX } = position;- const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;- const { vertexAngle: angle } = convertTextRotation(textRotation);- documentModel!.updateDocumentId(editorUnitId);+ /**+ * Should update current editing cell info when selection is changed.+ * @param d DisposableCollection+ */+ private _subscribeToCurrentCell(d: DisposableCollection) {+ // TODO: After the sheet dispose, recreate the sheet, the first cell edit may be unsuccessful,+ // it should be the editor initialization late, and we need to pay attention to this problem in the future.+ d.add(this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {+ if (editCellState == null || this._editorBridgeService.isForceKeepVisible()) {+ return;+ }- if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {- documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);- }+ const { position, documentLayoutObject, scaleX, editorUnitId } = editCellState;+ if (+ this._contextService.getContextValue(FOCUSING_EDITOR_STANDALONE) ||+ this._contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)+ ) {+ return;+ }- this._univerInstanceService.changeDoc(editorUnitId, documentModel!);+ const { startX, endX } = position;+ const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;+ const { vertexAngle: angle } = convertTextRotation(textRotation);+ documentModel!.updateDocumentId(editorUnitId);- this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, true);+ if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {+ documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);+ }- this._textSelectionManagerService.replaceTextRanges([- {- startOffset: 0,- endOffset: 0,- },- ]);+ this._instanceSrv.changeDoc(editorUnitId, documentModel!);+ this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, true);+ this._textSelectionManagerService.replaceTextRanges([{+ startOffset: 0,+ endOffset: 0,+ }]);- this._textSelectionRenderManager.activate(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);- })- );+ this._textSelectionRenderManager.activate(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);+ }));}private _fitTextSize(@@ -380,7 +414,7 @@ export class EditingRenderController extends Disposable implements IRenderModulelet { startX, startY } = actualRangeWithCoord;- const { document: documentComponent, scene, engine } = editorObject;+ const { document: documentComponent, scene, engine: docEngine } = editorObject;const viewportMain = scene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);@@ -440,12 +474,17 @@ export class EditingRenderController extends Disposable implements IRenderModule* When modifying the selection area for a formula, it is necessary to add a setTimeout to ensure successful updating.*/requestIdleCallback(() => {- engine.resizeBySize(+ docEngine.resizeBySize(fixLineWidthByScale(editorWidth, precisionScaleX),fixLineWidthByScale(physicHeight, precisionScaleY));});+ const canvasElement = this._context.engine.getCanvasElement();+ const canvasBoundingRect = canvasElement.getBoundingClientRect();+ startX += canvasBoundingRect.left;+ // startY += canvasBoundingRect.top;+// Update cell editor container position and size.this._cellEditorManagerService.setState({startX,@@ -631,19 +670,21 @@ export class EditingRenderController extends Disposable implements IRenderModule}}- private _initialKeyboardListener() {- this.disposeWithMe(- this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {- const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);- const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);-- // TODO@Jocs: should get editor instead of current doc- const unitId = this._univerInstanceService.getCurrentUniverDocInstance()?.getUnitId();- if (unitId && isFocusSheets && !isFocusFormulaEditor && this._editorService.isSheetEditor(unitId)) {- this._showEditorByKeyboard(config);- }- })- );+ /**+ * Should activate the editor when the user inputs text.+ * @param d DisposableCollection+ */+ private _initialKeyboardListener(d: DisposableCollection) {+ d.add(this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {+ const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);+ const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);++ // TODO@Jocs: should get editor instead of current doc+ const unitId = this._instanceSrv.getCurrentUniverDocInstance()?.getUnitId();+ if (unitId && isFocusSheets && !isFocusFormulaEditor && this._editorService.isSheetEditor(unitId)) {+ this._showEditorByKeyboard(config);+ }+ }));}private _showEditorByKeyboard(config: Nullable<IEditorInputConfig>) {@@ -657,87 +698,82 @@ export class EditingRenderController extends Disposable implements IRenderModulevisible: true,eventType: DeviceInputEventType.Keyboard,keycode: event.which,+ unitId: this._context.unitId,});}/*** Listen to document edits to refresh the size of the sheet editor, not for normal editor.*/- private _commandExecutedListener() {+ private _commandExecutedListener(d: DisposableCollection) {const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (updateCommandList.includes(command.id)) {- const params = command.params as IRichTextEditingMutationParams;- const { unitId: commandUnitId } = params;+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (updateCommandList.includes(command.id)) {+ const params = command.params as IRichTextEditingMutationParams;+ const { unitId: commandUnitId } = params;- if (!this._editorService.isSheetEditor(commandUnitId)) {- return;- }+ if (!this._editorService.isSheetEditor(commandUnitId)) {+ return;+ }- const editorId = this._editorBridgeService.getCurrentEditorId();- if (editorId == null) {- return;- }+ const editorId = this._editorBridgeService.getCurrentEditorId();+ if (editorId == null) {+ return;+ }- const skeleton = this._getEditorSkeleton(editorId);- if (skeleton == null) {- return;- }+ const skeleton = this._getEditorSkeleton(editorId);+ if (skeleton == null) {+ return;+ }- this._editorBridgeService.changeEditorDirty(true);+ this._editorBridgeService.changeEditorDirty(true);- const param = this._editorBridgeService.getEditCellState();- if (param == null) {- return;- }+ const param = this._editorBridgeService.getEditCellState();+ if (param == null) {+ return;+ }- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;+ const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);- }- })- );+ this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);+ }+ }));- this.disposeWithMe(- // Use fix https://github.com/dream-num/univer/issues/1231.- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === ClearSelectionFormatCommand.id) {- this._editorBridgeService.refreshEditCellState();- }- })- );+ // Use fix https://github.com/dream-num/univer/issues/1231.+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === ClearSelectionFormatCommand.id) {+ this._editorBridgeService.refreshEditCellState();+ }+ }));const closeEditorOperation = [SetCellEditVisibleArrowOperation.id];- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (closeEditorOperation.includes(command.id)) {- const params = command.params as IEditorBridgeServiceVisibleParam & { isShift: boolean };- const { keycode, isShift } = params;-- /**- * After the user enters the editor and actively moves the editor selection area with the mouse,- * the up, down, left, and right keys can no longer switch editing cells,- * but move the cursor within the editor instead.- */- if (keycode != null &&- (this._cursorChange === CursorChange.CursorChange || this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR))- ) {- this._moveInEditor(keycode, isShift);- return;- }-- // TODO@Jocs: After we merging editor related controllers, this seems verbose.- // We can directly call SetRangeValues here.- this._editorBridgeService.changeVisible(params);+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (closeEditorOperation.includes(command.id)) {+ const params = command.params as IEditorBridgeServiceVisibleParam & { isShift: boolean };+ const { keycode, isShift } = params;++ /**+ * After the user enters the editor and actively moves the editor selection area with the mouse,+ * the up, down, left, and right keys can no longer switch editing cells,+ * but move the cursor within the editor instead.+ */+ if (keycode != null &&+ (this._cursorChange === CursorChange.CursorChange || this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR))+ ) {+ this._moveInEditor(keycode, isShift);+ return;}- if (command.id === SetCellEditVisibleWithF2Operation.id) {- this._cursorChange = CursorChange.CursorChange;- }- })- );+ // TODO@Jocs: After we merging editor related controllers, this seems verbose.+ // We can directly call SetRangeValues here.+ this._editorBridgeService.changeVisible(params);+ }++ if (command.id === SetCellEditVisibleWithF2Operation.id) {+ this._cursorChange = CursorChange.CursorChange;+ }+ }));}private _setOpenForCurrent(unitId: Nullable<string>, sheetId: Nullable<string>) {@@ -777,25 +813,19 @@ export class EditingRenderController extends Disposable implements IRenderModuleconst editorIsDirty = this._editorBridgeService.getEditorDirty();if (editorIsDirty === false) {this._moveCursor(keycode);-return;}- const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);- const worksheet = workbook?.getActiveSheet();-- if (worksheet == null) {- return;- }-- const workbookId = workbook!.getUnitId();+ const workbook = this._context.unit;+ const worksheet = workbook.getActiveSheet();+ const workbookId = this._context.unitId;const worksheetId = worksheet.getSheetId();+ // Reselect the current selections, when exist cell editor by press ESC.Iif (keycode === KeyCode.ESC) {- const selections = this._selectionManagerService.getCurrentSelections();- // Reselect the current selections, when exist cell editor by press ESC.+ const selections = this._workbookSelections.getCurrentSelections();if (selections) {this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {- unitId: workbookId,+ unitId: this._context.unit,subUnitId: worksheetId,selections,});@@ -811,9 +841,8 @@ export class EditingRenderController extends Disposable implements IRenderModule(model) => this._resourceLoaderService.saveDoc(model));- if (cellData == null) {+ if (!cellData) {this._moveCursor(keycode);-return;}@@ -918,28 +947,19 @@ export class EditingRenderController extends Disposable implements IRenderModule}}- private _cursorStateListener() {- /**- * The user's operations follow the sequence of opening the editor and then moving the cursor.- * The logic here predicts the user's first cursor movement behavior based on this rule- */-- const editorObject = this._getEditorObject();- if (editorObject == null) {- return;- }-+ /**+ * The user's operations follow the sequence of opening the editor and then moving the cursor.+ * The logic here predicts the user's first cursor movement behavior based on this rule+ */+ private _cursorStateListener(d: DisposableCollection) {+ const editorObject = this._getEditorObject()!;const { document: documentComponent } = editorObject;- this.disposeWithMe(- toDisposable(- documentComponent.onPointerDown$.subscribeEvent(() => {- if (this._cursorChange === CursorChange.StartEditor) {- this._cursorChange = CursorChange.CursorChange;- }- })- )- );+ d.add(toDisposable(documentComponent.onPointerDown$.subscribeEvent(() => {+ if (this._cursorChange === CursorChange.StartEditor) {+ this._cursorChange = CursorChange.CursorChange;+ }+ })));}// TODO: @JOCS, is it necessary to move these commands MoveSelectionOperation\MoveCursorOperation to shortcut? and use multi-commands?@@ -1047,3 +1067,4 @@ function isRichText(body: IDocumentBody) {customBlocks.length > 0);}+diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.tsindex 52ea89a899..f9cb309d28 100644--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts@@ -30,8 +30,8 @@ import {LifecycleStages,OnLifecycle,RxDisposable,- toDisposable,Tools,+ UniverInstanceType,} from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import {@@ -129,9 +129,9 @@ export class FormulaEditorController extends RxDisposable {if (isFocusButHidden) {this._univerInstanceService.setCurrentUnitForType(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);-this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);+ const currentSheet = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);@@ -141,6 +141,7 @@ export class FormulaEditorController extends RxDisposable {this._editorBridgeService.changeVisible({visible: true,eventType: DeviceInputEventType.PointerDown,+ unitId: currentSheet?.getUnitId() ?? '',});}@@ -195,22 +196,21 @@ export class FormulaEditorController extends RxDisposable {}this.disposeWithMe(- toDisposable(- documentComponent.onPointerDown$.subscribeEvent(() => {- // When clicking on the formula bar, the cell editor also needs to enter the edit state- const visibleState = this._editorBridgeService.isVisible();- if (visibleState.visible === false) {- this._editorBridgeService.changeVisible({- visible: true,- eventType: DeviceInputEventType.Dblclick,- });- }+ documentComponent.onPointerDown$.subscribeEvent(() => {+ // When clicking on the formula bar, the cell editor also needs to enter the edit state+ const visibleState = this._editorBridgeService.isVisible();+ if (visibleState.visible === false) {+ this._editorBridgeService.changeVisible({+ visible: true,+ eventType: DeviceInputEventType.Dblclick,+ unitId,+ });+ }- // Open the normal editor first, and then we mark formula editor as activated.- this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);- this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);- })- )+ // Open the normal editor first, and then we mark formula editor as activated.+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);+ this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);+ }));}diff --git a/packages/sheets-ui/src/controllers/hover-render.controller.ts b/packages/sheets-ui/src/controllers/hover-render.controller.tsindex 1b632a373a..573598bb5d 100644--- a/packages/sheets-ui/src/controllers/hover-render.controller.ts+++ b/packages/sheets-ui/src/controllers/hover-render.controller.ts@@ -21,14 +21,14 @@ 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';+import { SheetScrollManagerService } from '../services/scroll-manager.service';export class HoverRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(HoverManagerService) private _hoverManagerService: HoverManagerService,@Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,- @Inject(ScrollManagerService) private _scrollManagerService: ScrollManagerService+ @Inject(SheetScrollManagerService) private _scrollManagerService: SheetScrollManagerService) {super();diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.tsindex 86fa2a3243..576ffbeaeb 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-init.controller.ts@@ -278,42 +278,44 @@ export class SheetPermissionInitController extends Disposable {this._worksheetProtectionRuleModel.changeRuleInitState(false);- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();+ const workbooks = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ workbooks.forEach((workbook) => {+ const unitId = workbook.getUnitId();- getAllWorkbookPermissionPoint().forEach((F) => {- let instance = new F(unitId);- if (_map.has(instance.id)) {- instance = _map.get(instance.id) as any;- }- this._permissionService.addPermissionPoint(instance);- });-- workbook.getSheets().forEach((sheet) => {- const subUnitId = sheet.getSheetId();- [...getAllWorksheetPermissionPoint(), ...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {- let instance = new F(unitId, subUnitId);+ getAllWorkbookPermissionPoint().forEach((F) => {+ let instance = new F(unitId);if (_map.has(instance.id)) {instance = _map.get(instance.id) as any;}this._permissionService.addPermissionPoint(instance);});- const ruleList = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);- ruleList.forEach((rule) => {- getAllRangePermissionPoint().forEach((F) => {- let instance = new F(unitId, subUnitId, rule.permissionId);+ workbook.getSheets().forEach((sheet) => {+ const subUnitId = sheet.getSheetId();+ [...getAllWorksheetPermissionPoint(), ...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {+ let instance = new F(unitId, subUnitId);if (_map.has(instance.id)) {instance = _map.get(instance.id) as any;}this._permissionService.addPermissionPoint(instance);});++ const ruleList = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);+ ruleList.forEach((rule) => {+ getAllRangePermissionPoint().forEach((F) => {+ let instance = new F(unitId, subUnitId, rule.permissionId);+ if (_map.has(instance.id)) {+ instance = _map.get(instance.id) as any;+ }+ this._permissionService.addPermissionPoint(instance);+ });+ });});- });- this.initWorkbookPermissionChange();- this._initWorksheetPermissionFromSnapshot();- this._initRangePermissionFromSnapshot();+ this.initWorkbookPermissionChange();+ this._initWorksheetPermissionFromSnapshot();+ this._initRangePermissionFromSnapshot();+ });}));}diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.tsindex 5247b19ff9..add4f972ed 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts@@ -673,20 +673,21 @@ export class SheetPermissionInterceptorBaseController extends Disposable {}const { token } = node;const sequenceGrid = deserializeRangeWithSheet(token);- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- let targetSheet: Nullable<Worksheet> = workbook.getActiveSheet();+ const workbook = sequenceGrid.unitId ? this._univerInstanceService.getUnit<Workbook>(sequenceGrid.unitId) : this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) return true;+ let targetSheet: Nullable<Worksheet> = sequenceGrid.sheetName ? workbook.getSheetBySheetName(sequenceGrid.sheetName) : workbook.getActiveSheet();const unitId = workbook.getUnitId();if (sequenceGrid.sheetName) {targetSheet = workbook.getSheetBySheetName(sequenceGrid.sheetName);if (!targetSheet) {- return false;+ return true;}const subUnitId = targetSheet?.getSheetId();const viewPermission = this._permissionService.getPermissionPoint(new WorksheetViewPermission(unitId, subUnitId).id);if (!viewPermission) return false;}if (!targetSheet) {- return false;+ return true;}const { startRow, endRow, startColumn, endColumn } = sequenceGrid.range;for (let i = startRow; i <= endRow; i++) {diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.tsindex 70ba147000..51dc644b20 100644--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { ICommandInfo, IExecutionOptions, ISelectionCell, Nullable, Workbook } from '@univerjs/core';-import { ICommandService, RxDisposable } from '@univerjs/core';+import type { ICommandInfo, IExecutionOptions, Nullable, Workbook } from '@univerjs/core';+import { DisposableCollection, ICommandService, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { DeviceInputEventType } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';@@ -24,78 +24,92 @@ import {SetWorksheetActiveOperation,SheetsSelectionsService,} from '@univerjs/sheets';+import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';-import { merge, takeUntil } from 'rxjs';+import { merge } from 'rxjs';import { IRangeSelectorService } from '@univerjs/ui';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { SetActivateCellEditOperation } from '../../commands/operations/activate-cell-edit.operation';import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';-import type { ICurrentEditCellParam } from '../../services/editor-bridge.service';+import type { ICurrentEditCellParam, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';import { IEditorBridgeService } from '../../services/editor-bridge.service';import { getSheetObject } from '../utils/component-tools';+// TODO: wzhudev: this should be merged with Edit EditingRenderController.+export class EditorBridgeRenderController extends RxDisposable implements IRenderModule {+ private _d: Nullable<IDisposable>;+constructor(private readonly _context: IRenderContext<Workbook>,+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,@ICommandService private readonly _commandService: ICommandService,@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ // FIXME: should use WorkbookSelections+ // FIXME: should check if it is the current sheet, if it becomes the current sheet,+ // it should update cell params, otherwise it should do nothing.@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,@IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService) {super();- this._initialize();+ this.disposeWithMe(this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {+ if (workbook && workbook.getUnitId() === this._context.unitId) {+ this._d = this._init();+ } else {+ this._disposeCurrent();+ }+ }));- this._commandExecutedListener();+ this._initialRangeSelector();}- private _initialize() {- this._initSelectionChangeListener();- this._initEventListener();- this._initialRangeSelector();+ private _init(): IDisposable {+ const d = new DisposableCollection();+ this._initSelectionChangeListener(d);+ this._initEventListener(d);+ this._commandExecutedListener(d);+ return d;}- private _initSelectionChangeListener() {- merge(- this._selectionManagerService.selectionMoveEnd$,- this._selectionManagerService.selectionMoveStart$- )- .pipe(takeUntil(this.dispose$))- .subscribe((params) => this._handleSelectionChange(params));+ private _disposeCurrent(): void {+ this._d?.dispose();+ this._d = null;}- private _updateEditorPosition(cell: ISelectionCell): void {- const sheetObject = this._getSheetObject();- const { scene, engine } = sheetObject;- const unitId = this._context.unitId;- const sheetId = this._context.unit.getActiveSheet()?.getSheetId();- if (!sheetId) return;-- this._commandService.executeCommand<ICurrentEditCellParam>(SetActivateCellEditOperation.id, {- scene,- engine,- primary: cell,- unitId,- sheetId,- });+ private _initSelectionChangeListener(d: DisposableCollection) {+ d.add(merge(+ this._selectionManagerService.selectionMoveEnd$,+ this._selectionManagerService.selectionMoveStart$+ ).subscribe((params) => this._updateEditorPosition(params)));}- private _handleSelectionChange(params: Nullable<ISelectionWithStyle[]>) {- // The editor only responds to regular selections.+ private _updateEditorPosition(params: Nullable<ISelectionWithStyle[]>) {if (this._editorBridgeService.isVisible().visible) return;const primary = params?.[params.length - 1]?.primary;if (primary) {- this._updateEditorPosition(primary);+ const sheetObject = this._getSheetObject();+ const { scene, engine } = sheetObject;+ const unitId = this._context.unitId;+ const sheetId = this._context.unit.getActiveSheet()?.getSheetId();+ if (!sheetId) return;++ this._commandService.executeCommand<ICurrentEditCellParam>(SetActivateCellEditOperation.id, {+ scene,+ engine,+ primary,+ unitId,+ sheetId,+ });}}- private _initEventListener() {+ private _initEventListener(d: DisposableCollection) {const sheetObject = this._getSheetObject();const { spreadsheet, spreadsheetColumnHeader, spreadsheetLeftTopPlaceholder, spreadsheetRowHeader } = sheetObject;- spreadsheet.onDblclick$.subscribeEvent((evt) => {- // No need to enter edit status when user click the right button.+ d.add(spreadsheet.onDblclick$.subscribeEvent((evt) => {if (evt.button === 2) {return;}@@ -103,16 +117,17 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendethis._commandService.executeCommand(SetCellEditVisibleOperation.id, {visible: true,eventType: DeviceInputEventType.Dblclick,- });- });-- spreadsheet.onPointerDown$.subscribeEvent(this._onCanvasPointerDown.bind(this));- spreadsheetColumnHeader.onPointerDown$.subscribeEvent(this._onCanvasPointerDown.bind(this));- spreadsheetLeftTopPlaceholder.onPointerDown$.subscribeEvent(this._onCanvasPointerDown.bind(this));- spreadsheetRowHeader.onPointerDown$.subscribeEvent(this._onCanvasPointerDown.bind(this));+ unitId: this._context.unitId,+ } as IEditorBridgeServiceVisibleParam);+ }));++ d.add(spreadsheet.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));+ d.add(spreadsheetColumnHeader.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));+ d.add(spreadsheetLeftTopPlaceholder.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));+ d.add(spreadsheetRowHeader.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));}- private _onCanvasPointerDown() {+ private _tryHideEditor() {// In the activated state of formula editing,// prohibit closing the editor according to the state to facilitate generating selection reference text.if (this._editorBridgeService.isForceKeepVisible()) {@@ -123,13 +138,12 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende}private _hideEditor() {- if (this._editorBridgeService.isVisible().visible !== true) {- return;- }+ if (this._editorBridgeService.isVisible().visible !== true) return;this._commandService.executeCommand(SetCellEditVisibleOperation.id, {visible: false,eventType: DeviceInputEventType.PointerDown,+ unitId: this._context.unitId,});}@@ -137,6 +151,8 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendethis.disposeWithMe(this._selectionManagerService.selectionMoving$.subscribe(this._rangeSelector.bind(this)));this.disposeWithMe(this._selectionManagerService.selectionMoveStart$.subscribe(this._rangeSelector.bind(this)));+ // TODO: this method shouldn't be here. Fix in when refactor the range selector.+/*** pro/issues/388* When the range selector is opened,@@ -144,15 +160,11 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende*/this.disposeWithMe(this._rangeSelectorService.openSelector$.subscribe(() => {- const selectionWithStyle = this._selectionManagerService.getCurrentSelections();const { unitId, sheetId, sheetName } = this._getCurrentUnitIdAndSheetId();-if (!sheetId || !sheetName) return;- const ranges = selectionWithStyle?.map((value: ISelectionWithStyle) => {- return { range: value.range, unitId, sheetId, sheetName };- });-+ const selectionWithStyle = this._selectionManagerService.getCurrentSelections();+ const ranges = selectionWithStyle?.map((value) => ({ range: value.range, unitId, sheetId, sheetName }));if (ranges) {this._rangeSelectorService.selectionChange(ranges);}@@ -166,7 +178,6 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende}const { unitId, sheetId, sheetName } = this._getCurrentUnitIdAndSheetId();-if (!sheetId || !sheetName) return;const ranges = selectionWithStyle.map((value: ISelectionWithStyle) => {@@ -190,30 +201,20 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendereturn getSheetObject(this._context.unit, this._context)!;}- private _commandExecutedListener() {- const updateCommandList = COMMAND_LISTENER_SKELETON_CHANGE;+ private _commandExecutedListener(d: DisposableCollection) {+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {+ // When the zoom ratio is changed, the editor needs to be refreshed to get the latest cell size and position.+ if (command.id === SetZoomRatioCommand.id) {+ this._editorBridgeService.refreshEditCellState();+ }- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {- if (options?.fromCollab) {- return;- }+ if (options?.fromCollab) return;- if (command.id === SetWorksheetActiveOperation.id) {- this._onCanvasPointerDown();- } else if (updateCommandList.includes(command.id)) {- this._hideEditor();- }- })- );-- // When the zoom ratio is changed, the editor needs to be refreshed to get the latest cell size and position.- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === SetZoomRatioCommand.id) {- this._editorBridgeService.refreshEditCellState();- }- })- );+ if (command.id === SetWorksheetActiveOperation.id) {+ this._tryHideEditor();+ } else if (COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id)) {+ this._hideEditor();+ }+ }));}}diff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.tsindex 87f4f5f893..0142cd419a 100644--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts@@ -71,7 +71,7 @@ import { ScrollCommand } from '../../commands/commands/set-scroll.command';import { SetZoomRatioOperation } from '../../commands/operations/set-zoom-ratio.operation';import { SHEET_COMPONENT_HEADER_LAYER_INDEX } from '../../common/keys';-import { ScrollManagerService } from '../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../services/scroll-manager.service';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { getCoordByOffset, getSheetObject } from '../utils/component-tools';@@ -149,7 +149,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM@ICommandService private readonly _commandService: ICommandService,// @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService,@Inject(ThemeService) private readonly _themeService: ThemeService,@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(Injector) private _injector: Injectordiff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.tsindex 95a261cb05..f4744575cc 100644--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts@@ -33,7 +33,7 @@ import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commaimport type { IExpandSelectionCommandParams } from '../../../commands/commands/set-selection.command';import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';import type { IScrollManagerParam, IScrollManagerSearchParam } from '../../../services/scroll-manager.service';-import { ScrollManagerService } from '../../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../../services/scroll-manager.service';import type { ISheetSkeletonManagerParam } from '../../../services/sheet-skeleton-manager.service';import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';import { getSheetObject } from '../../utils/component-tools';@@ -50,7 +50,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR@ICommandService private readonly _commandService: ICommandService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService,@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService) {super();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 f2407ac711..de0c43699b 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@@ -32,7 +32,7 @@ import { ScrollCommand } from '../../commands/commands/set-scroll.command';import type { IExpandSelectionCommandParams } from '../../commands/commands/set-selection.command';import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';import type { IScrollManagerParam, IScrollManagerSearchParam } from '../../services/scroll-manager.service';-import { ScrollManagerService } from '../../services/scroll-manager.service';+import { SheetScrollManagerService } from '../../services/scroll-manager.service';import type { ISheetSkeletonManagerParam } from '../../services/sheet-skeleton-manager.service';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { getSheetObject } from '../utils/component-tools';@@ -49,7 +49,7 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@ICommandService private readonly _commandService: ICommandService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService) {super();diff --git a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.tsindex e9566ea8d4..2369ed4687 100644--- a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts@@ -123,8 +123,6 @@ export class SheetRenderController extends RxDisposable implements IRenderModuleconst bufferEdgeX = 100;const bufferEdgeY = 100;- // TODO @lumixraku test- // (window as any).sc = scene;const viewMain = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN, scene, {left: rowHeader.width,top: columnHeader.height,diff --git a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts b/packages/sheets-ui/src/mobile-sheets-ui-plugin.tsindex 593cfcdfc2..2a2593c380 100644--- a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts@@ -38,7 +38,7 @@ import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-filimport { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';import { FormatPainterService, IFormatPainterService } from './services/format-painter/format-painter.service';import { IMarkSelectionService, MarkSelectionService } from './services/mark-selection/mark-selection.service';-import { ScrollManagerService } from './services/scroll-manager.service';+import { SheetScrollManagerService } from './services/scroll-manager.service';import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';import { ShortcutExperienceService } from './services/shortcut-experience.service';@@ -102,7 +102,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {[IAutoFillService, { useClass: AutoFillService }],[SheetPrintInterceptorService],- [ScrollManagerService],+ [SheetScrollManagerService],// This would be removed from global injector and moved into RenderUnit provider.// [SheetSkeletonManagerService],[ISheetSelectionRenderService, { useClass: MobileSheetsSelectionRenderService }],@@ -116,7 +116,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {// controllers[ActiveWorksheetController],[AutoHeightController],- [HeaderFreezeRenderController],[SheetClipboardController],[SheetsRenderService],[diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsindex e5351f908b..6dab0bfee6 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts@@ -363,91 +363,91 @@ const mergeData = [startColumn: 10,endColumn: 11,},- // check+ // check{startRow: 0,startColumn: 5,endRow: 0,endColumn: 6,},- // check+ // check{startRow: 2,startColumn: 5,endRow: 2,endColumn: 7,},- // check+ // check{startRow: 4,startColumn: 5,endRow: 4,endColumn: 8,},- // check+ // check{startRow: 6,startColumn: 5,endRow: 7,endColumn: 6,},- // check+ // check{startRow: 9,startColumn: 5,endRow: 9,endColumn: 6,},- // check+ // check{startRow: 11,startColumn: 5,endRow: 12,endColumn: 6,},- // check+ // check{startRow: 11,startColumn: 7,endRow: 12,endColumn: 7,},- // check+ // check{startRow: 0,startColumn: 10,endRow: 0,endColumn: 11,},- // check+ // check{startRow: 3,startColumn: 10,endRow: 3,endColumn: 12,},- // check+ // check{startRow: 6,startColumn: 10,endRow: 6,endColumn: 11,},- // check+ // check{startRow: 8,startColumn: 11,endRow: 9,endColumn: 12,},- // check+ // check{startRow: 11,startColumn: 10,endRow: 11,endColumn: 12,},- // check+ // check{startRow: 13,startColumn: 11,@@ -490,15 +490,15 @@ export class testMarkSelectionService {}removeShape(id: string): void {- // empty+ // empty}removeAllShapes(): void {- // empty+ // empty}refreshShapes(): void {- // empty+ // empty}getShapeMap(): Map<string, any> {@@ -526,9 +526,9 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deconst injector = univer.__getInjector();const get = injector.get.bind(injector);- /**- * This plugin hooks into Sheet's DI system to expose API to test scripts- */+ /**+ * This plugin hooks into Sheet's DI system to expose API to test scripts+ */class TestPlugin extends Plugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;@@ -556,7 +556,7 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([INotificationService, { useClass: testNotificationService }]);injector.add([IPlatformService, { useClass: testPlatformService }]);- // Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually+ // Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manuallyconst sheetClipboardController = injector.createInstance(SheetClipboardController);injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);@@ -584,8 +584,8 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deconst logService = get(ILogService);logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs- // NOTE: This is pretty hack for the test. But with these hacks we can avoid to create- // real canvas-environment in univerjs/sheets-ui. If some we have to do that, this hack could be removed.+ // NOTE: This is pretty hack for the test. But with these hacks we can avoid to create+ // real canvas-environment in univerjs/sheets-ui. If some we have to do that, this hack could be removed.const fakeSheetSkeletonManagerService = new SheetSkeletonManagerService({unit: sheet,unitId: 'test',diff --git a/packages/sheets-ui/src/services/drag-manager.service.ts b/packages/sheets-ui/src/services/drag-manager.service.tsindex de5720a8f8..5399b8fd0b 100644--- a/packages/sheets-ui/src/services/drag-manager.service.ts+++ b/packages/sheets-ui/src/services/drag-manager.service.ts@@ -16,12 +16,11 @@import type { Nullable, Workbook } from '@univerjs/core';import { Disposable, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { Inject } from '@wendellhu/redi';import { distinctUntilChanged, Subject } from 'rxjs';import type { IDragEvent } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { getHoverCellPosition } from '../common/utils';-import { ScrollManagerService } from './scroll-manager.service';+import { SheetScrollManagerService } from './scroll-manager.service';import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';import type { IHoverCellPosition } from './hover-manager.service';@@ -45,7 +44,6 @@ export class DragManagerService extends Disposable {constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -78,9 +76,11 @@ export class DragManagerService extends Disposable {if (!worksheet) return;// const skeletonParam = this._sheetSkeletonManagerService.getCurrent();const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());- const skeletonParam = currentRender?.with(SheetSkeletonManagerService)?.getCurrent();+ if (!currentRender) return;- const scrollInfo = this._scrollManagerService.getCurrentScrollInfo();+ const skeletonParam = currentRender.with(SheetSkeletonManagerService).getCurrent();+ const scrollManagerService = currentRender.with(SheetScrollManagerService);+ const scrollInfo = scrollManagerService.getCurrentScrollInfo();if (!skeletonParam || !scrollInfo || !currentRender) return;diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex 3f07328bb7..923b60950b 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -48,6 +48,7 @@ import { attachPrimaryWithCoord } from './selection/util';export interface IEditorBridgeServiceVisibleParam {visible: boolean;eventType: DeviceInputEventType;+ unitId: string;keycode?: KeyCode;}@@ -111,6 +112,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServprivate _visible: IEditorBridgeServiceVisibleParam = {visible: false,eventType: DeviceInputEventType.Dblclick,+ unitId: '',};private _currentEditCell: Nullable<ICurrentEditCellParam> = null;@@ -203,6 +205,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServconst skeleton = ru.with(SheetSkeletonManagerService).getCurrentSkeleton();const selectionRenderService = ru.with(ISheetSelectionRenderService);+ if (!skeleton) return;const { primary, unitId, sheetId, scene, engine } = currentEditCell;const { startRow, startColumn } = primary;diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.tsindex 7111dec89d..85f699b08b 100644--- a/packages/sheets-ui/src/services/hover-manager.service.ts+++ b/packages/sheets-ui/src/services/hover-manager.service.ts@@ -17,12 +17,11 @@import type { IPosition, Nullable, Workbook } from '@univerjs/core';import { Disposable, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import type { ISheetLocation } from '@univerjs/sheets';-import { Inject } from '@wendellhu/redi';import { distinctUntilChanged, Subject } from 'rxjs';import { IRenderManagerService } from '@univerjs/engine-render';import { getHoverCellPosition } from '../common/utils';-import { ScrollManagerService } from './scroll-manager.service';import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';+import { SheetScrollManagerService } from './scroll-manager.service';export interface IHoverCellPosition {position: IPosition;@@ -49,7 +48,6 @@ export class HoverManagerService extends Disposable {constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -87,7 +85,8 @@ export class HoverManagerService extends Disposable {const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getWorksheetSkeleton(worksheet.getSheetId());- const scrollInfo = this._scrollManagerService.getCurrentScrollInfo();+ const scrollManagerService = currentRender?.with(SheetScrollManagerService);+ const scrollInfo = scrollManagerService?.getCurrentScrollInfo();if (!skeletonParam || !scrollInfo || !currentRender) return;diff --git a/packages/sheets-ui/src/services/scroll-manager.service.ts b/packages/sheets-ui/src/services/scroll-manager.service.tsindex 66f9c0711d..f8ae44602f 100644--- a/packages/sheets-ui/src/services/scroll-manager.service.ts+++ b/packages/sheets-ui/src/services/scroll-manager.service.ts@@ -14,9 +14,10 @@* limitations under the License.*/-import { IUniverInstanceService, type Nullable, UniverInstanceType } from '@univerjs/core';+import type { Nullable, Workbook } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';-import { IRenderManagerService } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { Inject } from '@wendellhu/redi';import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';export interface IViewportScrollState {@@ -71,7 +72,7 @@ export type IScrollInfo = Map<string, Map<string, IScrollManagerParam>>;** ScrollController subscribes to the changes in service data to refresh the view scrolling.*/-export class ScrollManagerService {+export class SheetScrollManagerService implements IRenderModule {/*** a map holds all scroll info for each sheet*/@@ -97,10 +98,10 @@ export class ScrollManagerService {private _searchParamForScroll: Nullable<IScrollManagerSearchParam> = null;constructor(- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ private readonly _context: IRenderContext<Workbook>,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService) {- // init+ // empty}dispose(): void {@@ -128,8 +129,9 @@ export class ScrollManagerService {if (this._searchParamForScroll == null) {return;}- const { unitId, sheetId } = this._searchParamForScroll;- const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);++ const { sheetId } = this._searchParamForScroll;+ const workbook = this._context.unit;const worksheet = workbook?.getSheetBySheetId(sheetId);const snapshot = worksheet?.getConfig();if (snapshot) {@@ -189,16 +191,6 @@ export class ScrollManagerService {this._clearByParam(this._searchParamForScroll);}- // scrollToCell(startRow: number, startColumn: number) {- // const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;- // const scene = this._renderManagerService.getCurrent()?.scene;- // if (skeleton == null || scene == null) {- // return;- // }-- // const {} = skeleton.getCellByIndex(startRow, startColumn);- // }-calcViewportScrollFromRowColOffset(scrollInfo: IScrollManagerWithSearchParam) {const { unitId } = scrollInfo;const workbookScrollInfo = this._scrollInfoMap.get(unitId);@@ -213,8 +205,7 @@ export class ScrollManagerService {sheetViewStartRow = sheetViewStartRow || 0;offsetY = offsetY || 0;- // const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;- const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();+ const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();const rowAcc = skeleton?.rowHeightAccumulation[sheetViewStartRow - 1] || 0;const colAcc = skeleton?.columnWidthAccumulation[sheetViewStartColumn - 1] || 0;const overallScrollX = colAcc + offsetX;diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.tsindex 7a9884aa19..19de6815cf 100644--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts@@ -20,7 +20,6 @@ import type {IRangeWithCoord,ISelectionCell,ISelectionCellWithMergeInfo,-ISelectionWithCoord,Nullable,ThemeService,@@ -62,7 +61,7 @@ export interface ISheetSelectionRenderService {getSkeleton(): SpreadsheetSkeleton;- getSelectionControls(): SelectionControl[]; // AutoFill+ getSelectionControls(): SelectionControl[];// The following methods are used to get range locations in a worksheet. Though `attachRangeWithCoord` should not happens here.// And `attachPrimaryWithCoord` is redundant.@@ -226,14 +225,13 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSeleconst { rowHeaderWidth, columnHeaderHeight } = skeleton;- // update controlcontrol.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);}newSelectionControl(scene: Scene, _rangeType: RANGE_TYPE): SelectionControl {const selectionControls = this.getSelectionControls();- const control = new SelectionControl(scene, selectionControls.length, this._isHeaderHighlight, this._themeService);//this._selectionStyle);+ const control = new SelectionControl(scene, selectionControls.length, this._isHeaderHighlight, this._themeService);this._selectionControls.push(control);return control;@@ -278,7 +276,13 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelegetSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {const selectionControls = this._selectionControls;- return selectionControls.map((control) => control.getValue());+ const [unitId, sheetId] = this._skeleton.getLocation();+ return selectionControls.map((control) => {+ const v = control.getValue();+ v.rangeWithCoord.sheetId = sheetId;+ v.rangeWithCoord.unitId = unitId;+ return v;+ });}getSelectionControls() {@@ -286,7 +290,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele}protected _clearSelectionControls() {- const allSelectionControls = this.getSelectionControls();+ const allSelectionControls = this._selectionControls;for (const control of allSelectionControls) {control.dispose();}@@ -354,7 +358,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele}endSelection() {- this._clearEndingListeners();+ this._clearUpdatingListeners();// ---> _updateSelections --> executeCommand(SetSelectionsOperation.id --> selectionManager.setSelections// ---> _selectionMoveEnd$.next --> _initSelectionChangeListener _reset --> _clearSelectionControls@@ -367,12 +371,8 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSeleprotected _reset() {this._clearSelectionControls();- this._clearMove();-this._downObserver?.unsubscribe();this._downObserver = null;- this._scenePointerUpSub?.unsubscribe();- this._scenePointerUpSub = null;}resetAndEndSelection() {@@ -489,7 +489,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelethis._selectionMoveStart$.next(this.getSelectionDataWithStyle());scene.disableEvent();- this._clearEndingListeners();+ this._clearUpdatingListeners();this._addEndingListeners();scene.getTransformer()?.clearSelectedObjects();@@ -502,13 +502,12 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele}this._moving(viewportPosX, viewportPosY, activeSelectionControl, rangeType);}- // #region setup moving+this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, viewportPosX, viewportPosY);- // #endregionthis._shortcutService.setDisable(true);this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {- this._clearEndingListeners();+ this._clearUpdatingListeners();this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());this._shortcutService.setDisable(false);});@@ -704,12 +703,15 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele) {const skeleton = this._skeleton;const scene = this._scene;+ const [unitId, sheetId] = skeleton.getLocation();const currSelectionRange: IRange = {startRow: activeSelectionControl?.model.startRow ?? -1,endRow: activeSelectionControl?.model.endRow ?? -1,startColumn: activeSelectionControl?.model.startColumn ?? -1,endColumn: activeSelectionControl?.model.endColumn ?? -1,+ unitId,+ sheetId,};const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;@@ -760,6 +762,8 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelestartColumn: newSelectionRange.startColumn,endRow: newSelectionRange.endRow,endColumn: newSelectionRange.endColumn,+ unitId,+ sheetId,startY: startCellXY?.startY || 0,endY: endCellXY?.endY || 0,startX: startCellXY?.startX || 0,@@ -773,7 +777,6 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelecurrSelectionRange.endRow !== newSelectionRange.endRow ||currSelectionRange.endColumn !== newSelectionRange.endColumn;if (activeSelectionControl != null && rangeChanged) {- // selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);this._updateSelectionControlRange(activeSelectionControl, newSelectionRangeWithCoord);this._selectionMoving$.next(this.getSelectionDataWithStyle());}@@ -785,25 +788,19 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelecontrol.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight, this._selectionStyle, !highlight ? null : highlight);}- private _clearMove(): void {- this._scenePointerMoveSub?.unsubscribe();- this._scenePointerMoveSub = null;- }-- protected _clearEndingListeners() {+ protected _clearUpdatingListeners() {const scene = this._scene;scene.enableEvent();- this._clearMove();+ this._scenePointerMoveSub?.unsubscribe();+ this._scenePointerMoveSub = null;this._scenePointerUpSub?.unsubscribe();this._scenePointerUpSub = null;-- this._scrollTimer?.dispose();-this._cancelDownSubscription?.unsubscribe();this._cancelDownSubscription = null;this._cancelUpSubscription?.unsubscribe();this._cancelUpSubscription = null;+ this._scrollTimer?.dispose();}protected _addEndingListeners() {@@ -818,8 +815,8 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelethis._cancelUpSubscription?.unsubscribe();this._cancelUpSubscription = null;- this._cancelDownSubscription = mainScene.onPointerDown$.subscribeEvent(() => this._clearEndingListeners());- this._cancelUpSubscription = mainScene.onPointerUp$.subscribeEvent(() => this._clearEndingListeners());+ this._cancelDownSubscription = mainScene.onPointerDown$.subscribeEvent(() => this._clearUpdatingListeners());+ this._cancelUpSubscription = mainScene.onPointerUp$.subscribeEvent(() => this._clearUpdatingListeners());}protected _getCellRangeByCursorPosition(diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.tsindex bfcba57236..7b6fa7eba3 100644--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts@@ -41,7 +41,7 @@ import { distinctUntilChanged, startWith } from 'rxjs';import type { ISheetObjectParam } from '../../controllers/utils/component-tools';import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';import { checkInHeaderRanges } from '../../controllers/utils/selections-tools';-import { ScrollManagerService } from '../scroll-manager.service';+import { SheetScrollManagerService } from '../scroll-manager.service';import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';import { MobileSelectionControl } from './mobile-selection-shape';@@ -76,7 +76,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi@ICommandService private readonly _commandService: ICommandService,@IContextService private readonly _contextService: IContextService,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService) {super(injector,@@ -360,7 +360,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi);this._selectionMoveStart$.next(this.getSelectionDataWithStyle());- this._clearEndingListeners();+ this._clearUpdatingListeners();// this._addEndingListeners();this._expandingSelection = false;@@ -495,7 +495,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServithis._selectionMoveStart$.next(this.getSelectionDataWithStyle());- this._clearEndingListeners();+ this._clearUpdatingListeners();this._addEndingListeners();this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);diff --git a/packages/sheets-ui/src/services/selection/selection-render-model.ts b/packages/sheets-ui/src/services/selection/selection-render-model.tsindex ddcf4d6003..b53fceaf7c 100644--- a/packages/sheets-ui/src/services/selection/selection-render-model.ts+++ b/packages/sheets-ui/src/services/selection/selection-render-model.ts@@ -19,22 +19,12 @@ import { makeCellToSelection, RANGE_TYPE } from '@univerjs/core';export class SelectionRenderModel implements IRangeWithCoord {private _startColumn: number = -1;-private _startRow: number = -1;-private _endColumn: number = -1;-private _endRow: number = -1;-- /**- * value from { startY, endY, startX, endX } = getCellPositionByIndex in basics/tools- */private _startX: number = 0;-private _startY: number = 0;-private _endX: number = 0;-private _endY: number = 0;/**@@ -42,65 +32,23 @@ export class SelectionRenderModel implements IRangeWithCoord {* when there is no merge info* top left cell of current selection (or bottomLeft of current selection)*/- private _currentCell: Nullable<ISelectionCellWithMergeInfo>;-+ private _primary: Nullable<ISelectionCellWithMergeInfo>;private _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;- get startColumn() {- return this._startColumn;- }-- get startRow() {- return this._startRow;- }-- get endColumn() {- return this._endColumn;- }-- get endRow() {- return this._endRow;- }-- /**- * value from { startY, endY, startX, endX } = getCellPositionByIndex in basics/tools- */- get startX() {- return this._startX;- }+ get startColumn() { return this._startColumn; }+ get startRow() { return this._startRow; }+ get endColumn() { return this._endColumn; }+ get endRow() { return this._endRow; }+ get startX() { return this._startX; }+ get startY() { return this._startY; }+ get endX() { return this._endX; }+ get endY() { return this._endY; }+ get currentCell() { return this._primary; }+ get rangeType() { return this._rangeType; }/**- * value from { startY, endY, startX, endX } = getCellPositionByIndex in basics/tools+ * @deprecated, Duplicate with `Rectangle`*/- get startY() {- return this._startY;- }-- /**- * value from { startY, endY, startX, endX } = getCellPositionByIndex in basics/tools- */- get endX() {- return this._endX;- }-- /**- * value from { startY, endY, startX, endX } = getCellPositionByIndex in basics/tools- */- get endY() {- return this._endY;- }-- /**- * highlight cell of selection- */- get currentCell() {- return this._currentCell;- }-- get rangeType() {- return this._rangeType;- }-isEqual(rangeWithCoord: IRangeWithCoord) {const { startColumn, startRow, endColumn, endRow } = this;const {@@ -109,9 +57,7 @@ export class SelectionRenderModel implements IRangeWithCoord {endColumn: newEndColumn,endRow: newEndRow,} = rangeWithCoord;- // if (type !== newType) {- // return false;- // }+if (startColumn === newStartColumn &&startRow === newStartRow &&@@ -120,9 +66,13 @@ export class SelectionRenderModel implements IRangeWithCoord {) {return true;}+return false;}+ /**+ * @deprecated, Duplicate with `Rectangle`+ */isInclude(rangeWithCoord: IRangeWithCoord) {const { startColumn, startRow, endColumn, endRow } = this;const {@@ -132,10 +82,6 @@ export class SelectionRenderModel implements IRangeWithCoord {endRow: newEndRow,} = rangeWithCoord;- // if (type !== newType) {- // return false;- // }-if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {@@ -145,28 +91,26 @@ export class SelectionRenderModel implements IRangeWithCoord {}highlightToSelection() {- if (!this._currentCell) return;- return makeCellToSelection(this._currentCell);+ if (!this._primary) return;+ return makeCellToSelection(this._primary);}- getRange() {+ getRange(): IRangeWithCoord {return {startColumn: this._startColumn,startRow: this._startRow,endColumn: this._endColumn,endRow: this._endRow,-startX: this._startX,startY: this._startY,endX: this._endX,endY: this._endY,-rangeType: this.rangeType,};}getCell() {- return this._currentCell;+ return this._primary;}getRangeType() {@@ -179,20 +123,8 @@ export class SelectionRenderModel implements IRangeWithCoord {getValue(): ISelectionWithCoord {return {- rangeWithCoord: {- startColumn: this._startColumn,- startRow: this._startRow,- endColumn: this._endColumn,- endRow: this._endRow,-- startX: this._startX,- startY: this._startY,- endX: this._endX,- endY: this._endY,-- rangeType: this._rangeType,- },- primaryWithCoord: this._currentCell,+ rangeWithCoord: this.getRange(),+ primaryWithCoord: this._primary,};}@@ -202,32 +134,23 @@ export class SelectionRenderModel implements IRangeWithCoord {startRow,endColumn,endRow,-startX,startY,endX,endY,-rangeType,} = newSelectionRange;this._startColumn = startColumn;-this._startRow = startRow;-this._endColumn = endColumn;-this._endRow = endRow;-this._startX = startX;-this._startY = startY;-this._endX = endX;-this._endY = endY;- if (rangeType != null) {+ if (rangeType) {this._rangeType = rangeType;}@@ -236,11 +159,11 @@ export class SelectionRenderModel implements IRangeWithCoord {setCurrentCell(currentCell: Nullable<ISelectionCellWithMergeInfo>) {if (currentCell) {- this._currentCell = currentCell;+ this._primary = currentCell;}}clearCurrentCell() {- this._currentCell = null;+ this._primary = null;}}diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.tsindex 9e48966cce..98f3ef97b8 100644--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts@@ -84,8 +84,8 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo}));}- getCurrentSkeleton(): SpreadsheetSkeleton {- return this.getCurrent()!.skeleton;+ getCurrentSkeleton(): Nullable<SpreadsheetSkeleton> {+ return this.getCurrent()?.skeleton;}getCurrent(): Nullable<ISheetSkeletonManagerParam> {@@ -197,6 +197,8 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo/** @deprecated Use function `attachRangeWithCoord` instead. */attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord> {const skeleton = this.getCurrentSkeleton();+ if (!skeleton) return null;+return attachRangeWithCoord(skeleton, range);}diff --git a/packages/sheets-ui/src/services/sheets-render.service.ts b/packages/sheets-ui/src/services/sheets-render.service.tsindex 047273405f..4adbbbb181 100644--- a/packages/sheets-ui/src/services/sheets-render.service.ts+++ b/packages/sheets-ui/src/services/sheets-render.service.ts@@ -54,7 +54,7 @@ export class SheetsRenderService extends RxDisposable {*/registerSkeletonChangingMutations(mutationId: string): IDisposable {if (this._skeletonChangeMutations.has(mutationId)) {- throw new Error(`[SheetsRenderService]: the mutationId ${mutationId} has already been registered!`);+ return toDisposable(() => {});}this._skeletonChangeMutations.add(mutationId);diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.tsindex 82415217bd..8a7ce618eb 100644--- a/packages/sheets-ui/src/sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts@@ -48,7 +48,6 @@ import {import { EditorBridgeService, IEditorBridgeService } from './services/editor-bridge.service';import { FormatPainterService, IFormatPainterService } from './services/format-painter/format-painter.service';import { IMarkSelectionService, MarkSelectionService } from './services/mark-selection/mark-selection.service';-import { ScrollManagerService } from './services/scroll-manager.service';import { SheetSelectionRenderService } from './services/selection/selection-render.service';import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';@@ -84,6 +83,7 @@ import { SheetPrintInterceptorService } from './services/print-interceptor.serviimport { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';import { MoveRangeRenderController } from './controllers/move-range.controller';import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';+import { SheetScrollManagerService } from './services/scroll-manager.service';@DependentOn(UniverSheetsPlugin)export class UniverSheetsUIPlugin extends Plugin {@@ -114,7 +114,6 @@ export class UniverSheetsUIPlugin extends Plugin {[IAutoFillService, { useClass: AutoFillService }],[SheetPrintInterceptorService],- [ScrollManagerService],// This would be removed from global injector and moved into RenderUnit provider.// [SheetSkeletonManagerService],[IStatusBarService, { useClass: StatusBarService }],@@ -128,7 +127,6 @@ export class UniverSheetsUIPlugin extends Plugin {[ActiveWorksheetController],[AutoHeightController],[FormulaEditorController],- [HeaderFreezeRenderController],[SheetClipboardController],[SheetsRenderService],[@@ -150,8 +148,7 @@ export class UniverSheetsUIPlugin extends Plugin {[SheetPermissionInterceptorBaseController],[SheetPermissionInitController],// [MoveRangeController],- ] as Dependency[]- ).forEach((d) => injector.add(d));+ ] as Dependency[]).forEach((d) => injector.add(d));this._injector.add([@@ -188,13 +185,13 @@ export class UniverSheetsUIPlugin extends Plugin {private _registerRenderModules(): void {([[HeaderMoveRenderController],- [HeaderFreezeRenderController],[HeaderUnhideRenderController],[HeaderResizeRenderController],-// Caution: ScrollRenderController should placed before ZoomRenderController// because ZoomRenderController ---> viewport.resize --> setScrollInfo, but ScrollRenderController needs scrollInfo+ [SheetScrollManagerService],[SheetsScrollRenderController],+ [HeaderFreezeRenderController],[SheetsZoomRenderController],[FormatPainterRenderController],diff --git a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsxindex 553c798c9a..8b4dc318e1 100644--- a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx+++ b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx@@ -28,28 +28,35 @@ import React, { useCallback, useEffect, useState } from 'react';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { SetZoomRatioOperation } from '../../commands/operations/set-zoom-ratio.operation';import { SHEET_ZOOM_RANGE } from '../../common/keys';+import { useActiveWorkbook } from '../../components/hook';const ZOOM_MAP = [50, 80, 100, 130, 150, 170, 200, 400];export function ZoomSlider() {const commandService = useDependency(ICommandService);const univerInstanceService = useDependency(IUniverInstanceService);+ const workbook = useActiveWorkbook();const getCurrentZoom = useCallback(() => {- const worksheet = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();+ if (!workbook) return 100;++ const worksheet = workbook.getActiveSheet();const currentZoom = (worksheet && (worksheet.getZoomRatio() * 100)) || 100;return Math.round(currentZoom);- }, [univerInstanceService]);+ }, [workbook]);const [zoom, setZoom] = useState(() => getCurrentZoom());useEffect(() => {+ setZoom(getCurrentZoom());+const disposable = commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetZoomRatioOperation.id || commandInfo.id === SetWorksheetActiveOperation.id) {const currentZoom = getCurrentZoom();setZoom(currentZoom);}});+return disposable.dispose;}, [commandService, getCurrentZoom]);diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsxindex a1d74b60d4..4c81cd1feb 100644--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx@@ -29,6 +29,7 @@ import { IFormulaEditorManagerService } from '../../services/editor/formula-editimport { IEditorBridgeService } from '../../services/editor-bridge.service';import { DefinedName } from '../defined-name/DefinedName';+import { useActiveWorkbook } from '../../components/hook';import styles from './index.module.less';enum ArrowDirection {@@ -50,6 +51,7 @@ export function FormulaBar() {const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);const permissionService = useDependency(IPermissionService);+ const currentWorkbook = useActiveWorkbook();function getPermissionIds(unitId: string, subUnitId: string): string[] {return [@@ -168,6 +170,7 @@ export function FormulaBar() {visible: false,eventType: DeviceInputEventType.Keyboard,keycode: KeyCode.ESC,+ unitId: currentWorkbook?.getUnitId() ?? '',});}}@@ -179,6 +182,7 @@ export function FormulaBar() {editorBridgeService.changeVisible({visible: false,eventType: DeviceInputEventType.PointerDown,+ unitId: currentWorkbook?.getUnitId() ?? '',});}}diff --git a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsxindex 75cc4ce9eb..e5beb1137d 100644--- a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx+++ b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx@@ -14,8 +14,7 @@* limitations under the License.*/-import type { Workbook } from '@univerjs/core';-import { ICommandService, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { ICommandService, IPermissionService } from '@univerjs/core';import { IncreaseSingle, MoreSingle } from '@univerjs/icons';import { InsertSheetCommand, WorkbookCreateSheetPermission, WorkbookEditablePermission } from '@univerjs/sheets';import { useDependency } from '@wendellhu/redi/react-bindings';@@ -23,6 +22,7 @@ import React, { useEffect, useState } from 'react';import { useObservable } from '@univerjs/ui';import { ISheetBarService } from '../../services/sheet-bar/sheet-bar.service';+import { useActiveWorkbook } from '../../components/hook';import styles from './index.module.less';import { SheetBarButton } from './sheet-bar-button/SheetBarButton';import { SheetBarMenu } from './sheet-bar-menu/SheetBarMenu';@@ -37,11 +37,9 @@ export const SheetBar = () => {const commandService = useDependency(ICommandService);const sheetBarService = useDependency(ISheetBarService);-const permissionService = useDependency(IPermissionService);- const univerInstanceService = useDependency(IUniverInstanceService);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const workbook = useActiveWorkbook()!;const unitId = workbook.getUnitId();const workbookEditablePermission = useObservable(permissionService.getPermissionPoint$(new WorkbookEditablePermission(unitId)?.id));diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsxindex 896081ba96..caacfe48ed 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx@@ -14,8 +14,8 @@* limitations under the License.*/-import type { ICommandInfo, Workbook } from '@univerjs/core';-import { ICommandService, IPermissionService, IUniverInstanceService, LocaleService, nameCharacterCheck, UniverInstanceType } from '@univerjs/core';+import type { ICommandInfo } from '@univerjs/core';+import { ICommandService, IPermissionService, LocaleService, nameCharacterCheck } from '@univerjs/core';import { Dropdown } from '@univerjs/design';import {InsertSheetMutation,@@ -58,7 +58,6 @@ export function SheetBarTabs() {const slideTabBarRef = useRef<{ slideTabBar: SlideTabBar | null }>({ slideTabBar: null });const slideTabBarContainerRef = useRef<HTMLDivElement>(null);- const univerInstanceService = useDependency(IUniverInstanceService);const commandService = useDependency(ICommandService);const sheetBarService = useDependency(ISheetBarService);const localeService = useDependency(LocaleService);@@ -121,7 +120,7 @@ export function SheetBarTabs() {slideTabBar.destroy();subscribeList.forEach((subscribe) => subscribe.unsubscribe());};- }, [resetOrder]);+ }, [resetOrder, workbook]);useEffect(() => {if (sheetList.length > 0) {@@ -206,6 +205,8 @@ export function SheetBarTabs() {return slideTabBar;};+ // TODO@Dushusir: the following callback functions should be wrapped by `useCallback`.+const nameEmptyCheck = (name: string) => {if (name.trim() === '') {const id = 'sheetNameEmptyAlert';@@ -255,7 +256,6 @@ export function SheetBarTabs() {};const nameRepeatCheck = (name: string) => {- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();const currenSheetName = worksheet?.getName();// TODO@Dushusir: no need trigger savediff --git a/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts b/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.tsindex ea01fe7f1a..1026246030 100644--- a/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts+++ b/packages/sheets-zen-editor/src/commands/commands/zen-editor.command.ts@@ -34,6 +34,7 @@ export const CancelZenEditCommand: ICommand = {visible: false,eventType: DeviceInputEventType.Keyboard,keycode: KeyCode.ESC,+ unitId: '',});}@@ -66,6 +67,7 @@ export const ConfirmZenEditCommand: ICommand = {editorBridgeService.changeVisible({visible: false,eventType: DeviceInputEventType.PointerDown,+ unitId: '',});}diff --git a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.tsindex c5e2114511..69a6b604df 100644--- a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts+++ b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts@@ -41,7 +41,7 @@ import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-reimport type { IEditorBridgeServiceParam } from '@univerjs/sheets-ui';import { getEditorObject, IEditorBridgeService } from '@univerjs/sheets-ui';import { IZenZoneService } from '@univerjs/ui';-import { Inject, Injector } from '@wendellhu/redi';+import { Inject } from '@wendellhu/redi';import { takeUntil } from 'rxjs';import { OpenZenEditorOperation } from '../commands/operations/zen-editor.operation';@@ -52,7 +52,6 @@ export const DOCS_ZEN_EDITOR_UNIT_ID_KEY = '__defaultDocumentZenEditorSpecialUni@OnLifecycle(LifecycleStages.Steady, ZenEditorController)export class ZenEditorController extends RxDisposable {constructor(- @Inject(Injector) private readonly _injector: Injector,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@IZenEditorManagerService private readonly _zenEditorManagerService: IZenEditorManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@@ -69,10 +68,7 @@ export class ZenEditorController extends RxDisposable {private _initialize() {this._syncZenEditorSize();-this._commandExecutedListener();-- // this._createZenEditorInstance();}private _createZenEditorInstance() {@@ -157,11 +153,12 @@ export class ZenEditorController extends RxDisposable {this._zenZoneService.open();+ const currentSheet = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);+// Need to clear undo/redo service when open zen mode.this._undoRedoService.clearUndoRedo(DOCS_ZEN_EDITOR_UNIT_ID_KEY);this._univerInstanceService.focusUnit(DOCS_ZEN_EDITOR_UNIT_ID_KEY);-this._univerInstanceService.setCurrentUnitForType(DOCS_ZEN_EDITOR_UNIT_ID_KEY);const visibleState = this._editorBridgeService.isVisible();@@ -169,6 +166,7 @@ export class ZenEditorController extends RxDisposable {this._editorBridgeService.changeVisible({visible: true,eventType: DeviceInputEventType.PointerDown,+ unitId: currentSheet?.getUnitId() ?? '',});}diff --git a/packages/sheets/src/basics/selection.ts b/packages/sheets/src/basics/selection.tsindex 733f76f52c..dc0081e012 100644--- a/packages/sheets/src/basics/selection.ts+++ b/packages/sheets/src/basics/selection.ts@@ -206,6 +206,8 @@ export function convertSelectionDataToRange(endRow: rangeWithCoord.endRow,endColumn: rangeWithCoord.endColumn,rangeType: rangeWithCoord.rangeType,+ unitId: rangeWithCoord.unitId,+ sheetId: rangeWithCoord.sheetId,},primary: null,style,diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.tsindex 2554476862..3633cbdcb5 100644--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts@@ -26,7 +26,6 @@ import {} from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';-import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';import type { ISetColHiddenMutationParams, ISetColVisibleMutationParams } from '../mutations/set-col-visible.mutation';import {SetColHiddenMutation,@@ -37,6 +36,7 @@ import {import type { ISetSelectionsOperationParams } from '../operations/selection.operation';import { SetSelectionsOperation } from '../operations/selection.operation';import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';import { getPrimaryForRange } from './utils/selection-utils';import { getSheetCommandTarget } from './utils/target-util';diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.tsindex 502f724243..d61010c5fc 100644--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts@@ -166,7 +166,6 @@ export const SetRowHiddenCommand: ICommand = {const setSelectionOperationParams: ISetSelectionsOperationParams = {unitId,subUnitId,-selections: getSelectionsAfterHiding(ranges).map((range) => ({range,primary: getPrimaryForRange(range, worksheet),diff --git a/packages/sheets/src/commands/operations/selection.operation.ts b/packages/sheets/src/commands/operations/selection.operation.tsindex a02ac6c0dc..a5f0963a4c 100644--- a/packages/sheets/src/commands/operations/selection.operation.ts+++ b/packages/sheets/src/commands/operations/selection.operation.ts@@ -18,8 +18,8 @@ import type { IOperation } from '@univerjs/core';import { CommandType } from '@univerjs/core';import type { ISelectionWithStyle } from '../../basics/selection';-import type { SelectionMoveType } from '../../services/selections/selection-manager.service';import { getSelectionsService } from '../utils/selection-command-util';+import type { SelectionMoveType } from '../../services/selections/selection-manager.service';export interface ISetSelectionsOperationParams {unitId: string;diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 7eaea5bb03..b04d3999c5 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -63,7 +63,7 @@ export {SelectionMoveType,DISABLE_NORMAL_SELECTIONS,} from './services/selections/selection-manager.service';-export { IRefSelectionsService } from './services/selections/ref-selections.service';+export { IRefSelectionsService, RefSelectionsService } from './services/selections/ref-selections.service';export { getAddMergeMutationRangeByType } from './controllers/merge-cell.controller';export { NumfmtService } from './services/numfmt/numfmt.service';diff --git a/packages/sheets/src/services/selections/ref-selections.service.ts b/packages/sheets/src/services/selections/ref-selections.service.tsindex 0a84a45f22..b0ebcbc8be 100644--- a/packages/sheets/src/services/selections/ref-selections.service.ts+++ b/packages/sheets/src/services/selections/ref-selections.service.ts@@ -14,8 +14,13 @@* limitations under the License.*/-import type { SheetsSelectionsService } from '@univerjs/sheets';+import type { Workbook } from '@univerjs/core';+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';+import type { Observable } from 'rxjs';+import { BehaviorSubject, map, merge, switchMap, takeUntil } from 'rxjs';+import type { WorkbookSelections } from './selection-manager.service';+import { SheetsSelectionsService } from './selection-manager.service';/*** Ref selections service reuses code of `SelectionManagerService`. And it only contains ref selections@@ -25,5 +30,38 @@ import { createIdentifier } from '@wendellhu/redi';*/export const IRefSelectionsService = createIdentifier<SheetsSelectionsService>('sheets-formula.ref-selections.service');-// TODO@wzhudev: `IRefSelectionsService` should have a total different implementation than `SheetsSelectionsService`-// because ref ranges could from different units in a formula.+/**+ * RefSelectionsService treats `selectionMoveStart$` `selectionMoving$` and `selectionMoveEnd$` differently+ * than `SheetsSelectionsService`. Because ref selections can be in different workbooks.+ */+export class RefSelectionsService extends SheetsSelectionsService {+ constructor(+ @IUniverInstanceService _instanceSrv: IUniverInstanceService+ ) {+ super(_instanceSrv);+ }++ protected override _init(): void {+ const $ = this._getAliveWorkbooks$().pipe(takeUntil(this.dispose$));+ this.selectionMoveStart$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoveStart$))));+ this.selectionMoving$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoving$))));+ this.selectionMoveEnd$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoveEnd$))));+ }++ private _getAliveWorkbooks$(): Observable<WorkbookSelections[]> {+ const aliveWorkbooks = this._instanceSrv.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ aliveWorkbooks.forEach((workbook) => this._ensureWorkbookSelection(workbook.getUnitId()));++ const workbooks$ = new BehaviorSubject(aliveWorkbooks);+ this.disposeWithMe(this._instanceSrv.getTypeOfUnitAdded$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {+ this._ensureWorkbookSelection(workbook.getUnitId());+ workbooks$.next([...workbooks$.getValue(), workbook]);+ }));+ this.disposeWithMe(this._instanceSrv.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {+ this._removeWorkbookSelection(workbook.getUnitId());+ workbooks$.next(workbooks$.getValue().filter((unit) => unit !== workbook));+ }));++ return workbooks$.pipe(map((workbooks) => workbooks.map((w) => this._ensureWorkbookSelection(w.getUnitId()))));+ }+}diff --git a/packages/sheets/src/services/selections/selection-manager.service.ts b/packages/sheets/src/services/selections/selection-manager.service.tsindex 0c37b7e8ec..d7889410d9 100644--- a/packages/sheets/src/services/selections/selection-manager.service.ts+++ b/packages/sheets/src/services/selections/selection-manager.service.ts@@ -41,22 +41,26 @@ export class SheetsSelectionsService extends RxDisposable {return { unitId: workbook.getUnitId(), sheetId: worksheet.getSheetId() };}- readonly selectionMoveStart$: Observable<Nullable<ISelectionWithStyle[]>>;- readonly selectionMoving$: Observable<Nullable<ISelectionWithStyle[]>>;- readonly selectionMoveEnd$: Observable<ISelectionWithStyle[]>;+ selectionMoveStart$: Observable<Nullable<ISelectionWithStyle[]>>;+ selectionMoving$: Observable<Nullable<ISelectionWithStyle[]>>;+ selectionMoveEnd$: Observable<ISelectionWithStyle[]>;constructor(- @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService+ @IUniverInstanceService protected readonly _instanceSrv: IUniverInstanceService) {super();+ this._init();+ }+ protected _init(): void {const c$ = this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).pipe(shareReplay(1), takeUntil(this.dispose$));+this.selectionMoveStart$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveStart$));this.selectionMoving$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoving$));this.selectionMoveEnd$ = c$.pipe(switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveEnd$));this._instanceSrv.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {- this._workbookSelections.delete(workbook.getUnitId());+ this._removeWorkbookSelection(workbook.getUnitId());});}@@ -144,7 +148,7 @@ export class SheetsSelectionsService extends RxDisposable {);}- private _getCurrentSelections() {+ protected _getCurrentSelections() {const current = this._currentSelectionPos;if (!current) {return [];@@ -158,8 +162,8 @@ export class SheetsSelectionsService extends RxDisposable {return this._ensureWorkbookSelection(unitId);}- private _workbookSelections = new Map<string, WorkbookSelections>();- private _ensureWorkbookSelection(unitId: string): WorkbookSelections {+ protected _workbookSelections = new Map<string, WorkbookSelections>();+ protected _ensureWorkbookSelection(unitId: string): WorkbookSelections {let wbSelection = this._workbookSelections.get(unitId);if (!wbSelection) {const workbook = this._instanceSrv.getUnit<Workbook>(unitId);@@ -173,6 +177,10 @@ export class SheetsSelectionsService extends RxDisposable {return wbSelection;}++ protected _removeWorkbookSelection(unitId: string): void {+ this._workbookSelections.delete(unitId);+ }}/**diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.tsindex de0bc871f2..bf9310fd44 100644--- a/packages/sheets/src/sheets-plugin.ts+++ b/packages/sheets/src/sheets-plugin.ts@@ -29,7 +29,6 @@ import { INumfmtService } from './services/numfmt/type';import { WorkbookPermissionService } from './services/permission/workbook-permission/workbook-permission.service';import { RefRangeService } from './services/ref-range/ref-range.service';-import { SheetsSelectionsService } from './services/selections/selection-manager.service';import { SheetInterceptorService } from './services/sheet-interceptor/sheet-interceptor.service';import { DefinedNameDataController } from './controllers/defined-name-data.controller';import { WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from './services/permission/worksheet-permission';@@ -40,6 +39,7 @@ import { RangeProtectionRefRangeService } from './services/permission/range-permimport { RangeProtectionService } from './services/permission/range-permission/range-protection.service';import { ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY } from './controllers/config';import { NumberCellDisplayController } from './controllers/number-cell.controller';+import { SheetsSelectionsService } from './services/selections/selection-manager.service';const PLUGIN_NAME = 'SHEET_PLUGIN';diff --git a/packages/docs-ui/src/views/doc-background/DocBackground.tsx b/packages/ui/src/const.tssimilarity index 73%rename from packages/docs-ui/src/views/doc-background/DocBackground.tsxrename to packages/ui/src/const.tsindex 411817dd76..c0d5698ebe 100644--- a/packages/docs-ui/src/views/doc-background/DocBackground.tsx+++ b/packages/ui/src/const.ts@@ -14,15 +14,7 @@* limitations under the License.*/-import React from 'react';--import styles from './index.module.less';-/**- * Doc standalone background+ * @ignore*/-export const DocBackground = () => {- return (- <div className={styles.docsUiCanvasBackground}></div>- );-};+export const UNI_DISABLE_CHANGING_FOCUS_KEY = 'UNI_DISABLE_CHANGING_FOCUS';diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsxindex 165c3f63b2..d2f43bccf8 100644--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx@@ -24,10 +24,10 @@ import { render as createRoot, unmount } from 'rc-util/lib/React/render';import React from 'react';import { ILayoutService } from '../../services/layout/layout.service';-import { DesktopApp } from '../../views/DesktopApp';import { BuiltInUIPart, IUIPartsService } from '../../services/parts/parts.service';import { CanvasPopup } from '../../views/components/popup/CanvasPopup';import { FloatDom } from '../../views/components/dom/FloatDom';+import { DesktopWorkbench } from '../../views/workbench/Workbench';import { type IUniverUIConfig, type IWorkbenchOptions, UI_CONFIG_KEY } from './ui.controller';const STEADY_TIMEOUT = 3000;@@ -113,7 +113,7 @@ function bootstrap(mountContainer = createContainer('univer');}- const ConnectedApp = connectInjector(DesktopApp, injector);+ const ConnectedApp = connectInjector(DesktopWorkbench, injector);const onRendered = (canvasElement: HTMLElement) => callback(canvasElement, mountContainer);function render() {diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex dcbd93972e..9d799a53a8 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -27,7 +27,7 @@ export {SharedController,UndoShortcutItem,} from './controllers/shared-shortcut.controller';-export { UI_CONFIG_KEY, IUIController, type IWorkbenchOptions } from './controllers/ui/ui.controller';+export { UI_CONFIG_KEY, IUIController, type IWorkbenchOptions, type IUniverUIConfig } from './controllers/ui/ui.controller';export { DesktopUIController } from './controllers/ui/ui-desktop.controller';export { IUIPartsService, BuiltInUIPart, UIPartsService } from './services/parts/parts.service';export { DesktopBeforeCloseService, IBeforeCloseService } from './services/before-close/before-close.service';@@ -86,14 +86,19 @@ export { ComponentContainer, useComponentsOfPart, type IComponentContainerPropsexport { IEditorService, EditorService } from './services/editor/editor.service';export { TextEditor } from './components/editor/TextEditor';export { RangeSelector } from './components/range-selector/RangeSelector';-export { IRangeSelectorService } from './services/range-selector/range-selector.service';-export { DesktopLocalStorageService } from './services/local-storage/local-storage.service';-export { CanvasPopupService, ICanvasPopupService, type IPopup } from './services/popup/canvas-popup.service';export { ProgressBar } from './components/progress-bar/ProgressBar';export { type IMenuGroup, useToolbarGroups, useToolbarItemStatus, useToolbarCollapseObserver } from './views/components/doc-bars/hook';export { mergeMenuConfigs } from './common/menu-merge-configs';-export { IProgressService, ProgressService } from './services/progress/progress.service';-export type { IProgressStep } from './services/progress/progress.service';+export { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';+export { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';+export { IProgressService, type IProgressCount, type IProgressStep, ProgressService } from './services/progress/progress.service';+export { type IRangeSelectorRange, IRangeSelectorService, RangeSelectorService } from './services/range-selector/range-selector.service';+export { CanvasPopupService, ICanvasPopupService, type IPopup } from './services/popup/canvas-popup.service';+export { UNIVER_UI_PLUGIN_NAME } from './ui-plugin';+export { ErrorController } from './controllers/error/error.controller';+export { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.service';+export { DesktopLocalStorageService } from './services/local-storage/local-storage.service';+export { UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';// #region - workbench components@@ -106,6 +111,7 @@ export { CanvasPopup } from './views/components/popup/CanvasPopup';export { CanvasFloatDomService, type IFloatDomLayout } from './services/dom/canvas-dom-layer.service';export { FloatDom } from './views/components/dom/FloatDom';export { MobileContextMenu } from './views/components/context-menu/MobileContextMenu';+export { Toolbar } from './views/components/doc-bars/Toolbar';// #endregiondiff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.tsindex 755f7714ae..c13506c6f7 100644--- a/packages/ui/src/ui-plugin.ts+++ b/packages/ui/src/ui-plugin.ts@@ -57,9 +57,7 @@ import { IProgressService, ProgressService } from './services/progress/progress.import { IUIPartsService, UIPartsService } from './services/parts/parts.service';import { CanvasFloatDomService } from './services/dom/canvas-dom-layer.service';-const PLUGIN_NAME = 'ui';--export const DefaultUiConfig = {};+export const UNIVER_UI_PLUGIN_NAME = 'UNIVER_UI_PLUGIN';export const DISABLE_AUTO_FOCUS_KEY = 'DISABLE_AUTO_FOCUS';@@ -68,7 +66,7 @@ export const DISABLE_AUTO_FOCUS_KEY = 'DISABLE_AUTO_FOCUS';*/@DependentOn(UniverRenderEnginePlugin)export class UniverUIPlugin extends Plugin {- static override pluginName = PLUGIN_NAME;+ static override pluginName = UNIVER_UI_PLUGIN_NAME;constructor(private _config: Partial<IUniverUIConfig> = {},@@ -77,8 +75,7 @@ export class UniverUIPlugin extends Plugin {) {super();- this._config = Tools.deepMerge({}, DefaultUiConfig, this._config);-+ this._config = Tools.deepMerge({}, this._config);if (this._config.disableAutoFocus) {this._contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);}@@ -89,7 +86,6 @@ export class UniverUIPlugin extends Plugin {[ComponentManager],[ZIndexManager],- // services[ShortcutPanelService],[IUIPartsService, { useClass: UIPartsService }],[ILayoutService, { useClass: DesktopLayoutService }],@@ -112,29 +108,19 @@ export class UniverUIPlugin extends Plugin {[ICanvasPopupService, { useClass: CanvasPopupService }],[IProgressService, { useClass: ProgressService }],[CanvasFloatDomService],-- // controllers- [- IUIController, {- useFactory: (injector: Injector) => injector.createInstance(DesktopUIController, this._config),- deps: [Injector],- },- ],- [- SharedController,- {- useFactory: () => this._injector.createInstance(SharedController, this._config),- },+ [IUIController, {+ useFactory: (injector: Injector) => injector.createInstance(DesktopUIController, this._config),+ deps: [Injector],+ },],+ [SharedController, {+ useFactory: () => this._injector.createInstance(SharedController, this._config),+ }],[ErrorController],- [- ShortcutPanelController,- {- useFactory: () => this._injector.createInstance(ShortcutPanelController, this._config),- },- ],+ [ShortcutPanelController, {+ useFactory: () => this._injector.createInstance(ShortcutPanelController, this._config),+ }],], this._config.override);-dependencies.forEach((dependency) => injector.add(dependency));}}diff --git a/packages/ui/src/views/DesktopApp.tsx b/packages/ui/src/views/workbench/Workbench.tsxsimilarity index 79%rename from packages/ui/src/views/DesktopApp.tsxrename to packages/ui/src/views/workbench/Workbench.tsxindex 124b158b2a..e08558d331 100644--- a/packages/ui/src/views/DesktopApp.tsx+++ b/packages/ui/src/views/workbench/Workbench.tsx@@ -19,26 +19,27 @@ import type { ILocale } from '@univerjs/design';import { ConfigContext, ConfigProvider, defaultTheme, themeInstance } from '@univerjs/design';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';-import { createPortal } from 'react-dom';-import type { IWorkbenchOptions } from '../controllers/ui/ui.controller';-import { IMessageService } from '../services/message/message.service';-import { BuiltInUIPart } from '../services/parts/parts.service';-import styles from './app.module.less';-import { ComponentContainer, useComponentsOfPart } from './components/ComponentContainer';-import { Toolbar } from './components/doc-bars/Toolbar';-import { Sidebar } from './components/sidebar/Sidebar';-import { ZenZone } from './components/zen-zone/ZenZone';-import { builtInGlobalComponents } from './parts';-import { DesktopContextMenu } from './components/context-menu/ContextMenu';--export interface IUniverAppProps extends IWorkbenchOptions {+import { createPortal } from 'react-dom';+import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';+import { IMessageService } from '../../services/message/message.service';+import { BuiltInUIPart } from '../../services/parts/parts.service';+import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';+import { DesktopContextMenu } from '../components/context-menu/ContextMenu';+import { Toolbar } from '../components/doc-bars/Toolbar';+import { Sidebar } from '../components/sidebar/Sidebar';+import { ZenZone } from '../components/zen-zone/ZenZone';+import { builtInGlobalComponents } from '../parts';++import styles from './workbench.module.less';++export interface IUniverWorkbenchProps extends IWorkbenchOptions {mountContainer: HTMLElement;onRendered?: (container: HTMLElement) => void;}-export function DesktopApp(props: IUniverAppProps) {+export function DesktopWorkbench(props: IUniverWorkbenchProps) {const {header = true,toolbar = true,@@ -108,28 +109,28 @@ export function DesktopApp(props: IUniverAppProps) {* all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events* bubbled to this element and refocus the input element.*/}- <div className={styles.appLayout} tabIndex={-1} onBlur={(e) => e.stopPropagation()}>+ <div className={styles.workbenchLayout} tabIndex={-1} onBlur={(e) => e.stopPropagation()}>{/* header */}{header && toolbar && (- <header className={styles.appContainerHeader}>+ <header className={styles.workbenchContainerHeader}><Toolbar headerMenuComponents={headerMenuComponents} /></header>)}{/* content */}- <section className={styles.appContainer}>- <div className={styles.appContainerWrapper}>- <aside className={styles.appContainerLeftSidebar}>+ <section className={styles.workbenchContainer}>+ <div className={styles.workbenchContainerWrapper}>+ <aside className={styles.workbenchContainerLeftSidebar}><ComponentContainer key="left-sidebar" components={leftSidebarComponents} /></aside>- <section className={styles.appContainerContent}>+ <section className={styles.workbenchContainerContent}><header>{header && <ComponentContainer key="header" components={headerComponents} />}</header><section- className={styles.appContainerCanvas}+ className={styles.workbenchContainerCanvas}ref={contentRef}data-range-selectoronContextMenu={(e) => e.preventDefault()}@@ -138,18 +139,17 @@ export function DesktopApp(props: IUniverAppProps) {</section></section>- <aside className={styles.appContainerSidebar}>+ <aside className={styles.workbenchContainerSidebar}><Sidebar /></aside></div>{/* footer */}{footer && (- <footer className={styles.appFooter}>+ <footer className={styles.workbenchFooter}><ComponentContainer key="footer" components={footerComponents} sharedProps={{ contextMenu }} /></footer>)}-<ZenZone /></section></div>diff --git a/packages/ui/src/views/app.module.less b/packages/ui/src/views/workbench/workbench.module.lesssimilarity index 98%rename from packages/ui/src/views/app.module.lessrename to packages/ui/src/views/workbench/workbench.module.lessindex b71c767e9f..b2055ca40f 100644--- a/packages/ui/src/views/app.module.less+++ b/packages/ui/src/views/workbench/workbench.module.less@@ -1,4 +1,4 @@-.app {+.workbench {&-layout {display: flex;flex-direction: column;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c960d74711..e10eee2ae3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -333,9 +333,15 @@ importers:'@univerjs/ui':specifier: workspace:*version: link:../packages/ui+ '@univerjs/uni-formula':+ specifier: workspace:*+ version: link:../packages-experimental/uni-formula'@univerjs/uniscript':specifier: workspace:*version: link:../packages/uniscript+ '@univerjs/uniui':+ specifier: workspace:*+ version: link:../packages-experimental/uniui'@wendellhu/redi':specifier: 0.16.0version: 0.16.0@@ -392,6 +398,146 @@ importers:specifier: ^5.5.3version: 5.5.3+ packages-experimental/uni-formula:+ dependencies:+ '@univerjs/icons':+ specifier: ^0.1.46+ devDependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: link:../../packages/core+ '@univerjs/design':+ specifier: workspace:*+ version: link:../../packages/design+ '@univerjs/docs':+ specifier: workspace:*+ version: link:../../packages/docs+ '@univerjs/engine-formula':+ specifier: workspace:*+ version: link:../../packages/engine-formula+ '@univerjs/rpc':+ specifier: workspace:*+ version: link:../../packages/rpc+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/sheets-formula':+ specifier: workspace:*+ version: link:../../packages/sheets-formula+ '@univerjs/ui':+ specifier: workspace:*+ version: link:../../packages/ui+ '@wendellhu/redi':+ specifier: 0.16.0+ version: 0.16.0+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ less:+ specifier: ^4.2.0+ version: 4.2.0+ react:+ specifier: 18.2.0+ version: 18.2.0+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.5.3+ vite:+ specifier: ^5.3.4+ vitest:+ specifier: ^2.0.3+ version: 2.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ packages-experimental/uni-formula-ui:+ devDependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: link:../../packages/core+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/uni-formula':+ specifier: workspace:*+ version: link:../uni-formula+ '@wendellhu/redi':+ specifier: 0.16.0+ version: 0.16.0+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.5.3+ vite:+ specifier: ^5.3.4+ vitest:+ specifier: ^2.0.3+ version: 2.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ packages-experimental/uniui:+ dependencies:+ '@univerjs/icons':+ specifier: ^0.1.46+ rc-util:+ specifier: ^5.43.0+ devDependencies:+ '@types/react':+ specifier: ^18.3.3+ version: 18.3.3+ '@types/react-dom':+ specifier: ^18.3.0+ version: 18.3.0+ '@univerjs/core':+ specifier: workspace:*+ version: link:../../packages/core+ '@univerjs/design':+ specifier: workspace:*+ version: link:../../packages/design+ '@univerjs/engine-render':+ specifier: workspace:*+ version: link:../../packages/engine-render+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/ui':+ specifier: workspace:*+ version: link:../../packages/ui+ '@wendellhu/redi':+ specifier: 0.16.0+ version: 0.16.0+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ less:+ specifier: ^4.2.0+ version: 4.2.0+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-dom:+ specifier: 18.3.1+ version: 18.3.1([email protected])+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.5.3+ vite:+ specifier: ^5.3.4+ vitest:+ specifier: ^2.0.3+ version: 2.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+packages/core:dependencies:'@univerjs/protocol':@@ -5492,6 +5638,12 @@ packages:'@univerjs/[email protected]':resolution: {integrity: sha512-c7DmkpQMt4jNSCdfPNf3sUczrdFCnABjupaJEO3CpWe556sIAcHY3kEfcrtOgbkTjGcmS07PD88Ai3s6K3eQug==}+ '@univerjs/[email protected]':+ resolution: {integrity: sha512-tnWFQ7IojxovMaYTKMOdAcwEBMm6JV+6XygOUTYwqf+YHwRsEePdQ7Tl0u1mtJAmzDssATLcb3t8xGb3wh6YuA==}+ peerDependencies:+ react: '*'+ react-dom: '*'+'@univerjs/[email protected]':resolution: {integrity: sha512-nKCsfxG2pwHT2x9nTwHvVUGr/dQxAQi76zvhJprm0Gqu8ywQdcCq7vX6D7fHiFwZPGQVO/91gbbwGfsG93mIpg==}peerDependencies:@@ -9708,6 +9860,10 @@ packages:react: '>=16.6.0'react-dom: '>=16.6.0'+ resolution: {integrity: sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==}+ engines: {node: '>=0.10.0'}+resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}engines: {node: '>=0.10.0'}@@ -14462,6 +14618,16 @@ snapshots:'@univerjs/[email protected]': {}+ dependencies:+ react: 18.2.0+ react-dom: 18.3.1([email protected])++ dependencies:+ react: 18.3.1+ react-dom: 18.3.1([email protected])+dependencies:react: 18.3.1@@ -19086,6 +19252,12 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ loose-envify: 1.4.0+ react: 18.2.0+ scheduler: 0.23.2+dependencies:loose-envify: 1.4.0@@ -19207,6 +19379,10 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])+ dependencies:+ loose-envify: 1.4.0+dependencies:loose-envify: 1.4.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 7b57b4ca0a..b8502a4abf 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,4 +1,5 @@packages:- common/*- packages/*+ - packages-experimental/*- examples