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.

feat(formula): table formula (#6113)

Univera5e51e4e1a8c
diff --git a/packages/engine-formula/src/basics/__tests__/regex.spec.ts b/packages/engine-formula/src/basics/__tests__/regex.spec.ts
index 23c06d1b5a..4fd7c03c42 100644
--- a/packages/engine-formula/src/basics/__tests__/regex.spec.ts
+++ b/packages/engine-formula/src/basics/__tests__/regex.spec.ts
@@ -15,7 +15,7 @@
*/
import { describe, expect, it } from 'vitest';
-import { isReferenceString, REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX, REFERENCE_TABLE_SINGLE_COLUMN_REGEX, regexTestColumn, regexTestMultipleRange, regexTestRow, regexTestSingeRange } from '../regex';
+import { isReferenceString, REFERENCE_TABLE_ALL_COLUMN_REGEX, REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX, REFERENCE_TABLE_SINGLE_COLUMN_REGEX, REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX, regexTestColumn, regexTestMultipleRange, regexTestRow, regexTestSingeRange } from '../regex';
describe('Test ref regex', () => {
it('Single range', () => {
@@ -83,4 +83,365 @@ describe('Test ref regex', () => {
expect(isReferenceString('[workbook]\'Sheet-1\'!A:B')).toBeTruthy();
expect(isReferenceString('\'[workbook]Sheet1\'!A:B')).toBeTruthy();
});
+
+ // Structured Reference extra tests (comments in English)
+ // Assumes REFERENCE_TABLE_SINGLE_COLUMN_REGEX / REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX are already imported.
+ describe('Structured Reference – Single Column (positive)', () => {
+ const RE_SINGLE = new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX);
+
+ it('matches basic single column', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[Column1]')).toBe(true);
+ });
+
+ it('matches double-bracket single column', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[Column1]]')).toBe(true);
+ });
+
+ it('matches with #Headers tag', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Headers],[Column1]]')).toBe(true);
+ });
+
+ it('matches with #Data tag', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Data],[Column1]]')).toBe(true);
+ });
+
+ it('matches with #All tag', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#All],[Column1]]')).toBe(true);
+ });
+
+ it('matches with #Totals tag', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Totals],[Column1]]')).toBe(true);
+ });
+
+ it('matches with #This Row tag', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#This Row],[Column1]]')).toBe(true);
+ });
+
+ it('matches with #Title tag (allowed in your grammar)', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Title],[Column1]]')).toBe(true);
+ });
+
+ it('matches tag order swapped (column before tag)', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[Column1],[#Data]]')).toBe(false);
+ });
+
+ it('matches spaces around tokens', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[ Column1 ]]')).toBe(true);
+ });
+
+ it('matches spaces and comma spacing', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Data] , [Column1]]')).toBe(true);
+ });
+
+ it('matches mixed spacing inside brackets', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[ #All ],[ Column1 ]]')).toBe(false);
+ });
+
+ it('matches unicode/space column name', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[客户 名称]]')).toBe(true);
+ });
+
+ it('matches special char column name', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[Order-ID]]')).toBe(true);
+ });
+
+ it('matches pure unicode column name', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[中文列名]]')).toBe(true);
+ });
+
+ it('matches empty bracket', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[]')).toBe(true);
+ });
+ });
+
+ describe('Structured Reference – Single Column (negative)', () => {
+ const RE_SINGLE = new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX);
+
+ it('does not match #All only', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[#All]')).toBe(false);
+ });
+
+ it('does not match #Headers only', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[#Headers]')).toBe(false);
+ });
+
+ it('does not match #Data only', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[#Data]')).toBe(false);
+ });
+
+ it('does not match #Totals only', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[#Totals]')).toBe(false);
+ });
+
+ it('does not match table name only', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1')).toBe(false);
+ });
+ });
+
+ describe('Structured Reference – Multi Column (positive)', () => {
+ const RE_MULTI = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
+
+ it('matches basic column range', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #Headers', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Headers],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #Data', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Data],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #All', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#All],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #Totals', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Totals],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #This Row', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#This Row],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with #Title', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Title],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with multi tags', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Headers],[#Data],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('matches column range with spaces around tokens', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[ Column1 ]:[ Column10 ]]')).toBe(true);
+ });
+
+ it('matches column range with spaced colon and tag', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Data], [ Column1 ] : [ Column10 ]]')).toBe(true);
+ });
+
+ it('matches unicode/special char names in range', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[客户 名称]:[订单-ID]]')).toBe(true);
+ });
+ });
+
+ describe('Structured Reference – Multi Column (negative)', () => {
+ const RE_MULTI = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
+
+ it('does not match single column simple', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[Column1]')).toBe(false);
+ });
+
+ it('does not match single column with tag', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Data],[Column1]]')).toBe(false);
+ });
+
+ it('does not match comma-separated multiple columns (list, not range)', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[Column1],[Column2]]')).toBe(false);
+ });
+
+ it('does not match comma-separated with tag', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Data],[Column1],[Column3]]')).toBe(false);
+ });
+
+ it('does not match #All only', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[#All]')).toBe(false);
+ });
+
+ it('does not match #Headers only', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[#Headers]')).toBe(false);
+ });
+
+ it('does not match A1-style range', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[A1:B10]')).toBe(false);
+ });
+
+ it('does not match empty bracket', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[]')).toBe(false);
+ });
+ });
+
+ describe('Structured Reference – Cross guard', () => {
+ const RE_MULTI = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
+
+ it('multi-regex should not match single-column (double bracket)', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[Column1]]')).toBe(false);
+ });
+
+ it('multi-regex should not match single-column (simple)', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[Column1]')).toBe(false);
+ });
+ });
+
+ describe('Structured Reference – Order & spacing edge cases', () => {
+ const RE_SINGLE = new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX);
+ const RE_MULTI = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
+
+ // Single
+ it('single: tag order after column (Totals)', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[Column1],[#Totals]]')).toBe(false);
+ });
+
+ it('single: multiple tags after column', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[Column1],[#Headers],[#Data]]')).toBe(false);
+ });
+
+ it('single: excessive spaces around comma', () => {
+ RE_SINGLE.lastIndex = 0;
+ expect(RE_SINGLE.test('Table1[[#Data] , [Column1]]')).toBe(true);
+ });
+
+ // Multi
+ it('multi: tag after range', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[Column1]:[Column10],[#All]]')).toBe(false);
+ });
+
+ it('multi: multiple tags before range', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#Data],[#Totals],[Column1]:[Column10]]')).toBe(true);
+ });
+
+ it('multi: excessive spaces around colon and tags', () => {
+ RE_MULTI.lastIndex = 0;
+ expect(RE_MULTI.test('Table1[[#All] , [Column1] : [Column10]]')).toBe(true);
+ });
+ });
+
+ describe('Single all column test', () => {
+ const FULL_SINGLE = new RegExp(REFERENCE_TABLE_ALL_COLUMN_REGEX);
+
+ // Should match a plain table name (shorthand for #All)
+ it('matches plain table name', () => {
+ FULL_SINGLE.lastIndex = 0;
+ expect(FULL_SINGLE.test('Table1')).toBe(true);
+ });
+
+ // Should not match an empty bracket (invalid structured reference)
+ it('rejects empty brackets', () => {
+ FULL_SINGLE.lastIndex = 0;
+ expect(FULL_SINGLE.test('Table1[]')).toBe(false);
+ });
+
+ // Should not match strings with non-table prefix
+ it('rejects prefixed string', () => {
+ FULL_SINGLE.lastIndex = 0;
+ expect(FULL_SINGLE.test('122Table1')).toBe(true);
+ });
+
+ // Should not match column-qualified reference (not a pure whole-table reference)
+ it('rejects table with column reference', () => {
+ FULL_SINGLE.lastIndex = 0;
+ expect(FULL_SINGLE.test('Table1[Column1]')).toBe(false);
+ });
+ });
+
+ describe('Title-only hash test', () => {
+ const TITLE_ONLY = new RegExp(REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX);
+
+ // Should match a basic title-only structured reference, e.g. Table1[#Headers]
+ it('matches simple hash title', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#Headers]')).toBe(true);
+ });
+
+ // Should match arbitrary hash names, not only Excel built-ins
+ it('matches any #title content', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#FooBar]')).toBe(true);
+ });
+
+ // Should allow spaces inside the bracket
+ it('matches hash title with spaces', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#This Row]')).toBe(true);
+ });
+
+ // Should allow sheet/unit prefix if UNIT_NAME_REGEX supports it
+ it('rejects unit prefix', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Sheet1!TableA[#Data]')).toBe(false);
+ });
+
+ // Should reject non-hash titles
+ it('rejects normal column name', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[Column1]')).toBe(false);
+ });
+
+ // Should reject missing content after #
+ it('rejects # with no content', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#]')).toBe(false);
+ });
+
+ // Should reject nested blocks (multiple bracket groups)
+ it('rejects multiple bracket segments', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#Headers][#Data]')).toBe(false);
+ });
+
+ // Should reject empty bracket
+ it('rejects empty bracket', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[]')).toBe(false);
+ });
+
+ // Should reject malformed formats
+ it('rejects malformed hash block', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#Headers')).toBe(false); // missing ]
+ });
+
+ // Should reject trailing characters after the bracket
+ it('rejects trailing characters', () => {
+ TITLE_ONLY.lastIndex = 0;
+ expect(TITLE_ONLY.test('Table1[#Headers]Extra')).toBe(false);
+ });
+ });
});
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index a13ad9e0c3..a11c8276ee 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -15,7 +15,6 @@
*/
import type {
- BooleanNumber,
ICellData,
IColumnData,
IObjectArrayPrimitiveType,
@@ -163,7 +162,6 @@ export interface IOtherFormulaDataItem {
export interface ISuperTable {
sheetId: string;
- hasCustomTitle: BooleanNumber;
titleMap: Map<string, number>;
range: IRange;
}
@@ -173,6 +171,7 @@ export enum TableOptionType {
DATA = '#Data',
HEADERS = '#Headers',
TOTALS = '#Totals',
+ THIS_ROW = '#This Row',
}
export interface IUnitExcludedCell {
diff --git a/packages/engine-formula/src/basics/function.ts b/packages/engine-formula/src/basics/function.ts
index fa788c12dd..73dba744f2 100644
--- a/packages/engine-formula/src/basics/function.ts
+++ b/packages/engine-formula/src/basics/function.ts
@@ -121,6 +121,11 @@ export enum FunctionType {
* Defined name
*/
DefinedName,
+
+ /**
+ * Super Table name
+ */
+ Table,
}
export interface IFunctionParam {
diff --git a/packages/engine-formula/src/basics/regex.ts b/packages/engine-formula/src/basics/regex.ts
index 7642205151..c4ee86f8ea 100644
--- a/packages/engine-formula/src/basics/regex.ts
+++ b/packages/engine-formula/src/basics/regex.ts
@@ -76,7 +76,17 @@ export const REFERENCE_TABLE_SINGLE_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TABL
export const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}(\\[${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$|^${TABLE_NAME_REGEX}(\\[${TABLE_TITLE_REGEX}${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$`; // =Table1[[#Title],[Column1]:[Column2]] | =Table1[[Column1]:[Column2]]
-export const SUPER_TABLE_COLUMN_REGEX = '[.*?]';
+export const REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}\\[\\s*#([^\\]]+)\\s*\\]$`; // =Table1[#All] | =Table1[#Data] | =Table1[#Headers] | =Table1[#Totals] | =Table1[#This Row]
+
+export const REFERENCE_TABLE_ALL_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_ALL_COLUMN_REGEX);
+
+export const REFERENCE_TABLE_SINGLE_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX);
+
+export const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
+
+export const REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX);
+
+export const SUPER_TABLE_COLUMN_REGEX = '\\[[^\\]]*?]';
export const SUPER_TABLE_COLUMN_REGEX_PRECOMPILING = new RegExp(SUPER_TABLE_COLUMN_REGEX, 'g');
@@ -119,6 +129,26 @@ export function regexTestSuperTableColumn(token: string): boolean {
return SUPER_TABLE_COLUMN_REGEX_PRECOMPILING.test(token);
}
+export function regexTestReferenceTableAllColumn(token: string): boolean {
+ REFERENCE_TABLE_ALL_COLUMN_REGEX_PRECOMPILING.lastIndex = 0;
+ return REFERENCE_TABLE_ALL_COLUMN_REGEX_PRECOMPILING.test(token);
+}
+
+export function regexTestReferenceTableSingleColumn(token: string): boolean {
+ REFERENCE_TABLE_SINGLE_COLUMN_REGEX_PRECOMPILING.lastIndex = 0;
+ return REFERENCE_TABLE_SINGLE_COLUMN_REGEX_PRECOMPILING.test(token);
+}
+
+export function regexTestReferenceTableMultipleColumn(token: string): boolean {
+ REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX_PRECOMPILING.lastIndex = 0;
+ return REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX_PRECOMPILING.test(token);
+}
+
+export function regexTestReferenceTableTitleOnlyAnyHash(token: string): boolean {
+ REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX_PRECOMPILING.lastIndex = 0;
+ return REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX_PRECOMPILING.test(token);
+}
+
export function regexTestArrayValue(token: string): boolean {
ARRAY_VALUE_REGEX_PRECOMPILING.lastIndex = 0;
return ARRAY_VALUE_REGEX_PRECOMPILING.test(token);
diff --git a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
index 28aaf4b69e..6f6b288cee 100644
--- a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
@@ -15,10 +15,11 @@
*/
import type { IMutation } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
-
import type { ISuperTable } from '../../basics/common';
+
import type { ISuperTableOptionParam } from '../../services/super-table.service';
+import { CommandType } from '@univerjs/core';
+import { ISuperTableService } from '../../services/super-table.service';
export interface ISetSuperTableMutationSearchParam {
unitId: string;
@@ -35,17 +36,32 @@ export interface ISetSuperTableMutationParam extends ISetSuperTableMutationSearc
export const SetSuperTableMutation: IMutation<ISetSuperTableMutationParam> = {
id: 'formula.mutation.set-super-table',
type: CommandType.MUTATION,
- handler: () => true,
+ handler: (accessor, params) => {
+ const { unitId, tableName, reference } = params;
+ const superTableService = accessor.get(ISuperTableService);
+ superTableService.registerTable(unitId, tableName, reference);
+ return true;
+ },
};
export const RemoveSuperTableMutation: IMutation<ISetSuperTableMutationSearchParam> = {
id: 'formula.mutation.remove-super-table',
type: CommandType.MUTATION,
- handler: () => true,
+ handler: (accessor, params) => {
+ const { unitId, tableName } = params;
+ const superTableService = accessor.get(ISuperTableService);
+ superTableService.remove(unitId, tableName);
+ return true;
+ },
};
export const SetSuperTableOptionMutation: IMutation<ISuperTableOptionParam> = {
id: 'formula.mutation.set-super-table-option',
type: CommandType.MUTATION,
- handler: () => true,
+ handler: (accessor, params) => {
+ const { tableOption, tableOptionType } = params;
+ const superTableService = accessor.get(ISuperTableService);
+ superTableService.registerTableOptionMap(tableOption, tableOptionType);
+ return true;
+ },
};
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
index 30987a6333..43b44718ad 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
@@ -29,9 +29,12 @@ import { Divided } from '../../../functions/meta/divided';
import { FUNCTION_NAMES_META } from '../../../functions/meta/function-names';
import { Minus } from '../../../functions/meta/minus';
import { Plus } from '../../../functions/meta/plus';
+import { Countif } from '../../../functions/statistical/countif';
+import { FUNCTION_NAMES_STATISTICAL } from '../../../functions/statistical/function-names';
import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
import { IFunctionService } from '../../../services/function.service';
import { IFormulaRuntimeService } from '../../../services/runtime.service';
+import { ISuperTableService } from '../../../services/super-table.service';
import { Interpreter } from '../../interpreter/interpreter';
import { generateExecuteAstNodeData } from '../../utils/ast-node-tool';
import { Lexer } from '../lexer';
@@ -59,6 +62,8 @@ describe('Test indirect', () => {
const formulaRuntimeService = get(IFormulaRuntimeService);
+ const superTableService = get(ISuperTableService);
+
formulaCurrentConfigService.load({
formulaData: {},
arrayFormulaCellData: {},
@@ -90,8 +95,25 @@ describe('Test indirect', () => {
new Plus(FUNCTION_NAMES_META.PLUS),
new Minus(FUNCTION_NAMES_META.MINUS),
new Divided(FUNCTION_NAMES_META.DIVIDED),
- new Pi(FUNCTION_NAMES_MATH.PI)
+ new Pi(FUNCTION_NAMES_MATH.PI),
+ new Countif(FUNCTION_NAMES_STATISTICAL.COUNTIF)
);
+
+ superTableService.registerTable(testBed.unitId, 'Table1', {
+ sheetId: testBed.sheetId,
+ titleMap: new Map([
+ ['col1', 0],
+ ['col2', 1],
+ ['col3', 2],
+ ['col4', 3],
+ ]),
+ range: {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 4,
+ },
+ });
});
describe('normal', () => {
@@ -321,4 +343,107 @@ describe('Test indirect', () => {
expect((result as ArrayValueObject).getFirstCell().getValue()).toStrictEqual(10);
});
});
+
+ describe('Structured references — Table1 (Main)', () => {
+ it('test super formula correctly', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[col1]:[col4]])');
+
+ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode as BaseAstNode));
+
+ expect((result as BaseValueObject).getValue()).toStrictEqual(9.23);
+ });
+
+ it('sums a single column: Table1[col1] => 3 + 1 + 0 = 4', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[col1])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(4);
+ });
+
+ it('sums a 2-column data range: Table1[[#Data],[col1]:[col2]] => (3+1+0) + (4) = 8', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#Data],[col1]:[col2]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(8);
+ });
+
+ it('sums headers only: Table1[[#Headers],[col1]:[col4]] => 1 + 2 = 3 (text ignored)', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#Headers],[col1]:[col4]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(3);
+ });
+
+ it('sums a single column across #All: Table1[[#All],[col3]] => 1.23', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#All],[col3]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(1.23);
+ });
+
+ it('counts numbers in data column: SUM(Table1[[#Data],[col2]]) => 1', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#Data],[col2]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(4);
+ });
+
+ it('sums a multi-column range: Table1[[col1]:[col4]] => 9.23 (baseline)', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[col1]:[col4]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(9.23);
+ });
+
+ it('sums all data across the table: SUM(Table1[#Data]) => 9.23', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[#Data])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(6.23);
+ });
+
+ it('totals row behavior: SUM(Table1[[#Totals],[col1]]) => 0 when no totals row is configured', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#Totals],[col1]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(0);
+ });
+
+ it('unions two columns: SUM(Table1[col1], Table1[col3]) => (3+1+0) + (1.23) = 5.23', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[col1], Table1[col3])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(5.23);
+ });
+
+ it('mixed qualifier order is supported: Table1[[col1]:[col2],[#Data]] => 8', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[col1]:[col2],[#Data]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual('#NAME?');
+ });
+
+ it('single-column double-bracket form: Table1[[#Data],[col1]] => 3+1+0 = 4', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[[#Data],[col1]])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(4);
+ });
+
+ it('ignores text in numeric aggregations: SUM(Table1[col2]) => 4', async () => {
+ const lexerNode = lexer.treeBuilder('=SUM(Table1[col2])') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(4);
+ });
+
+ it('COUNTIF on a column with mixed types: COUNTIF(Table1[col2], ">0") => 1', async () => {
+ const lexerNode = lexer.treeBuilder('=COUNTIF(Table1[col2], ">0")') as LexerNode;
+ const astNode = astTreeBuilder.parse(lexerNode) as BaseAstNode;
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode));
+ expect((result as BaseValueObject).getValue()).toStrictEqual(1);
+ });
+ });
});
diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.ts
index e2c84075c2..1c2a3ba0a8 100644
--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts
@@ -18,6 +18,10 @@ import type { Nullable } from '@univerjs/core';
import { ErrorType } from '../../basics/error-type';
import {
+ regexTestReferenceTableAllColumn,
+ regexTestReferenceTableMultipleColumn,
+ regexTestReferenceTableSingleColumn,
+ regexTestReferenceTableTitleOnlyAnyHash,
regexTestSingeRange,
regexTestSingleColumn,
regexTestSingleRow,
@@ -26,7 +30,9 @@ import { matchToken } from '../../basics/token';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IFunctionService } from '../../services/function.service';
import { IFormulaRuntimeService } from '../../services/runtime.service';
+import { ISuperTableService } from '../../services/super-table.service';
import { LexerNode } from '../analysis/lexer-node';
+import { TableReferenceObject } from '../reference-object/table-reference-object';
import { prefixHandler } from '../utils/prefix-handler';
import { getReferenceObjectFromCache, ReferenceObjectType } from '../utils/value-object';
import { ErrorValueObject } from '../value-object/base-value-object';
@@ -43,7 +49,8 @@ export class ReferenceNode extends BaseAstNode {
private _runtimeService: IFormulaRuntimeService,
operatorString: string,
private _referenceObjectType: ReferenceObjectType,
- private _isPrepareMerge: boolean = false
+ private _isPrepareMerge: boolean = false,
+ private _tableReferenceObject?: TableReferenceObject
) {
super(operatorString);
}
@@ -56,7 +63,7 @@ export class ReferenceNode extends BaseAstNode {
const currentConfigService = this._currentConfigService;
const runtimeService = this._runtimeService;
- const referenceObject = getReferenceObjectFromCache(this.getToken(), this._referenceObjectType);
+ const referenceObject = this._tableReferenceObject || getReferenceObjectFromCache(this.getToken(), this._referenceObjectType);
referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
@@ -76,6 +83,10 @@ export class ReferenceNode extends BaseAstNode {
referenceObject.setRuntimeFeatureCellData(runtimeService.getRuntimeFeatureCellData());
+ const currentRow = runtimeService.currentRow;
+ const currentCol = runtimeService.currentColumn;
+ referenceObject.setCurrentRowAndColumn(currentRow, currentCol);
+
const { x, y } = this.getRefOffset();
referenceObject.setRefOffset(x, y);
@@ -104,7 +115,8 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
constructor(
@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,
@IFormulaRuntimeService private readonly _formulaRuntimeService: IFormulaRuntimeService,
- @IFunctionService private readonly _functionService: IFunctionService
+ @IFunctionService private readonly _functionService: IFunctionService,
+ @ISuperTableService private readonly _superTableService: ISuperTableService
) {
super();
}
@@ -137,47 +149,13 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
// return true;
// }
- const currentConfigService = this._currentConfigService;
- const runtimeService = this._formulaRuntimeService;
-
- const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(tokenTrimPre, this._functionService, runtimeService);
+ const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(tokenTrimPre, this._functionService, this._formulaRuntimeService);
if (!isLexerNode && tokenTrim.charAt(0) === '"' && tokenTrim.charAt(tokenTrim.length - 1) === '"') {
return;
}
- let node: Nullable<ReferenceNode>;
- if (regexTestSingeRange(tokenTrim)) {
- node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.CELL, isPrepareMerge);
- } else if (isLexerNode && this._checkParentIsUnionOperator(param as LexerNode)) {
- if (regexTestSingleRow(tokenTrim)) {
- node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.ROW, isPrepareMerge);
- } else if (regexTestSingleColumn(tokenTrim)) {
- node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.COLUMN, isPrepareMerge);
- }
- }
- // else {
- // const unitId = this._formulaRuntimeService.currentUnitId;
- // // parserDataLoader.get
-
- // const tableMap = this._superTableService.getTableMap(unitId);
- // const $regex = $SUPER_TABLE_COLUMN_REGEX_PRECOMPILING;
- // const tableName = tokenTrim.replace($regex, '');
- // if (!isLexerNode && tableMap?.has(tableName)) {
- // const columnResult = $regex.exec(tokenTrim);
- // let columnDataString = '';
- // if (columnResult) {
- // columnDataString = columnResult[0];
- // }
- // const tableData = tableMap.get(tableName)!;
- // const tableOption = this._superTableService.getTableOptionMap();
- // node = new ReferenceNode(
- // this._injector,
- // tokenTrim,
- // new TableReferenceObject(tokenTrim, tableData, columnDataString, tableOption)
- // );
- // }
- // }
+ const node: Nullable<ReferenceNode> = this._getNode(tokenTrim, isLexerNode, isPrepareMerge, param);
if (node) {
if (atPrefixNode) {
@@ -189,6 +167,89 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
}
}
+ private _getTableMap() {
+ const unitId = this._currentConfigService.getExecuteUnitId();
+ if (!unitId) {
+ return;
+ }
+ return this._superTableService.getTableMap(unitId);
+ }
+
+ private _getNode(
+ tokenTrim: string,
+ isLexerNode: boolean,
+ isPrepareMerge: boolean,
+ param: LexerNode | string
+ ) {
+ const currentConfigService = this._currentConfigService;
+ const runtimeService = this._formulaRuntimeService;
+
+ const tableMap = this._getTableMap();
+ const isSuperTableDirect = tableMap?.has(tokenTrim) ?? false;
+
+ const isCellRange = regexTestSingeRange(tokenTrim);
+ const parentIsUnion = isLexerNode && this._checkParentIsUnionOperator(param as LexerNode);
+ const isRowRef = parentIsUnion && regexTestSingleRow(tokenTrim);
+ const isColRef = parentIsUnion && regexTestSingleColumn(tokenTrim);
+
+ const makeRef = (type: ReferenceObjectType) =>
+ new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, isPrepareMerge);
+
+ if (isSuperTableDirect) {
+ return this._getTableReferenceNode(tokenTrim, isLexerNode, isPrepareMerge, true);
+ }
+
+ if (isCellRange) {
+ return makeRef(ReferenceObjectType.CELL);
+ }
+
+ if (isRowRef) {
+ return makeRef(ReferenceObjectType.ROW);
+ }
+
+ if (isColRef) {
+ return makeRef(ReferenceObjectType.COLUMN);
+ }
+
+ return this._getTableReferenceNode(tokenTrim, isLexerNode, isPrepareMerge, false);
+ }
+
+ private _getTableReferenceNode(tokenTrim: string, isLexerNode: boolean, isPrepareMerge: boolean, isSuperTableDirectly: boolean = false) {
+ if (!this._checkTokenIsTableReference(tokenTrim) && !isSuperTableDirectly) {
+ return;
+ }
+ const { tableName, columnStruct } = this._splitTableStructuredRef(tokenTrim);
+ const tableMap = this._getTableMap();
+ if (!isLexerNode && tableMap?.has(tableName)) {
+ const columnDataString = columnStruct;
+ const tableData = tableMap.get(tableName)!;
+ const tableOption = this._superTableService.getTableOptionMap();
+ return new ReferenceNode(
+ this._currentConfigService,
+ this._formulaRuntimeService,
+ tokenTrim,
+ ReferenceObjectType.COLUMN,
+ isPrepareMerge,
+ new TableReferenceObject(tokenTrim, tableData, columnDataString, tableOption)
+ );
+ }
+ }
+
+ private _splitTableStructuredRef(ref: string) {
+ const idx = ref.indexOf('[');
+ if (idx === -1) {
+ return { tableName: ref, struct: '' };
+ }
+ return {
+ tableName: ref.slice(0, idx),
+ columnStruct: ref.slice(idx), // 包含外层 [[...]]
+ };
+ }
+
+ private _checkTokenIsTableReference(token: string): boolean {
+ return regexTestReferenceTableAllColumn(token) || regexTestReferenceTableSingleColumn(token) || regexTestReferenceTableMultipleColumn(token) || regexTestReferenceTableTitleOnlyAnyHash(token);
+ }
+
private _checkParentIsUnionOperator(param: LexerNode) {
return param.getParent()?.getParent()?.getToken().trim() === matchToken.COLON;
}
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
index 98134f3656..0cbffafa41 100644
--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
@@ -77,6 +77,10 @@ export class BaseReferenceObject extends ObjectClassType {
private _refOffsetY = 0;
+ private _currentRow?: number;
+
+ private _currentColumn?: number;
+
constructor(private _token: string) {
super();
}
@@ -119,7 +123,8 @@ export class BaseReferenceObject extends ObjectClassType {
}
getRangePosition() {
- let { startRow, startColumn, endRow, endColumn } = moveRangeByOffset(this._rangeData, this._refOffsetX, this._refOffsetY);
+ const { x, y } = this.getRefOffset();
+ let { startRow, startColumn, endRow, endColumn } = moveRangeByOffset(this.getRangeData(), x, y);
if (Number.isNaN(startRow)) {
startRow = 0;
@@ -138,7 +143,7 @@ export class BaseReferenceObject extends ObjectClassType {
}
return {
- ...this._rangeData,
+ ...this.getRangeData(),
startRow,
endRow,
startColumn,
@@ -358,11 +363,13 @@ export class BaseReferenceObject extends ObjectClassType {
}
getRowCount() {
- return this._rangeData.endRow - this._rangeData.startRow + 1;
+ const rangeData = this.getRangeData();
+ return rangeData.endRow - rangeData.startRow + 1;
}
getColumnCount() {
- return this._rangeData.endColumn - this._rangeData.startColumn + 1;
+ const rangeData = this.getRangeData();
+ return rangeData.endColumn - rangeData.startColumn + 1;
}
getRowData() {
@@ -393,6 +400,14 @@ export class BaseReferenceObject extends ObjectClassType {
return false;
}
+ isCurrentRowForRange(): boolean {
+ return false;
+ }
+
+ isCurrentColumnForRange(): boolean {
+ return false;
+ }
+
unionBy(referenceObject: BaseReferenceObject): NodeValueType {
/** abstract */
return ErrorValueObject.create(ErrorType.REF);
@@ -496,12 +511,13 @@ export class BaseReferenceObject extends ObjectClassType {
getCellByPosition(rowRaw?: number, columnRaw?: number) {
let row = rowRaw;
let column = columnRaw;
+ const rangeData = this.getRangeData();
if (!row) {
- row = this._rangeData.startRow;
+ row = rangeData.startRow;
}
if (!column) {
- column = this._rangeData.startColumn;
+ column = rangeData.startColumn;
}
const cell = this.getCellData(row, column);
@@ -513,6 +529,19 @@ export class BaseReferenceObject extends ObjectClassType {
return this.getCellValueObject(cell);
}
+ setCurrentRowAndColumn(row: number, column: number) {
+ this._currentRow = row;
+ this._currentColumn = column;
+ }
+
+ getCurrentRow() {
+ return this._currentRow;
+ }
+
+ getCurrentColumn() {
+ return this._currentColumn;
+ }
+
/**
* Get the pattern of the cell
* @param unitId
diff --git a/packages/engine-formula/src/engine/reference-object/table-reference-object.ts b/packages/engine-formula/src/engine/reference-object/table-reference-object.ts
index b63fa87f74..0401ca45f9 100644
--- a/packages/engine-formula/src/engine/reference-object/table-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/table-reference-object.ts
@@ -14,54 +14,85 @@
* limitations under the License.
*/
-import type { ISuperTable } from '../../basics/common';
+import type { ISuperTable, IUnitSheetNameMap } from '../../basics/common';
import { TableOptionType } from '../../basics/common';
-import { regexTestSuperTableColumn } from '../../basics/regex';
-
import { matchToken } from '../../basics/token';
import { BaseReferenceObject } from './base-reference-object';
-// =Table2[[#Headers],[11111]:[Column3]]
-// =Table2[[11111]:[222]]
-// =Table2[222]
-// =Table2[[#All],[222]:[Column4]]
+/**
+ * Table reference object compatible with Excel Structured References
+ *
+ * Supported (examples):
+ * - =Table[Column] // Single column (default DATA)
+ * - =Table[[ColumnA]:[ColumnB]] // Column range (default DATA)
+ * - =Table[#All] / [#Data] / [#Headers] / [#Totals] / [#This Row]
+ * - =Table[[#All],[Column]] // Section + column/column range
+ * - =Table[[#Data],[ColA]:[ColB]]
+ * - =Table[[#This Row],[Column]]
+ *
+ * Not supported (invalid):
+ * - Multiple sections in parallel (e.g., [[#Headers],[#Data]])
+ * - Non-existent sections (e.g., #Title)
+ * - Column indices instead of column names (e.g., [[1]:[3]])
+ */
export class TableReferenceObject extends BaseReferenceObject {
+ private _isCurrentRowForRange: boolean = false;
+
constructor(
token: string,
private _tableData: ISuperTable,
- private _columnDataString: string,
- tableOptionMap: Map<string, TableOptionType>
+ /**
+ * Structured reference body (with or without outer []):
+ * - "#Data" / "#All"
+ * - "[Col]" / "[[ColA]:[ColB]]"
+ * - "[[#Data],[Col]]" / "[[#All],[ColA]:[ColB]]"
+ */
+ private _columnDataString: string | undefined,
+ /** Section text to enum mapping ('#All', '#Data', '#Headers', '#Totals', '#This Row') */
+ private _tableOptionMap: Map<string, TableOptionType>
) {
super(token);
- const sheetId = this._tableData.sheetId;
- const range = this._tableData.range;
- const titleMap = this._tableData.titleMap;
+ const { sheetId, range, titleMap } = this._tableData;
this.setForcedSheetIdDirect(sheetId);
- const columnData = this._stringToColumnData(this._columnDataString, titleMap, tableOptionMap);
- const startColumn = columnData.startColumn;
- const endColumn = columnData.endColumn;
- const type = columnData.type;
- let startRow = -1;
- let endRow = -1;
+ const { startColumn, endColumn, type } = this._parseStructuredRef(this._columnDataString, titleMap);
const tableStartRow = range.startRow;
+ const tableEndRow = range.endRow;
- const tableEndRow = range.startColumn;
-
- if (type === TableOptionType.ALL) {
- startRow = tableStartRow;
- endRow = tableEndRow;
- } else if (type === TableOptionType.DATA) {
- startRow = tableStartRow + 1;
- endRow = tableEndRow;
- } else if (type === TableOptionType.HEADERS) {
- startRow = tableStartRow;
- endRow = tableStartRow;
- } else if (type === TableOptionType.TOTALS) {
- startRow = tableEndRow;
- endRow = tableEndRow;
+ let startRow = -1;
+ let endRow = -1;
+
+ switch (type) {
+ case TableOptionType.ALL:
+ startRow = tableStartRow;
+ endRow = tableEndRow;
+ break;
+ case TableOptionType.DATA:
+ // Default: First row is header, data area = [startRow+1, endRow]
+ startRow = tableStartRow + 1;
+ endRow = tableEndRow;
+ break;
+ case TableOptionType.HEADERS:
+ startRow = tableStartRow;
+ endRow = tableStartRow;
+ break;
+ case TableOptionType.TOTALS:
+ startRow = tableEndRow;
+ endRow = tableEndRow;
+ break;
+ case TableOptionType.THIS_ROW: {
+ const r = this._resolveThisRow(tableStartRow, tableEndRow);
+ startRow = r;
+ endRow = r;
+ break;
+ }
+ default:
+ // Defensive: Unknown type defaults to DATA
+ startRow = tableStartRow + 1;
+ endRow = tableEndRow;
+ break;
}
this.setRangeData({
@@ -72,68 +103,237 @@ export class TableReferenceObject extends BaseReferenceObject {
});
}
+ override getRangeData() {
+ const rangeData = super.getRangeData();
+ if (this._isCurrentRowForRange) {
+ const { startRow, startColumn, endRow, endColumn } = rangeData;
+ const currentRow = this.getCurrentRow();
+ return {
+ startRow: currentRow == null ? startRow : currentRow,
+ endRow: currentRow == null ? endRow : currentRow,
+ startColumn,
+ endColumn,
+ };
+ }
+ return rangeData;
+ }
+
+ override getRefOffset() {
+ return {
+ x: 0,
+ y: 0,
+ };
+ }
+
override isTable() {
return true;
}
- private _stringToColumnData(
- columnDataString: string,
- titleMap: Map<string, number>,
- tableOptionMap: Map<string, TableOptionType>
- ) {
- columnDataString = columnDataString.substring(1, -1);
- const commaIndex = columnDataString.indexOf(matchToken.COMMA);
- let startColumn = -1;
- let endColumn = -1;
- let type = TableOptionType.ALL;
- if (commaIndex === -1) {
- const data = this._columnHandler(columnDataString, titleMap);
- startColumn = data.startColumn;
- endColumn = data.endColumn;
- } else {
- // =Table2[[#Headers],[11111]:[Column3]]
- const rowString = columnDataString.substring(0, commaIndex).substring(1, -1);
- const columnString = columnDataString.substring(commaIndex + 1);
-
- const data = this._columnHandler(columnString, titleMap, true);
- startColumn = data.startColumn;
- endColumn = data.endColumn;
-
- type = tableOptionMap.get(rowString)!;
- if (!type) {
- type = TableOptionType.ALL;
+ override isCurrentRowForRange(): boolean {
+ return this._isCurrentRowForRange;
+ }
+
+ override setForcedSheetId(sheetNameMap: IUnitSheetNameMap) {
+ // No-op: already set in constructor
+ }
+
+ /**
+ * Parse structured reference body, returning column range and Section type.
+ * Determination rules:
+ * - Whether it's a Section depends on "whether it starts with # after stripping", not whether it still has brackets.
+ * - No comma: Either Section, or column/column range
+ * - Has comma: Left is Section, right is column/column range
+ */
+ private _parseStructuredRef(
+ raw: string | undefined,
+ titleMap: Map<string, number>
+ ): { startColumn: number; endColumn: number; type: TableOptionType } {
+ const { range } = this._tableData;
+ const fullStartCol = range.startColumn ?? 0;
+ const fullEndCol = range.endColumn ?? 0;
+
+ if (!raw || raw.trim().length === 0) {
+ // Empty reference: By conventional semantics → all columns in data area
+ return { startColumn: fullStartCol, endColumn: fullEndCol, type: TableOptionType.DATA };
+ }
+
+ const s = raw.trim();
+
+ // Section-only form (without brackets): e.g., "#Data"
+ if (s[0] !== '[') {
+ const typeMaybe = this._mapSection(s); // Only hits if starts with #
+ if (typeMaybe !== undefined) {
+ return { startColumn: fullStartCol, endColumn: fullEndCol, type: typeMaybe };
}
+ // Not a Section: Treat as column name (rare, but for error tolerance)
+ const { startColumn, endColumn } = this._parseColumnOrRange(s, titleMap, fullStartCol);
+ return { startColumn, endColumn, type: TableOptionType.DATA };
}
- return {
- startColumn,
- endColumn,
- type,
- };
- }
+ // Strip one layer of outer brackets
+ const body = this._stripOuterBracketOnce(s);
+ const commaAt = this._findCommaAtTopLevel(body);
- private _columnHandler(rightString: string, titleMap: Map<string, number>, isSingle = false) {
- let startColumn = -1;
- let endColumn = -1;
- const colonIndex = rightString.indexOf(matchToken.COLON);
- if (regexTestSuperTableColumn(rightString)) {
- // =Table2[[11111]:[222]]
- const startColumnString = rightString.substring(0, colonIndex).substring(1, -1);
- const endColumnString = rightString.substring(colonIndex + 1).substring(1, -1);
- startColumn = titleMap.get(startColumnString) ?? -1;
- endColumn = titleMap.get(endColumnString) ?? -1;
- } else {
- // =Table2[222] =Table2[[222]]
- if (isSingle) {
- rightString = rightString.substring(1, -1);
+ if (body.length === 0) {
+ // Empty brackets: By conventional semantics → all columns in data area
+ return { startColumn: fullStartCol, endColumn: fullEndCol, type: TableOptionType.DATA };
+ }
+
+ if (commaAt === -1) {
+ // No comma: Either Section, or column/column range
+ if (body.startsWith('#')) {
+ const typeMaybe = this._mapSection(body);
+ if (typeMaybe !== undefined) {
+ return { startColumn: fullStartCol, endColumn: fullEndCol, type: typeMaybe };
+ }
+ // '#...' but not recognized → fallback to DATA (could also throw error)
+ return { startColumn: fullStartCol, endColumn: fullEndCol, type: TableOptionType.DATA };
}
- startColumn = titleMap.get(rightString) ?? -1;
- endColumn = startColumn;
+ // Not a Section: column/column range. Note: passing original s (with brackets) is more robust.
+ const { startColumn, endColumn } = this._parseColumnOrRange(body, titleMap, fullStartCol);
+ return { startColumn, endColumn, type: TableOptionType.DATA };
}
- return {
- startColumn,
- endColumn,
- };
+ // Has comma: Left Section + Right column/column range
+ const sectionRaw = body.slice(0, commaAt).trim(); // May be "[#Data]" or "#Data"
+ const columnsRaw = body.slice(commaAt + 1).trim(); // May be "[Col]" or "[[ColA]:[ColB]]" or "Col"
+
+ const section = this._parseSectionMaybeBracketed(sectionRaw);
+ const { startColumn, endColumn } = this._parseColumnOrRange(columnsRaw, titleMap, fullStartCol);
+
+ return { startColumn, endColumn, type: section };
+ }
+
+ /** Strip one layer of outer brackets from "[...]" (return as-is if none) */
+ private _stripOuterBracketOnce(s: string): string {
+ if (s.length >= 2 && s[0] === '[' && s[s.length - 1] === ']') {
+ return s.slice(1, -1);
+ }
+ return s;
+ }
+
+ /**
+ * Find first comma at depth=0 (used to split Section and column parts)
+ * Compatible with nesting like "[[#Data],[ColA]:[ColB]]".
+ */
+ private _findCommaAtTopLevel(s: string): number {
+ let depth = 0;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (ch === '[') depth++;
+ else if (ch === ']') depth = Math.max(0, depth - 1);
+ else if (ch === matchToken.COMMA && depth === 0) return i;
+ }
+ return -1;
+ }
+
+ /**
+ * Parse Section, compatible with both "[#Data]" and "#Data" inputs
+ * Returns TableOptionType if matched; returns DATA if not (could throw error instead)
+ */
+ private _parseSectionMaybeBracketed(raw: string): TableOptionType {
+ const x = raw.trim();
+ const inner = (x.startsWith('[') && x.endsWith(']')) ? this._stripOuterBracketOnce(x) : x;
+ const typeMaybe = this._mapSection(inner);
+ return typeMaybe ?? TableOptionType.DATA;
+ }
+
+ /**
+ * Section mapping: Only accepts keywords starting with #.
+ * Returns undefined if not a valid Section (caller treats as column or fallback).
+ */
+ private _mapSection(x: string): TableOptionType | undefined {
+ const key = x.trim();
+ if (!key.startsWith('#')) return undefined;
+
+ // Exact match
+ const hit = this._tableOptionMap.get(key);
+ if (hit !== undefined) return hit;
+
+ // Lenient: Remove extra spaces / ignore case
+ const norm = key.replace(/\s+/g, ' ').toLowerCase();
+ for (const [k, v] of this._tableOptionMap.entries()) {
+ const kk = k.replace(/\s+/g, ' ').toLowerCase();
+ if (kk === norm) return v;
+ }
+ return undefined;
+ }
+
+ /**
+ * Parse column selection:
+ * - "[Col]" / "Col" => Single column
+ * - "[[ColA]:[ColB]]" / "[ColA]:[ColB]" / "ColA:ColB" => Column range
+ *
+ * Rules:
+ * - First find colon at top level, strip one layer of brackets from left and right sides (if present)
+ * - Returns -1 if column name not found (caller should handle as parse error)
+ */
+ private _parseColumnOrRange(
+ raw: string,
+ titleMap: Map<string, number>,
+ fullStartCol: number
+ ): { startColumn: number; endColumn: number } {
+ const s = raw.trim();
+
+ // Check if there's a range colon at top level
+ const colonAt = this._findColonAtTopLevel(s);
+ if (colonAt === -1) {
+ // Single column (may be "[Col]" or "Col")
+ const name = this._stripOuterBracketIfAny(s);
+ const idx = this._titleToIndex(name, titleMap);
+ return { startColumn: fullStartCol + idx, endColumn: +fullStartCol + idx };
+ }
+
+ // Range: Left and right may be "[ColA]" / "ColA"
+ const left = s.slice(0, colonAt).trim();
+ const right = s.slice(colonAt + 1).trim();
+
+ const leftName = this._stripOuterBracketIfAny(left);
+ const rightName = this._stripOuterBracketIfAny(right);
+
+ const l = this._titleToIndex(leftName, titleMap);
+ const r = this._titleToIndex(rightName, titleMap);
+
+ // Excel requires l <= r; swap for error tolerance here (could throw error for strict conformance)
+ if (l !== -1 && r !== -1 && l > r) {
+ return { startColumn: fullStartCol + r, endColumn: fullStartCol + l };
+ }
+ return { startColumn: fullStartCol + l, endColumn: fullStartCol + r };
+ }
+
+ /** Strip one layer of outer brackets; return as-is if none (compatible with "[Col]" and "Col") */
+ private _stripOuterBracketIfAny(t: string): string {
+ return (t.length >= 2 && t[0] === '[' && t[t.length - 1] === ']')
+ ? t.slice(1, -1)
+ : t;
+ }
+
+ /** Find range colon at depth=0 */
+ private _findColonAtTopLevel(s: string): number {
+ let depth = 0;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (ch === '[') depth++;
+ else if (ch === ']') depth = Math.max(0, depth - 1);
+ else if (ch === matchToken.COLON && depth === 0) return i;
+ }
+ return -1;
+ }
+
+ /** Column title → column index; returns -1 if not found (caller should handle as parse error) */
+ private _titleToIndex(name: string, titleMap: Map<string, number>): number {
+ const key = name.trim();
+ const hit = titleMap.get(key);
+ if (hit !== undefined) return hit;
+
+ // Defensive: Full-width space → half-width, then trim
+ const keyNorm = key.replace(/\u3000/g, ' ').trim();
+ return titleMap.get(keyNorm) ?? -1;
+ }
+
+ /** Resolve #This Row's row number; takes first data row (tableStartRow+1) when no context available */
+ private _resolveThisRow(tableStartRow: number, tableEndRow: number): number {
+ this._isCurrentRowForRange = true;
+ return Math.min(tableStartRow + 1, tableEndRow);
}
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 1bcb9ada5e..ab3e01b4fb 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -62,6 +62,7 @@ export {
export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './commands/mutations/set-formula-data.mutation';
export { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';
export { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';
+export type { ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from './commands/mutations/set-super-table.mutation';
export { CalculateController } from './controller/calculate.controller';
export { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY, type IUniverEngineFormulaConfig } from './controller/config.schema';
export { Lexer } from './engine/analysis/lexer';
diff --git a/packages/engine-formula/src/services/super-table.service.ts b/packages/engine-formula/src/services/super-table.service.ts
index 9b5fd93837..aea8795b9a 100644
--- a/packages/engine-formula/src/services/super-table.service.ts
+++ b/packages/engine-formula/src/services/super-table.service.ts
@@ -15,9 +15,12 @@
*/
import type { Nullable } from '@univerjs/core';
-import type { ISuperTable, TableOptionType } from '../basics/common';
+import type { Observable } from 'rxjs';
+import type { ISuperTable } from '../basics/common';
import { createIdentifier, Disposable } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { TableOptionType } from '../basics/common';
export interface ISuperTableOptionParam {
tableOption: string;
@@ -34,6 +37,8 @@ export interface ISuperTableService {
registerTableOptionMap(tableOption: string, tableOptionType: TableOptionType): void;
remove(unitId: string, tableName: string): void;
+
+ update$: Observable<unknown>;
}
export class SuperTableService extends Disposable implements ISuperTableService {
@@ -43,15 +48,28 @@ export class SuperTableService extends Disposable implements ISuperTableService
// 18.5.1.2 table (Table) for I18N
private _tableOptionMap: Map<string, TableOptionType> = new Map();
+ private readonly _update$ = new Subject();
+ readonly update$ = this._update$.asObservable();
+
+ constructor() {
+ super();
+ this.registerTableOptionMap(TableOptionType.ALL, TableOptionType.ALL);
+ this.registerTableOptionMap(TableOptionType.DATA, TableOptionType.DATA);
+ this.registerTableOptionMap(TableOptionType.HEADERS, TableOptionType.HEADERS);
+ this.registerTableOptionMap(TableOptionType.TOTALS, TableOptionType.TOTALS);
+ this.registerTableOptionMap(TableOptionType.THIS_ROW, TableOptionType.THIS_ROW);
+ }
+
override dispose(): void {
super.dispose();
-
+ this._update$.complete();
this._tableMap.clear();
this._tableOptionMap.clear();
}
remove(unitId: string, tableName: string) {
this._tableMap.get(unitId)?.delete(tableName);
+ this._update();
}
getTableMap(unitId: string) {
@@ -67,11 +85,16 @@ export class SuperTableService extends Disposable implements ISuperTableService
this._tableMap.set(unitId, new Map());
}
this._tableMap.get(unitId)?.set(tableName, reference);
+ this._update();
}
registerTableOptionMap(tableOption: string, tableOptionType: TableOptionType) {
this._tableOptionMap.set(tableOption, tableOptionType);
}
+
+ private _update() {
+ this._update$.next(null);
+ }
}
export const ISuperTableService = createIdentifier<ISuperTableService>('univer.formula.super-table.service');
diff --git a/packages/sheets-formula/src/controllers/super-table.controller.ts b/packages/sheets-formula/src/controllers/super-table.controller.ts
new file mode 100644
index 0000000000..b12930cbba
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/super-table.controller.ts
@@ -0,0 +1,215 @@
+/**
+ * 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 { ICommandInfo, IExecutionOptions, Nullable, Workbook } from '@univerjs/core';
+import type { IFunctionInfo, ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';
+import {
+ Disposable,
+ ICommandService,
+ IUniverInstanceService,
+ toDisposable,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { FunctionType, ISuperTableService, RemoveSuperTableMutation, serializeRangeWithSheet, SetSuperTableMutation } from '@univerjs/engine-formula';
+import { SetWorksheetActiveOperation } from '@univerjs/sheets';
+
+import { IDescriptionService } from '../services/description.service';
+
+/**
+ * header highlight
+ * column menu: show, hover and mousedown event
+ */
+export class SuperTableController extends Disposable {
+ private _preUnitId: Nullable<string> = null;
+
+ constructor(
+ @IDescriptionService private readonly _descriptionService: IDescriptionService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @ISuperTableService private readonly _superTableService: ISuperTableService
+
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize() {
+ this._descriptionListener();
+
+ this._changeUnitListener();
+
+ this._changeSheetListener();
+ }
+
+ private _descriptionListener() {
+ toDisposable(
+ this._superTableService.update$.subscribe(() => {
+ this._registerDescriptions();
+ })
+ );
+ }
+
+ private _changeUnitListener() {
+ toDisposable(
+ this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe(() => {
+ this._unRegisterDescriptions();
+ this._registerDescriptions();
+ })
+ );
+ }
+
+ private _changeSheetListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {
+ if (options?.fromCollab) {
+ return;
+ }
+
+ if (command.id === SetWorksheetActiveOperation.id) {
+ this._unregisterDescriptionsForNotInSheetId();
+ this._registerDescriptions();
+ }
+ // Since command interception will supplement mutation, it is necessary to monitor mutation changes here
+ // SetDefinedNameMutation and RemoveDefinedNameMutation already cover all possible Defined Name updates
+ else if (command.id === SetSuperTableMutation.id) {
+ const param = command.params as ISetSuperTableMutationParam;
+ this._registerDescription(param);
+ } else if (command.id === RemoveSuperTableMutation.id) {
+ const param = command.params as ISetSuperTableMutationSearchParam;
+ this._unregisterDescription(param);
+ }
+ })
+ );
+ }
+
+ private _registerDescription(param: ISetSuperTableMutationParam) {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const { tableName, reference } = param;
+ if (!this._descriptionService.hasDescription(tableName)) {
+ const sheetName = this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(reference.sheetId)?.getName() || '';
+ const refString = serializeRangeWithSheet(sheetName, reference.range);
+ this._descriptionService.registerDescriptions([{
+ functionName: tableName,
+ description: refString,
+ abstract: refString,
+ functionType: FunctionType.Table,
+ functionParameter: [],
+ }]);
+ }
+ }
+
+ private _unregisterDescription(param: ISetSuperTableMutationSearchParam) {
+ const { tableName } = param;
+ this._descriptionService.unregisterDescriptions([tableName]);
+ }
+
+ private _unRegisterDescriptions() {
+ if (this._preUnitId == null) {
+ return;
+ }
+ const superTables = this._superTableService.getTableMap(this._preUnitId);
+
+ if (superTables == null) {
+ return;
+ }
+
+ const functionList: string[] = [];
+ superTables.forEach((_, tableName) => {
+ functionList.push(tableName);
+ });
+
+ this._descriptionService.unregisterDescriptions(functionList);
+
+ this._preUnitId = null;
+ }
+
+ private _getUnitIdAndSheetId() {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ if (workbook == null) {
+ return {};
+ }
+ const worksheet = workbook.getActiveSheet();
+
+ if (worksheet == null) {
+ return {};
+ }
+
+ return {
+ unitId: workbook.getUnitId(),
+ sheetId: worksheet.getSheetId(),
+ };
+ }
+
+ private _registerDescriptions() {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const superTables = this._superTableService.getTableMap(unitId);
+ if (!superTables) {
+ return;
+ }
+
+ const functionList: IFunctionInfo[] = [];
+
+ this._preUnitId = unitId;
+
+ superTables.forEach((table, tableName) => {
+ const sheetName = this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(table.sheetId)?.getName() || '';
+ const refString = serializeRangeWithSheet(sheetName, table.range);
+ if (!this._descriptionService.hasDescription(tableName)) {
+ functionList.push({
+ functionName: tableName,
+ description: refString,
+ abstract: refString,
+ functionType: FunctionType.Table,
+ functionParameter: [],
+ });
+ }
+ });
+
+ this._descriptionService.registerDescriptions(functionList);
+ }
+
+ private _unregisterDescriptionsForNotInSheetId() {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const superTables = this._superTableService.getTableMap(unitId);
+ if (!superTables) {
+ return;
+ }
+
+ const functionList: string[] = [];
+
+ superTables.forEach((_, tableName) => {
+ functionList.push(tableName);
+ });
+
+ this._descriptionService.unregisterDescriptions(functionList);
+ }
+}
diff --git a/packages/sheets-formula/src/plugin.ts b/packages/sheets-formula/src/plugin.ts
index c979ebffc5..46ac884230 100644
--- a/packages/sheets-formula/src/plugin.ts
+++ b/packages/sheets-formula/src/plugin.ts
@@ -31,6 +31,7 @@ import {
} from './controllers/config.schema';
import { DefinedNameController } from './controllers/defined-name.controller';
import { FormulaController } from './controllers/formula.controller';
+import { SuperTableController } from './controllers/super-table.controller';
import { TriggerCalculationController } from './controllers/trigger-calculation.controller';
import { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
import { UpdateFormulaController } from './controllers/update-formula.controller';
@@ -105,6 +106,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[ActiveDirtyController],
[DefinedNameController],
[UpdateDefinedNameController],
+ [SuperTableController],
];
// If the plugin do not execute formula, it should delegate a remote proxy.
@@ -139,6 +141,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
override onRendered(): void {
touchDependencies(this._injector, [
[DefinedNameController],
+ [SuperTableController],
]);
// Wait for rendering to complete before initializing formula calculation
diff --git a/packages/sheets-table/package.json b/packages/sheets-table/package.json
index 9b2d359e7c..dcddc82e4b 100644
--- a/packages/sheets-table/package.json
+++ b/packages/sheets-table/package.json
@@ -75,6 +75,7 @@
},
"dependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/sheets": "workspace:*"
},
"devDependencies": {
diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
new file mode 100644
index 0000000000..f447170969
--- /dev/null
+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
@@ -0,0 +1,98 @@
+/**
+ * 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 { ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';
+import type { Table } from '../model/table';
+import { Disposable, ICommandService, Inject } from '@univerjs/core';
+import { RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';
+import { TableManager } from '../model/table-manager';
+
+export class SheetTableFormulaController extends Disposable {
+ constructor(
+ @Inject(TableManager) private _tableManager: TableManager,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+ this._initRangeListener();
+ }
+
+ private _initRangeListener() {
+ this.disposeWithMe(
+ this._tableManager.tableRangeChanged$.subscribe((event) => {
+ const { tableId, unitId } = event;
+ const table = this._tableManager.getTableById(unitId, tableId);
+ if (!table) {
+ return;
+ }
+ this._updateSuperTable(unitId, table);
+ })
+ );
+ this.disposeWithMe(
+ this._tableManager.tableAdd$.subscribe((event) => {
+ const { tableId, unitId } = event;
+ const table = this._tableManager.getTableById(unitId, tableId);
+ if (!table) {
+ return;
+ }
+ this._updateSuperTable(unitId, table);
+ })
+ );
+ this.disposeWithMe(
+ this._tableManager.tableDelete$.subscribe((event) => {
+ const { unitId, tableName } = event;
+ this._commandService.executeCommand<ISetSuperTableMutationSearchParam>(RemoveSuperTableMutation.id, {
+ unitId,
+ tableName,
+ });
+ })
+ );
+ this.disposeWithMe(
+ this._tableManager.tableNameChanged$.subscribe((event) => {
+ const { tableId, unitId, oldTableName } = event;
+
+ this._commandService.executeCommand<ISetSuperTableMutationSearchParam>(RemoveSuperTableMutation.id, {
+ unitId,
+ tableName: oldTableName,
+ });
+
+ const table = this._tableManager.getTableById(unitId, tableId);
+ if (!table) {
+ return;
+ }
+ this._updateSuperTable(unitId, table);
+ })
+ );
+ }
+
+ private _updateSuperTable(unitId: string, table: Table) {
+ const tableInfo = table.getTableInfo();
+ const name = tableInfo.name;
+ const columns = tableInfo.columns;
+ const titleMap = new Map<string, number>();
+ columns.forEach((column, index) => {
+ titleMap.set(column.displayName, index);
+ });
+ this._commandService.executeCommand<ISetSuperTableMutationParam>(SetSuperTableMutation.id, {
+ unitId,
+ tableName: name,
+ reference: {
+ range: tableInfo.range,
+ sheetId: tableInfo.subUnitId,
+ titleMap,
+ },
+ });
+ }
+}
diff --git a/packages/sheets-table/src/plugin.ts b/packages/sheets-table/src/plugin.ts
index 557d64d35d..7851a30938 100644
--- a/packages/sheets-table/src/plugin.ts
+++ b/packages/sheets-table/src/plugin.ts
@@ -29,6 +29,7 @@ import { SetSheetTableMutation } from './commands/mutations/set-sheet-table.muta
import { SetSheetTableFilterMutation } from './commands/mutations/set-table-filter.mutation';
import { PLUGIN_NAME } from './const';
import { defaultPluginConfig, SHEETS_TABLE_PLUGIN_CONFIG_KEY } from './controllers/config.schema';
+import { SheetTableFormulaController } from './controllers/sheet-table-formula.controller';
import { SheetTableRangeController } from './controllers/sheet-table-range.controller';
import { SheetTableRefRangeController } from './controllers/sheet-table-ref-range.controller';
import { SheetsTableThemeController } from './controllers/sheet-table-theme.controller';
@@ -68,9 +69,13 @@ export class UniverSheetsTablePlugin extends Plugin {
[TableFilterController],
[SheetTableRangeController],
[SheetTableRefRangeController],
+ [SheetTableFormulaController],
]);
+ }
+ override onReady(): void {
touchDependencies(this._injector, [
+ [SheetTableFormulaController],
[SheetTableRangeController],
[SheetTableRefRangeController],
[SheetsTableThemeController],
@@ -78,9 +83,7 @@ export class UniverSheetsTablePlugin extends Plugin {
[SheetTableService],
[TableFilterController],
]);
- }
- override onReady(): void {
touchDependencies(this._injector, [
[TableManager],
]);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e2f49c67f7..e319f7cccd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2879,6 +2879,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets