Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(sheets-formula): support writing formula array cache to snapshot (#5283)
Evandd281f0c57e9
diff --git a/examples/esbuild.config.ts b/examples/esbuild.config.tsindex 8be365bb49..a65c104b3f 100644--- a/examples/esbuild.config.ts+++ b/examples/esbuild.config.ts@@ -108,6 +108,8 @@ const entryPoints = ['./src/sheets/main.ts','./src/sheets/worker.ts',+ './src/sheets-no-worker/main.ts',+// sheets-multi'./src/sheets-multi/main.tsx',diff --git a/examples/src/main.tsx b/examples/src/main.tsxindex 9a51f9ef65..2e09ffb5aa 100644--- a/examples/src/main.tsx+++ b/examples/src/main.tsx@@ -49,6 +49,9 @@ function Examples() {}, {title: '📽️ Slides',href: './slides/',+ }, {+ title: '🗂️ Sheets No Worker',+ href: './sheets-no-worker/',}, {title: '🗂️ Sheets Multi Instance',href: './sheets-multi/',diff --git a/examples/src/sheets-no-worker/lazy.ts b/examples/src/sheets-no-worker/lazy.tsnew file mode 100644index 0000000000..2c843fb642--- /dev/null+++ b/examples/src/sheets-no-worker/lazy.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { Plugin, PluginCtor } from '@univerjs/core';+import { UniverDocsDrawingUIPlugin } from '@univerjs/docs-drawing-ui';+import { UniverDocsMentionUIPlugin } from '@univerjs/docs-mention-ui';+import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';+import { UniverSheetsDataValidationUIPlugin } from '@univerjs/sheets-data-validation-ui';+import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';+import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';+import { UniverSheetsFormulaUIPlugin } from '@univerjs/sheets-formula-ui';+import { UniverSheetsNoteUIPlugin } from '@univerjs/sheets-note-ui';+import { UniverSheetsNumfmtUIPlugin } from '@univerjs/sheets-numfmt-ui';+import { UniverSheetsTableUIPlugin } from '@univerjs/sheets-table-ui';+import { UniverSheetsThreadCommentUIPlugin } from '@univerjs/sheets-thread-comment-ui';+import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';++export default function getLazyPlugins(): Array<[PluginCtor<Plugin>] | [PluginCtor<Plugin>, unknown]> {+ return [+ [UniverDocsDrawingUIPlugin],+ [UniverDocsMentionUIPlugin],+ [UniverSheetsNumfmtUIPlugin],+ [UniverThreadCommentUIPlugin],+ [UniverSheetsThreadCommentUIPlugin],+ [UniverSheetsNoteUIPlugin],+ [UniverSheetsTableUIPlugin],+ [UniverSheetsFormulaUIPlugin],+ [UniverSheetsDataValidationUIPlugin],+ [UniverSheetsConditionalFormattingUIPlugin],+ [UniverSheetsFilterUIPlugin, { useRemoteFilterValuesGenerator: false }],+ [UniverSheetsDrawingUIPlugin],+ ];+}diff --git a/examples/src/sheets-no-worker/main.ts b/examples/src/sheets-no-worker/main.tsnew file mode 100644index 0000000000..748b19d27c--- /dev/null+++ b/examples/src/sheets-no-worker/main.ts@@ -0,0 +1,176 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { UniverDebuggerPlugin } from '@univerjs/debugger';+import { UniverDocsPlugin } from '@univerjs/docs';+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';+import { DEFAULT_WORKBOOK_DATA_DEMO } from '@univerjs/mockdata';+import zhCN from '@univerjs/mockdata/locales/zh-CN';+import { UniverNetworkPlugin } from '@univerjs/network';+import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import { UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';+import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';+import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';+import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';+import { UniverSheetsNotePlugin } from '@univerjs/sheets-note';+import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';+import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';+import { UniverSheetsTablePlugin } from '@univerjs/sheets-table';+import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';+import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';+import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';+import { UniverUIPlugin } from '@univerjs/ui';++import '@univerjs/sheets/facade';+import '@univerjs/ui/facade';+import '@univerjs/docs-ui/facade';+import '@univerjs/sheets-ui/facade';+import '@univerjs/sheets-data-validation/facade';+import '@univerjs/engine-formula/facade';+import '@univerjs/sheets-filter/facade';+import '@univerjs/sheets-formula/facade';+import '@univerjs/sheets-numfmt/facade';+import '@univerjs/sheets-hyper-link-ui/facade';+import '@univerjs/sheets-thread-comment/facade';+import '@univerjs/sheets-conditional-formatting/facade';+import '@univerjs/sheets-find-replace/facade';+import '@univerjs/sheets-drawing-ui/facade';+import '@univerjs/sheets-zen-editor/facade';+import '@univerjs/sheets-crosshair-highlight/facade';+import '@univerjs/sheets-formula-ui/facade';+import '@univerjs/sheets-table/facade';+import '@univerjs/sheets-sort/facade';+import '@univerjs/network/facade';+import '@univerjs/sheets-note/facade';+import '../global.css';++/* eslint-disable-next-line node/prefer-global/process */+const IS_E2E: boolean = !!process.env.IS_E2E;++const LOAD_LAZY_PLUGINS_TIMEOUT = 100;+const LOAD_VERY_LAZY_PLUGINS_TIMEOUT = 1_000;++export 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,+};++// eslint-disable-next-line max-lines-per-function+function createNewInstance() {+ // univer+ const univer = new Univer({+ // theme: greenTheme,+ darkMode: localStorage.getItem('local.darkMode') === 'dark',+ locale: LocaleType.ZH_CN,+ locales: {+ [LocaleType.ZH_CN]: zhCN,+ },+ logLevel: LogLevel.VERBOSE,+ });++ const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });+ univer.registerPlugin(UniverRPCMainThreadPlugin, { workerURL: worker });++ univer.registerPlugin(UniverDocsPlugin);+ univer.registerPlugin(UniverRenderEnginePlugin);+ univer.registerPlugin(UniverUIPlugin, {+ container: 'app',+ // ribbonType: 'simple',+ });+ univer.registerPlugin(UniverDocsUIPlugin);++ univer.registerPlugin(UniverSheetsPlugin, {+ autoHeightForMergedCells: true,+ });+ univer.registerPlugin(UniverSheetsUIPlugin);+ univer.registerPlugin(UniverSheetsNumfmtPlugin);+ univer.registerPlugin(UniverSheetsZenEditorPlugin);+ univer.registerPlugin(UniverFormulaEnginePlugin);+ univer.registerPlugin(UniverSheetsFormulaPlugin, { writeArrayFormulaToSnapshot: true });+ univer.registerPlugin(UniverSheetsDataValidationPlugin);+ univer.registerPlugin(UniverSheetsConditionalFormattingPlugin);+ univer.registerPlugin(UniverSheetsFilterPlugin);+ univer.registerPlugin(UniverSheetsSortPlugin);+ univer.registerPlugin(UniverSheetsHyperLinkPlugin);+ univer.registerPlugin(UniverSheetsThreadCommentPlugin);++ univer.registerPlugin(UniverSheetsTablePlugin);+ univer.registerPlugin(UniverNetworkPlugin);+ univer.registerPlugin(UniverSheetsNotePlugin);++ // If we are running in e2e platform, we should immediately register the debugger plugin.+ if (IS_E2E) {+ univer.registerPlugin(UniverDebuggerPlugin, {+ fab: false,+ performanceMonitor: {+ enabled: false,+ },+ });+ }++ const injector = univer.__getInjector();+ const userManagerService = injector.get(UserManagerService);+ userManagerService.setCurrentUser(mockUser);++ // create univer sheet instance+ if (!IS_E2E) {+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);+ }++ setTimeout(() => {+ import('./lazy').then((lazy) => {+ const plugins = lazy.default();+ plugins.forEach((p) => univer.registerPlugin(p[0], p[1]));+ });+ }, LOAD_LAZY_PLUGINS_TIMEOUT);++ setTimeout(() => {+ import('./very-lazy').then((lazy) => {+ const plugins = lazy.default();+ plugins.forEach((p) => univer.registerPlugin(p[0], p[1]));+ });+ }, LOAD_VERY_LAZY_PLUGINS_TIMEOUT);++ univer.onDispose(() => {+ worker.terminate();+ window.univer = undefined;+ window.univerAPI = undefined;+ });++ window.univer = univer;+ window.univerAPI = FUniver.newAPI(univer);+}++createNewInstance();+window.createNewInstance = createNewInstance;++declare global {+ // eslint-disable-next-line ts/naming-convention+ interface Window {+ univer?: Univer;+ univerAPI?: ReturnType<typeof FUniver.newAPI>;+ createNewInstance?: typeof createNewInstance;+ }+}diff --git a/examples/src/sheets-no-worker/very-lazy.ts b/examples/src/sheets-no-worker/very-lazy.tsnew file mode 100644index 0000000000..588f3d4e4f--- /dev/null+++ b/examples/src/sheets-no-worker/very-lazy.ts@@ -0,0 +1,62 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { Plugin, PluginCtor } from '@univerjs/core';+import { UniverActionRecorderPlugin } from '@univerjs/action-recorder';+import { UniverDebuggerPlugin } from '@univerjs/debugger';+import { UniverSheetsCrosshairHighlightPlugin } from '@univerjs/sheets-crosshair-highlight';+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';+import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';+import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';+import { UniverUniscriptPlugin } from '@univerjs/uniscript';+import { UniverWatermarkPlugin } from '@univerjs/watermark';++/* eslint-disable-next-line node/prefer-global/process */+const IS_E2E: boolean = !!process.env.IS_E2E;++export default function getVeryLazyPlugins() {+ const plugins: Array<[PluginCtor<Plugin>] | [PluginCtor<Plugin>, unknown]> = [+ [UniverActionRecorderPlugin],+ [UniverSheetsHyperLinkUIPlugin],+ [UniverSheetsSortUIPlugin],+ [UniverSheetsCrosshairHighlightPlugin],+ [UniverSheetsFindReplacePlugin],+ [UniverWatermarkPlugin],+ ];++ if (!IS_E2E) {+ plugins.push([UniverDebuggerPlugin]);+ plugins.push([UniverUniscriptPlugin, {+ getWorkerUrl(_: string, label: string) {+ if (label === 'json') {+ return '/vs/language/json/json.worker.js';+ }+ if (label === 'css' || label === 'scss' || label === 'less') {+ return '/vs/language/css/css.worker.js';+ }+ if (label === 'html' || label === 'handlebars' || label === 'razor') {+ return '/vs/language/html/html.worker.js';+ }+ if (label === 'typescript' || label === 'javascript') {+ return '/vs/language/typescript/ts.worker.js';+ }+ return '/vs/editor/editor.worker.js';+ },+ }]);+ }++ return plugins;+}diff --git a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.tsindex 75ab8ffe23..4d6e5f4e93 100644--- a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts+++ b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts@@ -15,14 +15,18 @@*/import type { ICommandInfo } from '@univerjs/core';-import type { ISetArrayFormulaDataMutationParams } from '@univerjs/engine-formula';-import { CellValueType, Disposable, ICommandService, Inject, InterceptorEffectEnum, isRealNum } from '@univerjs/core';+import type { IArrayFormulaUnitCellType, ISetArrayFormulaDataMutationParams } from '@univerjs/engine-formula';+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';+import type { IUniverSheetsFormulaBaseConfig } from './config.schema';+import { CellValueType, Disposable, ICommandService, IConfigService, Inject, InterceptorEffectEnum, isRealNum } from '@univerjs/core';import { FormulaDataModel, SetArrayFormulaDataMutation, stripErrorMargin } from '@univerjs/engine-formula';-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';+import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';+import { PLUGIN_CONFIG_KEY_BASE } from './config.schema';export class ArrayFormulaCellInterceptorController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,+ @IConfigService private readonly _configService: IConfigService,@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel) {@@ -54,16 +58,34 @@ export class ArrayFormulaCellInterceptorController extends Disposable {const { arrayFormulaRange, arrayFormulaCellData } = params;this._formulaDataModel.setArrayFormulaRange(arrayFormulaRange);this._formulaDataModel.setArrayFormulaCellData(arrayFormulaCellData);++ if (this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE)?.writeArrayFormulaToSnapshot) {+ this._writeArrayFormulaToSnapshot(arrayFormulaCellData);+ }}));}+ private _writeArrayFormulaToSnapshot(arrayFormulaCellData: IArrayFormulaUnitCellType) {+ Array.from(Object.entries(arrayFormulaCellData)).forEach(([unitId, subUnitData]) => {+ subUnitData && Array.from(Object.entries(subUnitData)).forEach(([subUnitId, rowData]) => {+ // Keep this local to avoid triggering re-calculate in the worker.+ this._commandService.executeCommand<ISetRangeValuesMutationParams>(SetRangeValuesMutation.id, {+ unitId,+ subUnitId,+ cellValue: rowData,+ }, { onlyLocal: true });+ });+ });+ }+private _initInterceptorCellContent() {this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {priority: 100,effect: InterceptorEffectEnum.Value,- handler: (cell, location, next) => {+ handler: (cell_, location, next) => {+ let cell = cell_;const { unitId, subUnitId, row, col } = location;const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();const cellData = arrayFormulaCellData?.[unitId]?.[subUnitId]?.[row]?.[col];diff --git a/packages/sheets-formula/src/controllers/config.schema.ts b/packages/sheets-formula/src/controllers/config.schema.tsindex 53afe1f2e2..c6b77a5cab 100644--- a/packages/sheets-formula/src/controllers/config.schema.ts+++ b/packages/sheets-formula/src/controllers/config.schema.ts@@ -50,6 +50,11 @@ export interface IUniverSheetsFormulaBaseConfig {* Define the calculation mode during initialization, default is `WHEN_EMPTY`*/initialFormulaComputing?: CalculationMode;++ /**+ * If true, the plugin will write array formula results to the snapshot. Normally you should not set this to true.+ */+ writeArrayFormulaToSnapshot?: boolean;}export const defaultPluginBaseConfig: IUniverSheetsFormulaBaseConfig = {};