Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheet): fill and ref (#634)

Univerb9e79893d488
diff --git a/packages/core/src/common/request-immediate-macro-task.ts b/packages/core/src/common/request-immediate-macro-task.ts
new file mode 100644
index 0000000000..324f3d63b0
--- /dev/null
+++ b/packages/core/src/common/request-immediate-macro-task.ts
@@ -0,0 +1,16 @@
+export function requestImmediateMacroTask(callback: (value?: unknown) => void): () => void {
+ const channel = new MessageChannel();
+ let cancelled = false;
+
+ channel.port1.onmessage = () => {
+ if (!cancelled) {
+ callback();
+ }
+ };
+
+ channel.port2.postMessage(null);
+
+ return () => {
+ cancelled = true;
+ };
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 50c9787ab1..8a76edc926 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -6,6 +6,7 @@ export {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
} from './common/const';
export { MemoryCursor } from './common/memory-cursor';
+export { requestImmediateMacroTask } from './common/request-immediate-macro-task';
export { type ISequenceExecuteResult, sequence, sequenceAsync } from './common/sequence';
export * from './docs/data-model';
export {
diff --git a/packages/engine-formula/src/analysis/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/analysis/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..69997c2aa8
--- /dev/null
+++ b/packages/engine-formula/src/analysis/__tests__/create-command-test-bed.ts
@@ -0,0 +1,101 @@
+import type { IWorkbookData } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { AstRootNodeFactory } from '../../ast-node/ast-root-node';
+import { FunctionNodeFactory } from '../../ast-node/function-node';
+import { LambdaNodeFactory } from '../../ast-node/lambda-node';
+import { LambdaParameterNodeFactory } from '../../ast-node/lambda-parameter-node';
+import { OperatorNodeFactory } from '../../ast-node/operator-node';
+import { PrefixNodeFactory } from '../../ast-node/prefix-node';
+import { ReferenceNodeFactory } from '../../ast-node/reference-node';
+import { SuffixNodeFactory } from '../../ast-node/suffix-node';
+import { UnionNodeFactory } from '../../ast-node/union-node';
+import { ValueNodeFactory } from '../../ast-node/value-node';
+import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';
+import { AstTreeBuilder } from '../parser';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '1': {
+ '1': {
+ v: 1,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+
+export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([AstTreeBuilder]);
+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);
+ injector.add([AstRootNodeFactory]);
+ injector.add([FunctionNodeFactory]);
+ injector.add([LambdaNodeFactory]);
+ injector.add([LambdaParameterNodeFactory]);
+ injector.add([OperatorNodeFactory]);
+ injector.add([PrefixNodeFactory]);
+ injector.add([ReferenceNodeFactory]);
+ injector.add([SuffixNodeFactory]);
+ injector.add([UnionNodeFactory]);
+ injector.add([ValueNodeFactory]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/engine-formula/src/analysis/__tests__/utils.spec.ts b/packages/engine-formula/src/analysis/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..bc7ea660e4
--- /dev/null
+++ b/packages/engine-formula/src/analysis/__tests__/utils.spec.ts
@@ -0,0 +1,90 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { LexerTreeBuilder } from '../lexer';
+import type { LexerNode } from '../lexer-node';
+
+describe('utils test', () => {
+ const lexer = new LexerTreeBuilder();
+
+ afterEach(() => {
+ lexer.dispose();
+ });
+
+ describe('lexer', () => {
+ it('lambda simple1', () => {
+ const node = lexer.treeBuilder(`=lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+1-max(100,200)`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"lambda","st":0,"ed":5,"children":[{"token":"L_1","st":14,"ed":16,"children":[{"token":"P_1","st":15,"ed":17,"children":[{"token":"sum","st":19,"ed":21,"children":[{"token":"P_1","st":19,"ed":21,"children":["1"]},{"token":"P_1","st":21,"ed":23,"children":["1","2","+","3","*"]}]}]},{"token":"P_1","st":30,"ed":32,"children":["2"]}]},{"token":"P_1","st":3,"ed":5,"children":["x"]},{"token":"P_1","st":5,"ed":7,"children":["y"]},{"token":"P_1","st":7,"ed":9,"children":[" x","y","x","*","*"]}]},"1",{"token":"max","st":39,"ed":41,"children":[{"token":"P_1","st":39,"ed":41,"children":["100"]},{"token":"P_1","st":43,"ed":45,"children":["200"]}]},"-","+"]}`
+ );
+ });
+
+ it('lambda mixed2', () => {
+ const node = lexer.treeBuilder(
+ `=(-(1+2)--@A1:B2 + 5)/2 + -sum(indirect(A5):B10# + B6# + A1:offset(C5, 1, 1) , 100) + {1,2,3;4,5,6;7,8,10} + lambda(x,y,z, x*y*z)(sum(1,(1+2)*3),2,lambda(x,y, @offset(A1:B0,x#*y#))(1,2):C20) + sum((1+2%)*30%, 1+2)%`
+ ) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"-","st":1,"ed":1,"children":[{"token":"P_1","st":-1,"ed":1,"children":["1","2","+"]}]},{"token":"-","st":-1,"ed":-1,"children":[{"token":"@","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B2 ","st":-1,"ed":-1,"children":[]}]}]}]}]}," 5","+","-","2 ","/",{"token":" -sum","st":24,"ed":28,"children":[{"token":"P_1","st":26,"ed":28,"children":[{"token":"#","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"indirect","st":30,"ed":37,"children":[{"token":"P_1","st":35,"ed":37,"children":["A5"]}]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B10","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"#","st":-1,"ed":-1,"children":[" B6"]},{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":" A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"offset","st":59,"ed":64,"children":[{"token":"P_1","st":62,"ed":64,"children":["C5"]},{"token":"P_1","st":65,"ed":67,"children":[" 1"]},{"token":"P_1","st":68,"ed":70,"children":[" 1"]}]}]}]}," +"," +"]},{"token":"P_1","st":74,"ed":76,"children":[" 100"]}]}," {1,2,3;4,5,6;7,8,10}",{"token":" lambda","st":109,"ed":115,"children":[{"token":"L_1","st":126,"ed":128,"children":[{"token":"P_1","st":127,"ed":129,"children":[{"token":"sum","st":131,"ed":133,"children":[{"token":"P_1","st":131,"ed":133,"children":["1"]},{"token":"P_1","st":133,"ed":135,"children":["1","2","+","3","*"]}]}]},{"token":"P_1","st":142,"ed":144,"children":["2"]},{"token":"P_1","st":144,"ed":146,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"lambda","st":148,"ed":153,"children":[{"token":"L_1","st":177,"ed":179,"children":[{"token":"P_1","st":178,"ed":180,"children":["1"]},{"token":"P_1","st":180,"ed":182,"children":["2"]}]},{"token":"P_1","st":151,"ed":153,"children":["x"]},{"token":"P_1","st":153,"ed":155,"children":["y"]},{"token":"P_1","st":155,"ed":157,"children":[{"token":" @offset","st":159,"ed":166,"children":[{"token":"P_1","st":164,"ed":166,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B0","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":170,"ed":172,"children":[{"token":"#","st":-1,"ed":-1,"children":["x"]},{"token":"#","st":-1,"ed":-1,"children":["y"]},"*"]}]}]}]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C20","st":-1,"ed":-1,"children":[]}]}]}]}]},{"token":"P_1","st":113,"ed":115,"children":["x"]},{"token":"P_1","st":115,"ed":117,"children":["y"]},{"token":"P_1","st":117,"ed":119,"children":["z"]},{"token":"P_1","st":119,"ed":121,"children":[" x","y","z","*","*"]}]},{"token":"%","st":-1,"ed":-1,"children":[{"token":" sum","st":193,"ed":196,"children":[{"token":"P_1","st":194,"ed":196,"children":["1",{"token":"%","st":-1,"ed":-1,"children":["2"]},"+",{"token":"%","st":-1,"ed":-1,"children":["30"]},"*"]},{"token":"P_1","st":205,"ed":207,"children":[" 1","2","+"]}]}]}," +"," +"," +","+"]}`
+ );
+ });
+
+ it('normal', () => {
+ const node = lexer.treeBuilder(
+ `=(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10)+count(B1:C10,10*5-100))*5-100`
+ ) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"sum","st":1,"ed":3,"children":[{"token":"P_1","st":1,"ed":3,"children":[{"token":"max","st":5,"ed":7,"children":[{"token":"P_1","st":5,"ed":7,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C10","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":12,"ed":14,"children":["10"]}]},"5","*","100","-"]},{"token":"P_1","st":22,"ed":24,"children":["1","1","+","2","*","5","+","2","/"]},{"token":"P_1","st":36,"ed":38,"children":["10"]}]},{"token":"count","st":44,"ed":48,"children":[{"token":"P_1","st":46,"ed":48,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C10","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":53,"ed":55,"children":["10","5","*","100","-"]}]},"+","5","*","100","-"]}`
+ );
+ });
+
+ it('normal', () => {
+ const node = lexer.treeBuilder(
+ `=(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10, lambda(x,y, x*y*x)(sum(1,(1+2)*3),2))+lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+count(B1:C10,10*5-100))*5-100`
+ ) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"sum","st":1,"ed":3,"children":[{"token":"P_1","st":1,"ed":3,"children":[{"token":"max","st":5,"ed":7,"children":[{"token":"P_1","st":5,"ed":7,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C10","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":12,"ed":14,"children":["10"]}]},"5","*","100","-"]},{"token":"P_1","st":22,"ed":24,"children":["1","1","+","2","*","5","+","2","/"]},{"token":"P_1","st":36,"ed":38,"children":["10"]},{"token":"P_1","st":39,"ed":41,"children":[{"token":" lambda","st":43,"ed":49,"children":[{"token":"L_1","st":58,"ed":60,"children":[{"token":"P_1","st":59,"ed":61,"children":[{"token":"sum","st":63,"ed":65,"children":[{"token":"P_1","st":63,"ed":65,"children":["1"]},{"token":"P_1","st":65,"ed":67,"children":["1","2","+","3","*"]}]}]},{"token":"P_1","st":74,"ed":76,"children":["2"]}]},{"token":"P_1","st":47,"ed":49,"children":["x"]},{"token":"P_1","st":49,"ed":51,"children":["y"]},{"token":"P_1","st":51,"ed":53,"children":[" x","y","x","*","*"]}]}]}]},{"token":"lambda","st":82,"ed":87,"children":[{"token":"L_1","st":96,"ed":98,"children":[{"token":"P_1","st":97,"ed":99,"children":[{"token":"sum","st":101,"ed":103,"children":[{"token":"P_1","st":101,"ed":103,"children":["1"]},{"token":"P_1","st":103,"ed":105,"children":["1","2","+","3","*"]}]}]},{"token":"P_1","st":112,"ed":114,"children":["2"]}]},{"token":"P_1","st":85,"ed":87,"children":["x"]},{"token":"P_1","st":87,"ed":89,"children":["y"]},{"token":"P_1","st":89,"ed":91,"children":[" x","y","x","*","*"]}]},{"token":"count","st":119,"ed":123,"children":[{"token":"P_1","st":121,"ed":123,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C10","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":128,"ed":130,"children":["10","5","*","100","-"]}]},"+","+","5","*","100","-"]}`
+ );
+ });
+
+ it('let', () => {
+ const node = lexer.treeBuilder(`=let(x,5,y,4,sum(x,y)+x)`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"let","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":["x"]},{"token":"P_1","st":2,"ed":4,"children":["5"]},{"token":"P_1","st":4,"ed":6,"children":["y"]},{"token":"P_1","st":6,"ed":8,"children":["4"]},{"token":"P_1","st":8,"ed":10,"children":[{"token":"sum","st":12,"ed":14,"children":[{"token":"P_1","st":12,"ed":14,"children":["x"]},{"token":"P_1","st":14,"ed":16,"children":["y"]}]},"x","+"]}]}]}`
+ );
+ });
+
+ it('REDUCE', () => {
+ const node = lexer.treeBuilder(`=REDUCE(1, A1:C2, LAMBDA(a,b,a+b^2))`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"REDUCE","st":0,"ed":5,"children":[{"token":"P_1","st":3,"ed":5,"children":["1"]},{"token":"P_1","st":5,"ed":7,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":" A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C2","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":12,"ed":14,"children":[{"token":" LAMBDA","st":16,"ed":22,"children":[{"token":"P_1","st":20,"ed":22,"children":["a"]},{"token":"P_1","st":22,"ed":24,"children":["b"]},{"token":"P_1","st":24,"ed":26,"children":["a","b","2","^","+"]}]}]}]}]}`
+ );
+ });
+
+ it('missing default arguments', () => {
+ const node = lexer.treeBuilder(`=SUM(, A1:B1)`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"SUM","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":[]},{"token":"P_1","st":1,"ed":3,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":" A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]}]}]}]}]}`
+ );
+ });
+
+ it('negative and percentage', () => {
+ const node = lexer.treeBuilder(`=0.1 -- 0.2%`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":["0.1 ",{"token":"%","st":-1,"ed":-1,"children":["- 0.2"]},"-"]}`
+ );
+ });
+
+ it('negative and percentage', () => {
+ const node = lexer.treeBuilder(`=1+(3*4=4)*5+1`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":["1","3","4","*","4","=","5","*","1","+","+"]}`
+ );
+ });
+
+ it('prefixToken', () => {
+ const node = lexer.treeBuilder(`= -@A4:B5`) as LexerNode;
+ expect(JSON.stringify(node.serialize())).toStrictEqual(
+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"-","st":-1,"ed":-1,"children":[{"token":"@","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"A4","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B5","st":-1,"ed":-1,"children":[]}]}]}]}]}]}`
+ );
+ });
+ });
+});
diff --git a/packages/engine-formula/src/analysis/lexer.ts b/packages/engine-formula/src/analysis/lexer.ts
index 1e2af17212..f9167a63ec 100644
--- a/packages/engine-formula/src/analysis/lexer.ts
+++ b/packages/engine-formula/src/analysis/lexer.ts
@@ -738,7 +738,8 @@ export class LexerTreeBuilder extends Disposable {
if (
OPERATOR_TOKEN_SET.has(prevString) ||
prevString === matchToken.OPEN_BRACKET ||
- prevString === matchToken.COMMA
+ prevString === matchToken.COMMA ||
+ prevString === ''
) {
return true;
}
@@ -965,13 +966,19 @@ export class LexerTreeBuilder extends Disposable {
let subLexerNode_minus: Nullable<LexerNode>;
let subLexerNode_at: Nullable<LexerNode>;
let sliceLength = 0;
- if (new RegExp(prefixToken.MINUS, 'g').test(this._segment)) {
+ const segmentTrim = this._segment.trim();
+ const lastString = segmentTrim[0];
+ const twoLastString = segmentTrim[1];
+
+ // new RegExp(prefixToken.MINUS, 'g').test(this._segment)
+ if (lastString === prefixToken.MINUS) {
subLexerNode_minus = new LexerNode();
subLexerNode_minus.setToken(prefixToken.MINUS);
sliceLength++;
}
- if (new RegExp(prefixToken.AT, 'g').test(this._segment)) {
+ // new RegExp(prefixToken.AT, 'g').test(this._segment)
+ if (lastString === prefixToken.AT || twoLastString === prefixToken.AT) {
subLexerNode_at = new LexerNode();
subLexerNode_at.setToken(prefixToken.AT);
@@ -984,7 +991,7 @@ export class LexerTreeBuilder extends Disposable {
}
if (sliceLength > 0) {
- this._segment = this._segment.slice(sliceLength);
+ this._segment = segmentTrim.slice(sliceLength);
}
upLevel = sliceLength;
diff --git a/packages/engine-formula/src/ast-node/reference-node.ts b/packages/engine-formula/src/ast-node/reference-node.ts
index 226740301f..f23f94cab3 100644
--- a/packages/engine-formula/src/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/ast-node/reference-node.ts
@@ -40,12 +40,16 @@ export class ReferenceNode extends BaseAstNode {
const currentConfigService = this._accessor.get(IFormulaCurrentConfigService);
const runtimeService = this._accessor.get(IFormulaRuntimeService);
- this._referenceObject.setUnitData(currentConfigService.getUnitData());
+ this._referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
+
+ this._referenceObject.setDefaultSheetId(runtimeService.currentSubComponentId);
+
this._referenceObject.setForcedSheetId(currentConfigService.getSheetNameMap());
+
+ this._referenceObject.setUnitData(currentConfigService.getUnitData());
+
this._referenceObject.setArrayFormulaCellData(currentConfigService.getArrayFormulaCellData());
- this._referenceObject.setDefaultSheetId(runtimeService.currentSubComponentId);
- this._referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
this._referenceObject.setRuntimeData(runtimeService.getUnitData());
this._referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
diff --git a/packages/engine-formula/src/basics/set-zero-time-out.ts b/packages/engine-formula/src/basics/set-zero-time-out.ts
deleted file mode 100644
index 4304dec957..0000000000
--- a/packages/engine-formula/src/basics/set-zero-time-out.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-const timeouts: any[] = [];
-const messageName = 'zero-timeout-message';
-
-const globalObject = typeof self !== 'undefined' ? self : window;
-
-/**
- * Maintain the form of setTimeout, only accept a single function parameter,
- * and the delay is always 0.
- * @param fn
- */
-export function setZeroTimeout(fn: any) {
- timeouts.push(fn);
- globalObject.postMessage(messageName);
-}
-
-function handleMessage(event: MessageEvent) {
- if (typeof self === 'undefined') {
- globalObject.postMessage(messageName);
- } else if (event.source === globalObject && event.data === messageName) {
- event.stopPropagation();
- if (timeouts.length > 0) {
- const fn = timeouts.shift()!;
- fn();
- }
- }
-}
-
-globalObject.addEventListener('message', handleMessage, true);
diff --git a/packages/engine-formula/src/dependency/formula-dependency.ts b/packages/engine-formula/src/dependency/formula-dependency.ts
index c1ec167dc6..d560ae7083 100644
--- a/packages/engine-formula/src/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/dependency/formula-dependency.ts
@@ -219,7 +219,7 @@ export class FormulaDependencyGenerator extends Disposable {
}
private _generateAstNode(formulaString: string, refOffsetX: number = 0, refOffsetY: number = 0) {
- let astNode: Nullable<AstRootNode> = FormulaASTCache.get(formulaString);
+ let astNode: Nullable<AstRootNode> = FormulaASTCache.get(`${formulaString}##${refOffsetX}${refOffsetY}`);
if (astNode) {
return astNode;
@@ -239,7 +239,7 @@ export class FormulaDependencyGenerator extends Disposable {
throw new Error('astNode is null');
}
- FormulaASTCache.set(formulaString, astNode);
+ FormulaASTCache.set(`${formulaString}##${refOffsetX}${refOffsetY}`, astNode);
return astNode;
}
diff --git a/packages/engine-formula/src/reference-object/base-reference-object.ts b/packages/engine-formula/src/reference-object/base-reference-object.ts
index 1cf28bb3d9..a0b16653f6 100644
--- a/packages/engine-formula/src/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/reference-object/base-reference-object.ts
@@ -135,14 +135,14 @@ export class BaseReferenceObject extends ObjectClassType {
}
getUnitId() {
- if (this._forcedUnitId) {
+ if (this._forcedUnitId && this._forcedUnitId.length > 0) {
return this._forcedUnitId;
}
return this._defaultUnitId;
}
getSheetId() {
- if (this._forcedSheetId) {
+ if (this._forcedSheetId && this._forcedSheetId.length > 0) {
return this._forcedSheetId;
}
return this._defaultSheetId;
@@ -188,8 +188,8 @@ export class BaseReferenceObject extends ObjectClassType {
return this._defaultSheetId;
}
- setDefaultUnitId(sheetId: string) {
- this._defaultUnitId = sheetId;
+ setDefaultUnitId(unitId: string) {
+ this._defaultUnitId = unitId;
}
getDefaultUnitId() {
diff --git a/packages/engine-formula/src/reference-object/cell-reference-object.ts b/packages/engine-formula/src/reference-object/cell-reference-object.ts
index 2b9ad4d843..345550e152 100644
--- a/packages/engine-formula/src/reference-object/cell-reference-object.ts
+++ b/packages/engine-formula/src/reference-object/cell-reference-object.ts
@@ -88,10 +88,12 @@ export class CellReferenceObject extends BaseReferenceObject {
rangeReferenceObject.setRefOffset(x, y);
- const forceId = this.getForcedUnitId();
+ const forceSheetId = this.getForcedSheetId();
- if (forceId != null) {
- rangeReferenceObject.setForcedSheetIdDirect(this.getForcedUnitId());
+ rangeReferenceObject.setForcedSheetName(this.getForcedSheetName());
+
+ if (forceSheetId != null) {
+ rangeReferenceObject.setForcedSheetIdDirect(forceSheetId);
}
// const forcedSheetID = this.getForcedSheetId();
@@ -99,10 +101,10 @@ export class CellReferenceObject extends BaseReferenceObject {
// rangeReferenceObject.setForcedSheetIdDirect(forcedSheetID);
// }
- // const forcedUnitId = this.getForcedUnitId();
- // if (forcedUnitId) {
- // rangeReferenceObject.setForcedUnitIdDirect(forcedUnitId);
- // }
+ const forcedUnitId = this.getForcedUnitId();
+ if (forcedUnitId) {
+ rangeReferenceObject.setForcedUnitIdDirect(forcedUnitId);
+ }
return rangeReferenceObject;
}
diff --git a/packages/engine-formula/src/services/formula-engine.service.ts b/packages/engine-formula/src/services/formula-engine.service.ts
index a40118b33a..1918c68db6 100644
--- a/packages/engine-formula/src/services/formula-engine.service.ts
+++ b/packages/engine-formula/src/services/formula-engine.service.ts
@@ -1,5 +1,12 @@
import type { IUnitRange } from '@univerjs/core';
-import { Disposable, IConfigService, LifecycleStages, ObjectMatrix, OnLifecycle } from '@univerjs/core';
+import {
+ Disposable,
+ IConfigService,
+ LifecycleStages,
+ ObjectMatrix,
+ OnLifecycle,
+ requestImmediateMacroTask,
+} from '@univerjs/core';
import type { Ctor, Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { Subject } from 'rxjs';
@@ -298,6 +305,20 @@ export class FormulaEngineService extends Disposable {
this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
for (let i = 0, len = treeList.length; i < len; i++) {
+ /**
+ * For every functions, execute a setTimeout to wait for external command input.
+ */
+ await new Promise((resolve) => {
+ requestImmediateMacroTask(resolve);
+ });
+
+ if (this.runtimeService.isStopExecution()) {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
+ this.runtimeService.markedAsStopFunctionsExecuted();
+ this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
+ return;
+ }
+
const tree = treeList[i];
const astNode = tree.node;
let value: FunctionVariantType;
@@ -314,21 +335,7 @@ export class FormulaEngineService extends Disposable {
value = interpreter.execute(astNode);
}
- /**
- * For every 100 functions, execute a setTimeout to wait for external command input.
- */
- if (i % EVERY_N_FUNCTION_EXECUTION_PAUSE === 0) {
- await new Promise((resolve) => {
- setTimeout(resolve, 0);
- });
- }
-
- if (this.runtimeService.isStopExecution()) {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
- this.runtimeService.markedAsStopFunctionsExecuted();
- this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
- return;
- }
+ // this.runtimeService.setCurrent(tree.row, tree.column, tree.subComponentId, tree.unitId);
if (tree.formulaId != null) {
this.runtimeService.setRuntimeOtherData(tree.formulaId, value);
@@ -368,7 +375,7 @@ export class FormulaEngineService extends Disposable {
}
// this.lexerTreeBuilder.suffixExpressionHandler(lexerNode); // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++
- // console.log('lexerNode', (lexerNode as LexerNode).serialize());
+ console.log('lexerNode', (lexerNode as LexerNode).serialize());
// console.log('sequence', this.lexerTreeBuilder.sequenceNodesBuilder(formulaString));
@@ -378,7 +385,7 @@ export class FormulaEngineService extends Disposable {
const astNode = this.astTreeBuilder.parse(lexerNode as LexerNode);
- // console.log('astNode', astNode?.serialize());
+ console.log('astNode', astNode?.serialize());
// const interpreter = Interpreter.create();
diff --git a/packages/engine-render/src/base-object.ts b/packages/engine-render/src/base-object.ts
index 549883c165..2675644b31 100644
--- a/packages/engine-render/src/base-object.ts
+++ b/packages/engine-render/src/base-object.ts
@@ -1,5 +1,5 @@
import type { EventState, IKeyValue, Nullable, Observer } from '@univerjs/core';
-import { Observable } from '@univerjs/core';
+import { Observable, requestImmediateMacroTask } from '@univerjs/core';
import type { EVENT_TYPE } from './basics/const';
import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
@@ -325,12 +325,19 @@ export abstract class BaseObject {
return;
}
- window.clearTimeout(scene.debounceParentTimeout);
+ // window.clearTimeout(scene.debounceParentTimeout);
+ // // To prevent multiple refreshes caused by setting values for multiple object instances at once.
+ // scene.debounceParentTimeout = window.setTimeout(() => {
+ // this._parent?.makeDirty(state);
+ // }, 0);
+
+ if (typeof scene.debounceParentTimeout === 'function') {
+ scene.debounceParentTimeout();
+ }
// To prevent multiple refreshes caused by setting values for multiple object instances at once.
- scene.debounceParentTimeout = window.setTimeout(() => {
+ scene.debounceParentTimeout = requestImmediateMacroTask(() => {
this._parent?.makeDirty(state);
- }, 0);
- // this.parent?.makeDirty(state);
+ });
}
return this;
diff --git a/packages/formula/src/controllers/update-formula.controller.ts b/packages/formula/src/controllers/update-formula.controller.ts
index 0f58954315..7430a2e83f 100644
--- a/packages/formula/src/controllers/update-formula.controller.ts
+++ b/packages/formula/src/controllers/update-formula.controller.ts
@@ -28,6 +28,7 @@ import type {
InsertRangeMoveRightCommandParams,
IRemoveRowColCommandParams,
ISetRangeValuesMutationParams,
+ ISetWorksheetNameCommandParams,
} from '@univerjs/sheets';
import {
DeleteRangeMoveLeftCommand,
@@ -55,6 +56,7 @@ import {
SelectionManagerService,
SetRangeValuesMutation,
SetRangeValuesUndoMutationFactory,
+ SetWorksheetNameCommand,
SheetInterceptorService,
} from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
@@ -80,6 +82,7 @@ enum FormulaReferenceMoveType {
DeleteMoveUp, // range
InsertMoveDown, // range
InsertMoveRight, // range
+ SetName,
}
interface IFormulaReferenceMoveParam {
@@ -89,6 +92,7 @@ interface IFormulaReferenceMoveParam {
ranges?: IRange[];
from?: IRange;
to?: IRange;
+ sheetName?: string;
}
enum OriginRangeEdgeType {
@@ -186,6 +190,9 @@ export class UpdateFormulaController extends Disposable {
case DeleteRangeMoveLeftCommand.id:
result = this._handleDeleteRangeMoveLeft(command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>);
break;
+ case SetWorksheetNameCommand.id:
+ result = this._handleSetWorksheetName(command as ICommandInfo<ISetWorksheetNameCommandParams>);
+ break;
}
if (result) {
@@ -437,6 +444,22 @@ export class UpdateFormulaController extends Disposable {
};
}
+ private _handleSetWorksheetName(command: ICommandInfo<ISetWorksheetNameCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { workbookId, worksheetId, name } = params;
+
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
+
+ return {
+ type: FormulaReferenceMoveType.SetName,
+ unitId: workbookId || unitId,
+ sheetId: worksheetId || sheetId,
+ sheetName: name,
+ };
+ }
+
private _getUpdateFormulaMutations(oldFormulaData: IFormulaData, formulaData: IFormulaData) {
const redos = [];
const undos = [];
@@ -545,7 +568,10 @@ export class UpdateFormulaController extends Disposable {
const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;
- const sequenceSheetId = unitSheetNameMap?.[sequenceUnitId]?.[sheetName];
+ const mapUnitId =
+ sequenceUnitId == null || sequenceUnitId.length === 0 ? unitId : sequenceUnitId;
+
+ const sequenceSheetId = unitSheetNameMap?.[mapUnitId]?.[sheetName];
const sequenceUnitRangeWidthOffset = {
range,
@@ -556,12 +582,39 @@ export class UpdateFormulaController extends Disposable {
refOffsetY: y || 0,
};
- const newRefString = this._getNewRangeByMoveParam(
- sequenceUnitRangeWidthOffset,
- formulaReferenceMoveParam,
- unitId,
- sheetId
- );
+ let newRefString: Nullable<string> = null;
+
+ if (formulaReferenceMoveParam.type === FormulaReferenceMoveType.SetName) {
+ const {
+ unitId: userUnitId,
+ sheetId: userSheetId,
+ sheetName: newSheetName,
+ } = formulaReferenceMoveParam;
+ if (newSheetName == null) {
+ continue;
+ }
+
+ if (sequenceSheetId == null || sequenceSheetId.length === 0) {
+ continue;
+ }
+
+ if (userSheetId !== sequenceSheetId) {
+ continue;
+ }
+
+ newRefString = serializeRangeToRefString({
+ range,
+ sheetName: newSheetName,
+ unitId: sequenceUnitId,
+ });
+ } else {
+ newRefString = this._getNewRangeByMoveParam(
+ sequenceUnitRangeWidthOffset,
+ formulaReferenceMoveParam,
+ unitId,
+ sheetId
+ );
+ }
if (newRefString != null) {
sequenceNodes[i] = {
diff --git a/packages/sheets-ui/src/controllers/editor/editing.controller.ts b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
index 0aba3fda71..912786cc7c 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
@@ -99,10 +99,7 @@ export class EditingController extends Disposable {
// console.log(res.sheetData, res.arrayFormulaRange);
// });
- // console.log(
- // 'calculate',
- // this._formulaEngineService.calculate(`=REDUCE(1, 'sheeASDF%#@ASDFt-1'!A:B1, LAMBDA(a,b,a+b^2))`, false)
- // );
+ console.log('calculate', this._formulaEngineService.calculate(`= -@A4:B5`, false));
}
private _commandExecutedListener() {}
diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
index 6f98a929ec..e73359e0f3 100644
--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
@@ -25,6 +25,7 @@ import {
SelectionManagerService,
SetRangeValuesCommand,
SetSelectionsOperation,
+ SetWorksheetActivateCommand,
SheetInterceptorService,
} from '@univerjs/sheets';
import { KeyCode } from '@univerjs/ui';
@@ -233,6 +234,16 @@ export class EndEditController extends Disposable {
},
value: cell,
});
+
+ /**
+ * When closing the editor, switch to the current tab of the editor.
+ */
+ if (workbookId === unitId && sheetId !== worksheetId) {
+ this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ worksheetId: sheetId,
+ workbookId: unitId,
+ });
+ }
});
}
diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.ts
index 0788d18c4d..b7d7778cf8 100644
--- a/packages/sheets-ui/src/sheets-ui-plugin.ts
+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts
@@ -89,7 +89,6 @@ export class SheetsUIPlugin extends Plugin {
// controllers
[AutoHeightController],
- [EditingController],
[EditorBridgeController],
[EndEditController],
[FormulaEditorController],
@@ -112,6 +111,7 @@ export class SheetsUIPlugin extends Plugin {
[ZoomController],
[AutoFillController],
[StatusBarController],
+ [EditingController],
] as Dependency[]
).forEach((d) => injector.add(d));
}
diff --git a/packages/sheets/src/commands/commands/set-worksheet-name.command.ts b/packages/sheets/src/commands/commands/set-worksheet-name.command.ts
index 574a0d8d5d..3cb3b3aa54 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-name.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-name.command.ts
@@ -1,11 +1,18 @@
import type { ICommand } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ sequenceExecute,
+} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type { ISetWorksheetNameMutationParams } from '../mutations/set-worksheet-name.mutation';
import { SetWorksheetNameMutation, SetWorksheetNameMutationFactory } from '../mutations/set-worksheet-name.mutation';
-export interface SetWorksheetNameCommandParams {
+export interface ISetWorksheetNameCommandParams {
name: string;
worksheetId?: string;
workbookId?: string;
@@ -18,10 +25,11 @@ export const SetWorksheetNameCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-name',
- handler: async (accessor: IAccessor, params: SetWorksheetNameCommandParams) => {
+ handler: async (accessor: IAccessor, params: ISetWorksheetNameCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const workbookId = params.workbookId || univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId =
@@ -36,18 +44,38 @@ export const SetWorksheetNameCommand: ICommand = {
accessor,
redoMutationParams
);
- const result = commandService.syncExecuteCommand(SetWorksheetNameMutation.id, redoMutationParams);
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({
+ id: SetWorksheetNameCommand.id,
+ params,
+ });
+
+ const redos = [{ id: SetWorksheetNameMutation.id, params: redoMutationParams }, ...interceptorCommands.redos];
+ const undos = [...interceptorCommands.undos, { id: SetWorksheetNameMutation.id, params: undoMutationParams }];
+
+ const result = await sequenceExecute(redos, commandService).result;
if (result) {
undoRedoService.pushUndoRedo({
unitID: workbookId,
- undoMutations: [{ id: SetWorksheetNameMutation.id, params: undoMutationParams }],
- redoMutations: [{ id: SetWorksheetNameMutation.id, params: redoMutationParams }],
+ undoMutations: undos,
+ redoMutations: redos,
});
-
return true;
}
-
return false;
+
+ // const result = commandService.syncExecuteCommand(SetWorksheetNameMutation.id, redoMutationParams);
+
+ // if (result) {
+ // undoRedoService.pushUndoRedo({
+ // unitID: workbookId,
+ // undoMutations: [{ id: SetWorksheetNameMutation.id, params: undoMutationParams }],
+ // redoMutations: [{ id: SetWorksheetNameMutation.id, params: redoMutationParams }],
+ // });
+
+ // return true;
+ // }
+
+ // return false;
},
};
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index 54d07a34ca..f1cb11e2d2 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -135,7 +135,10 @@ export {
SetColWidthCommand,
} from './commands/commands/set-worksheet-col-width.command';
export { SetWorksheetHideCommand } from './commands/commands/set-worksheet-hide.command';
-export { SetWorksheetNameCommand } from './commands/commands/set-worksheet-name.command';
+export {
+ type ISetWorksheetNameCommandParams,
+ SetWorksheetNameCommand,
+} from './commands/commands/set-worksheet-name.command';
export { SetWorksheetOrderCommand } from './commands/commands/set-worksheet-order.command';
export {
DeltaRowHeightCommand,