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(sheets): preserve imported workbook semantics and formula caches (#7673)

Univer1484a245ba7f
diff --git a/packages/core/src/facade/f-enum.ts b/packages/core/src/facade/f-enum.ts
index 364ed514b0..c41b197364 100644
--- a/packages/core/src/facade/f-enum.ts
+++ b/packages/core/src/facade/f-enum.ts
@@ -34,6 +34,7 @@ import {
DeveloperMetadataVisibility,
Dimension,
Direction,
+ FormulaType,
HorizontalAlign,
ImageSourceType,
InterpolationPointType,
@@ -52,6 +53,7 @@ import {
ThemeColorType,
UniverInstanceType,
VerticalAlign,
+ WorksheetHiddenState,
WrapStrategy,
} from '@univerjs/core';
@@ -59,6 +61,16 @@ import {
* @hideconstructor
*/
export class FEnum {
+ /** SpreadsheetML formula types. */
+ get FormulaType(): typeof FormulaType {
+ return FormulaType;
+ }
+
+ /** Worksheet hiding states: VISIBLE (0), HIDDEN (1), VERY_HIDDEN (2). */
+ get WorksheetHiddenState(): typeof WorksheetHiddenState {
+ return WorksheetHiddenState;
+ }
+
/**
* @ignore
*/
diff --git a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
index 96410fe03b..8bf90b2b1b 100644
--- a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
+++ b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
@@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest';
import { Tools } from '../../shared/tools';
import { BooleanNumber } from '../../types/enum';
import { cloneWorksheetData } from '../clone';
+import { WorksheetHiddenState } from '../typedef';
function createTestWorksheetData(rowCount: number, colCount: number): IWorksheetData {
const cellData: IWorksheetData['cellData'] = {};
@@ -58,7 +59,7 @@ function createTestWorksheetData(rowCount: number, colCount: number): IWorksheet
id: 'test-sheet-id',
name: 'Test Sheet',
tabColor: '#FF0000',
- hidden: BooleanNumber.FALSE,
+ hidden: WorksheetHiddenState.VERY_HIDDEN,
freeze: {
xSplit: 0,
ySplit: 0,
@@ -112,6 +113,8 @@ describe('cloneWorksheetData', () => {
expect(cloned.id).toBe(original.id);
expect(cloned.name).toBe(original.name);
expect(cloned.tabColor).toBe(original.tabColor);
+ expect(cloned.hidden).toBe(WorksheetHiddenState.VERY_HIDDEN);
+ expect(cloned).not.toHaveProperty('visibility');
expect(cloned.rowCount).toBe(original.rowCount);
expect(cloned.columnCount).toBe(original.columnCount);
diff --git a/packages/core/src/sheets/__tests__/clone.spec.ts b/packages/core/src/sheets/__tests__/clone.spec.ts
new file mode 100644
index 0000000000..25d23752e7
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/clone.spec.ts
@@ -0,0 +1,33 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { BooleanNumber } from '../../types/enum';
+import { cloneCellData, cloneCellDataWithSpanAndDisplay } from '../clone';
+import { FormulaType } from '../typedef';
+
+describe('formula metadata cloning', () => {
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])('retains the array kind and dynamic flag %s in cell and clipboard clones', (fd) => {
+ const source = { f: '=SUM(A1:A2)', ft: FormulaType.ARRAY, fd };
+ expect(cloneCellData(source)).toEqual(source);
+ expect(cloneCellDataWithSpanAndDisplay({ ...source, rowSpan: 2, displayV: '3' })).toEqual({
+ ...source,
+ rowSpan: 2,
+ displayV: '3',
+ });
+ expect(cloneCellData({ v: 'text' })).toEqual({ v: 'text' });
+ });
+});
diff --git a/packages/core/src/sheets/__tests__/workbook.spec.ts b/packages/core/src/sheets/__tests__/workbook.spec.ts
index d8eda2f09c..e8bc03cabc 100644
--- a/packages/core/src/sheets/__tests__/workbook.spec.ts
+++ b/packages/core/src/sheets/__tests__/workbook.spec.ts
@@ -18,8 +18,9 @@ import type { Univer } from '../../univer';
import type { IWorkbookData } from '../typedef';
import type { Workbook } from '../workbook';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { BooleanNumber, DateSystem } from '../../types/enum';
+import { DateSystem } from '../../types/enum';
import { LocaleType } from '../../types/enum/locale-type';
+import { WorksheetHiddenState } from '../typedef';
import { createCoreTestBed } from './create-core-test-bed';
describe('Test workbook', () => {
@@ -131,7 +132,7 @@ describe('Test workbook', () => {
styles: {},
sheetOrder: ['s1', 's2'],
sheets: {
- s1: { id: 's1', name: 'Hidden', hidden: BooleanNumber.TRUE },
+ s1: { id: 's1', name: 'Hidden', hidden: WorksheetHiddenState.VERY_HIDDEN },
s2: { id: 's2', name: 'Visible' },
},
};
@@ -143,6 +144,8 @@ describe('Test workbook', () => {
expect(hiddenWorkbook.getActiveSheet().getSheetId()).toBe('s2');
expect(hiddenWorkbook.getActiveSheetIndex()).toBe(1);
expect(hiddenWorkbook.getHiddenWorksheets()).toEqual(['s1']);
+ expect(hiddenWorkbook.getHiddenWorksheets(false)).toEqual([]);
+ expect(hiddenWorkbook.getSheetBySheetId('s1')?.getHiddenState()).toBe(WorksheetHiddenState.VERY_HIDDEN);
expect(hiddenWorkbook.getUnhiddenWorksheets()).toEqual(['s2']);
expect(hiddenWorkbook.checkSheetName('visible')).toBe(true);
diff --git a/packages/core/src/sheets/clone.ts b/packages/core/src/sheets/clone.ts
index 09ba94deab..b446f259ab 100644
--- a/packages/core/src/sheets/clone.ts
+++ b/packages/core/src/sheets/clone.ts
@@ -95,6 +95,14 @@ export function cloneCellData(cell: Nullable<ICellData>): Nullable<ICellData> {
result.f = cell.f;
}
+ if (cell.ft !== undefined) {
+ result.ft = cell.ft;
+ }
+
+ if (cell.fd !== undefined) {
+ result.fd = cell.fd;
+ }
+
// ref - formula array reference
if (cell.ref !== undefined) {
result.ref = cell.ref;
@@ -129,56 +137,7 @@ export function cloneCellDataWithSpanAndDisplay(cell: Nullable<ICellDataWithSpan
return cell;
}
- const result: ICellDataWithSpanAndDisplay = {};
-
- // p - IDocumentData (complex object, needs deep clone)
- if (cell.p !== undefined) {
- result.p = cell.p === null ? null : cloneValue(cell.p);
- }
-
- // s - style id (string) or IStyleData (object)
- if (cell.s !== undefined) {
- if (cell.s === null || typeof cell.s === 'string') {
- result.s = cell.s;
- } else {
- result.s = cloneValue(cell.s);
- }
- }
-
- // v - primitive value (string | number | boolean)
- if (cell.v !== undefined) {
- result.v = cell.v;
- }
-
- // t - CellValueType (number enum)
- if (cell.t !== undefined) {
- result.t = cell.t;
- }
-
- // f - formula string
- if (cell.f !== undefined) {
- result.f = cell.f;
- }
-
- // ref - formula array reference
- if (cell.ref !== undefined) {
- result.ref = cell.ref;
- }
-
- // xf - Excel formula prefix
- if (cell.xf !== undefined) {
- result.xf = cell.xf;
- }
-
- // si - formula id
- if (cell.si !== undefined) {
- result.si = cell.si;
- }
-
- // custom - user stored custom fields
- if (cell.custom !== undefined) {
- result.custom = cell.custom === null ? null : cloneValue(cell.custom);
- }
+ const result: ICellDataWithSpanAndDisplay = cloneCellData(cell)!;
// rowSpan - span properties (primitives)
if (cell.rowSpan !== undefined) {
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index bb51fddb9c..7e947c676e 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -89,6 +89,16 @@ export interface IWorkbookData {
custom?: CustomData;
}
+/** Worksheet-only hiding states; row/column and cell flags still use BooleanNumber. */
+export enum WorksheetHiddenState {
+ /** Visible in the sheet bar. Preserves the existing hidden: 0 value. */
+ VISIBLE = 0,
+ /** Hidden, and listed in the UI's Unhide dialog. Preserves hidden: 1. */
+ HIDDEN = 1,
+ /** Omitted from Unhide UI; can be revealed through the API. Not an access permission. */
+ VERY_HIDDEN = 2,
+}
+
/**
* Snapshot of a worksheet.
*/
@@ -104,14 +114,12 @@ export interface IWorksheetData {
tabColor: string;
/**
- * Determine whether the sheet is hidden.
- *
- * @remarks
- * See {@link BooleanNumber| the BooleanNumber enum} for more details.
- *
- * @defaultValue `BooleanNumber.FALSE`
+ * Sheet hiding state: 0 = visible, 1 = hidden, 2 = very hidden.
+ * BooleanNumber remains accepted for existing 0/1 snapshots and integrations.
+ * Use WorksheetHiddenState for new code; do not interpret this as a boolean flag.
+ * @defaultValue WorksheetHiddenState.VISIBLE
*/
- hidden: BooleanNumber;
+ hidden: WorksheetHiddenState | BooleanNumber;
freeze: IFreeze;
@@ -246,6 +254,15 @@ export interface IColAutoWidthInfo {
*/
export type CellValue = string | number | boolean;
+/** Formula kinds from SpreadsheetML ST_CellFormulaType. */
+export enum FormulaType {
+ NORMAL = 0,
+ SHARED = 1,
+ ARRAY = 2,
+ /** What-if analysis data table, not a structured table. */
+ DATA_TABLE = 3,
+}
+
/**
* Cell data
*/
@@ -272,6 +289,12 @@ export interface ICellData {
*/
f?: Nullable<string>;
+ /** Formula type, mapped from OOXML f@t. Omission preserves existing runtime behavior. */
+ ft?: Nullable<FormulaType>;
+
+ /** Dynamic array flag, mapped from the referenced dynamicArrayProperties@fDynamic metadata. */
+ fd?: Nullable<BooleanNumber>;
+
/**
* If the formula is a formula array, this field is used to store the referencing range.
* @ignore
@@ -349,6 +372,8 @@ export function isICellData(value: any): value is ICellData {
(value as ICellData).v !== undefined ||
(value as ICellData).t !== undefined ||
(value as ICellData).f !== undefined ||
+ (value as ICellData).ft !== undefined ||
+ (value as ICellData).fd !== undefined ||
(value as ICellData).si !== undefined ||
(value as ICellData).custom !== undefined)
);
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 540bab67cb..47aab3d650 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -27,6 +27,7 @@ import { BooleanNumber } from '../types/enum';
import { DateSystem } from '../types/enum/date-system';
import { getEmptySnapshot } from './empty-snapshot';
import { Styles } from './styles';
+import { WorksheetHiddenState } from './typedef';
import { Worksheet } from './worksheet';
export function getWorksheetUID(workbook: Workbook, worksheet: Worksheet): string {
@@ -385,15 +386,16 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
return this._worksheets.get(sheetOrder[index]);
}
- getHiddenWorksheets(): string[] {
+ getHiddenWorksheets(includeVeryHidden = true): string[] {
return this.getSheets()
- .filter((s) => s.getConfig().hidden === BooleanNumber.TRUE)
+ .filter((s) => s.isSheetHidden() === BooleanNumber.TRUE)
+ .filter((s) => includeVeryHidden || s.getHiddenState() !== WorksheetHiddenState.VERY_HIDDEN)
.map((s) => s.getConfig().id);
}
getUnhiddenWorksheets(): string[] {
return this.getSheets()
- .filter((s) => s.getConfig().hidden !== BooleanNumber.TRUE)
+ .filter((s) => s.isSheetHidden() !== BooleanNumber.TRUE)
.map((s) => s.getConfig().id);
}
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 5fe8b80e9b..3ca510ab19 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -17,7 +17,7 @@
import type { IDisposable } from '../common/di';
import type { IInterceptor } from '../common/interceptor';
import type { IObjectMatrixPrimitiveType, Nullable } from '../shared';
-import type { BooleanNumber, HorizontalAlign, TextDirection, VerticalAlign, WrapStrategy } from '../types/enum';
+import type { HorizontalAlign, TextDirection, VerticalAlign, WrapStrategy } from '../types/enum';
import type { IDocumentData, IDocumentRenderConfig, IPaddingData, IStyleData, ITextRotation } from '../types/interfaces';
import type { Styles } from './styles';
import type {
@@ -36,14 +36,14 @@ import { composeStyles, ObjectMatrix, toDisposable, Tools } from '../shared';
import { generateRandomId } from '../shared/random-id';
import { createRowColIter } from '../shared/row-col-iter';
import { DEFAULT_STYLES } from '../types/const';
-import { CellValueType } from '../types/enum';
+import { BooleanNumber, CellValueType } from '../types/enum';
import { DocumentFlavor } from '../types/interfaces';
import { ColumnManager } from './column-manager';
import { Range } from './range';
import { RowManager } from './row-manager';
import { mergeWorksheetSnapshotWithDefault } from './sheet-snapshot-utils';
import { SpanModel } from './span-model';
-import { CellModeEnum } from './typedef';
+import { CellModeEnum, WorksheetHiddenState } from './typedef';
import {
addLinkToDocumentModel,
createDocumentModelWithStyle,
@@ -828,12 +828,19 @@ export class Worksheet {
this._snapshot.columnCount = count;
}
- /**
- * isSheetHidden
- * @returns hidden status of sheet
- */
+ /** Returns 0 for visible, 1 for either hidden state, preserving the existing predicate API. */
isSheetHidden(): BooleanNumber {
- return this._snapshot.hidden;
+ return this._snapshot.hidden === WorksheetHiddenState.VISIBLE ? BooleanNumber.FALSE : BooleanNumber.TRUE;
+ }
+
+ /** Returns the complete persisted state, including VERY_HIDDEN (2). */
+ getHiddenState(): WorksheetHiddenState {
+ return this._snapshot.hidden as WorksheetHiddenState;
+ }
+
+ /** Model mutation primitive. User-facing changes must go through worksheet hide/show commands. */
+ setHiddenState(hidden: WorksheetHiddenState | BooleanNumber): void {
+ this._snapshot.hidden = hidden;
}
/**
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index d8999bacf2..7cbfa5d98a 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -245,7 +245,8 @@ export interface IUnitExcludedCell {
}
export interface IUnitRowData {
- [unitId: string]: Nullable<{ [sheetId: string]: IObjectArrayPrimitiveType<Partial<IRowData>> }>;
+ // Calculation transport only: distinguish filter exclusions from manually hidden rows in Workers.
+ [unitId: string]: Nullable<{ [sheetId: string]: IObjectArrayPrimitiveType<Partial<IRowData> & { filtered?: boolean }> }>;
}
export interface IFormulaDatasetConfig {
diff --git a/packages/engine-formula/src/basics/math.ts b/packages/engine-formula/src/basics/math.ts
index 718bf96fc4..e466b62225 100644
--- a/packages/engine-formula/src/basics/math.ts
+++ b/packages/engine-formula/src/basics/math.ts
@@ -98,41 +98,13 @@ export function calculateMdeterm(matrix: number[][]): number {
}
export function calculateMinverse(matrix: number[][]): number[][] | null {
- const det = calculateMdeterm(matrix);
+ const { smallPivotDetected, luMatrix, permutation } = performLUDecomposition(matrix, false, Number.EPSILON);
- if (det === 0) {
+ if (smallPivotDetected) {
return null; // Matrix is irreversible
}
- if (matrix.length === 1) {
- return [[1 / det]];
- }
-
- const adjugate = adjoint(matrix);
- const inverseMatrix = adjugate.map((row) => row.map((value) => value / det));
-
- return inverseMatrix;
-}
-
-function minor(matrix: number[][], row: number, col: number): number[][] {
- return matrix
- .filter((_, r) => r !== row)
- .map((row) => row.filter((_, c) => c !== col));
-}
-
-function adjoint(matrix: number[][]): number[][] {
- const n = matrix.length;
- const adj = Array.from({ length: n }, () => new Array(n).fill(0));
-
- for (let i = 0; i < n; i++) {
- for (let j = 0; j < n; j++) {
- const sign = ((i + j) % 2 === 0 ? 1 : -1);
- const res = sign * calculateMdeterm(minor(matrix, i, j));
- adj[j][i] = (res === 0 ? 0 : res); // deal with -0 case
- }
- }
-
- return adj;
+ return transformMatrix(luMatrix, permutation);
}
export function calculateMmult(matrix1: number[][], matrix2: number[][]): number[][] {
@@ -155,8 +127,8 @@ export function inverseMatrixByLUD(matrix: number[][]) {
return transformMatrix(luMatrix, permutation);
}
-function performLUDecomposition(matrix: number[][]) {
- const decomposedMatrix = matrixTranspose(matrix);
+function performLUDecomposition(matrix: number[][], transpose: boolean = true, minimumPivot: number = 1e-11) {
+ const decomposedMatrix = transpose ? matrixTranspose(matrix) : matrix.map((row) => [...row]);
const numRows = decomposedMatrix.length;
const numCols = decomposedMatrix[0].length;
let isRowSwap = true;
@@ -195,7 +167,9 @@ function performLUDecomposition(matrix: number[][]) {
}
}
- if (Math.abs(luMatrix[pivotRow][c]) < 1e-11) {
+ const pivot = Math.abs(luMatrix[pivotRow][c]);
+
+ if (!Number.isFinite(pivot) || pivot <= minimumPivot) {
smallPivotDetected = true;
break;
}
diff --git a/packages/engine-formula/src/basics/regex.ts b/packages/engine-formula/src/basics/regex.ts
index 574d315c8f..b8ae775390 100644
--- a/packages/engine-formula/src/basics/regex.ts
+++ b/packages/engine-formula/src/basics/regex.ts
@@ -34,7 +34,7 @@ export const RANGE_SYMBOL = '\\s*?:\\s*?';
const COLUMN_REGEX = '[A-Za-z]+';
const ROW_REGEX = '[1-9][0-9]*';
-export const UNIT_NAME_SHEET_NAME_REGEX = `'?(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?'?`;
+export const UNIT_NAME_SHEET_NAME_REGEX = `(?:'(?:[^'\\[]|'')*[\\\\/]|'?)(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?'?`;
export const SIMPLE_SINGLE_RANGE_REGEX = `\\${ABSOLUTE_SYMBOL}?${COLUMN_REGEX}\\${ABSOLUTE_SYMBOL}?${ROW_REGEX}`;
diff --git a/packages/engine-formula/src/basics/statistical.ts b/packages/engine-formula/src/basics/statistical.ts
index 32f104f72e..dddf8ea8fa 100644
--- a/packages/engine-formula/src/basics/statistical.ts
+++ b/packages/engine-formula/src/basics/statistical.ts
@@ -1025,6 +1025,85 @@ function getSlopeAndInterceptOfConstbIsFalse(knownXsValues: number[], knownYsVal
};
}
+function solveLeastSquaresByQR(matrix: number[][], values: number[]): number[] | null {
+ const rows = matrix.length;
+ const columns = matrix[0]?.length ?? 0;
+
+ if (!columns || rows < columns || values.length !== rows || matrix.some((row) => row.length !== columns)) {
+ return null;
+ }
+
+ const qr = matrix.map((row) => [...row]);
+ const scales: number[] = [];
+
+ for (let column = 0; column < columns; column++) {
+ let sumSquares = 0;
+ for (let row = 0; row < rows; row++) {
+ sumSquares += qr[row][column] ** 2;
+ }
+ const scale = Math.sqrt(sumSquares);
+ if (!Number.isFinite(scale) || scale === 0) {
+ return null;
+ }
+ scales.push(scale);
+ for (let row = 0; row < rows; row++) {
+ qr[row][column] /= scale;
+ }
+ }
+
+ const transformed = [...values];
+ for (let pivot = 0; pivot < columns; pivot++) {
+ let sumSquares = 0;
+ for (let row = pivot; row < rows; row++) {
+ sumSquares += qr[row][pivot] ** 2;
+ }
+ const norm = Math.sqrt(sumSquares);
+ if (!Number.isFinite(norm) || norm <= Number.EPSILON * rows) {
+ return null;
+ }
+ const alpha = qr[pivot][pivot] >= 0 ? -norm : norm;
+ const reflector = Array.from({ length: rows - pivot }, (_, offset) => qr[pivot + offset][pivot]);
+ reflector[0] -= alpha;
+ const reflectorNorm = reflector.reduce((sum, value) => sum + value ** 2, 0);
+ if (!Number.isFinite(reflectorNorm) || reflectorNorm === 0) {
+ return null;
+ }
+
+ for (let column = pivot; column < columns; column++) {
+ let projection = 0;
+ for (let offset = 0; offset < reflector.length; offset++) {
+ projection += reflector[offset] * qr[pivot + offset][column];
+ }
+ const factor = 2 * projection / reflectorNorm;
+ for (let offset = 0; offset < reflector.length; offset++) {
+ qr[pivot + offset][column] -= factor * reflector[offset];
+ }
+ }
+ let projection = 0;
+ for (let offset = 0; offset < reflector.length; offset++) {
+ projection += reflector[offset] * transformed[pivot + offset];
+ }
+ const factor = 2 * projection / reflectorNorm;
+ for (let offset = 0; offset < reflector.length; offset++) {
+ transformed[pivot + offset] -= factor * reflector[offset];
+ }
+ }
+
+ const coefficients = new Array(columns).fill(0);
+ for (let row = columns - 1; row >= 0; row--) {
+ const diagonal = qr[row][row];
+ if (!Number.isFinite(diagonal) || Math.abs(diagonal) <= Number.EPSILON * rows) {
+ return null;
+ }
+ let remainder = 0;
+ for (let column = row + 1; column < columns; column++) {
+ remainder += qr[row][column] * coefficients[column];
+ }
+ coefficients[row] = (transformed[row] - remainder) / diagonal;
+ }
+ return coefficients.map((coefficient, index) => coefficient / scales[index]);
+}
+
export function getKnownsArrayCoefficients(knownYsValues: number[][], knownXsValues: number[][], newXsValues: number[][], constb: number, isExponentialTransform: boolean) {
const isOneRow = knownYsValues.length === 1 && knownYsValues[0].length > 1;
@@ -1049,8 +1128,6 @@ export function getKnownsArrayCoefficients(knownYsValues: number[][], knownXsVal
const XT = matrixTranspose(X);
const XTX = calculateMmult(XT, X);
- const XTY = calculateMmult(XT, Y);
-
let XTXInverse = inverseMatrixByLUD(XTX);
if (!XTXInverse) {
@@ -1061,14 +1138,17 @@ export function getKnownsArrayCoefficients(knownYsValues: number[][], knownXsVal
}
}
- let coefficients = calculateMmult(XTXInverse, XTY);
+ const solved = solveLeastSquaresByQR(X, Y.map((row) => row[0]));
+
+ // Preserve the pseudoinverse solution for rank-deficient input.
+ const coefficients = solved
+ ? [solved]
+ : matrixTranspose(calculateMmult(XTXInverse, calculateMmult(XT, Y)));
if (!constb) {
- coefficients.push([0]);
+ coefficients[0].push(0);
}
- coefficients = matrixTranspose(coefficients);
-
const pop = coefficients[0].pop() as number;
coefficients[0].reverse();
@@ -1162,13 +1242,17 @@ const NESTED_AGGREGATE_FORMULA_CACHE = new WeakMap<FormulaDataModel, Map<string,
// Check if the cell is a nested SUBTOTAL or AGGREGATE result
function isNestedAggregateOrSubtotal(
- cellData: ObjectMatrix<ICellData>,
+ cellData: Nullable<ObjectMatrix<ICellData>>,
rowIndex: number,
columnIndex: number,
sheetId: string,
unitId: string,
formulaDataModel: FormulaDataModel
): boolean {
+ if (!cellData) {
+ return false;
+ }
+
const cellValue = cellData.getValue(rowIndex, columnIndex);
if (!cellValue?.f && !cellValue?.si) {
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
index 7452adbfcd..377ebd12f7 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
@@ -19,6 +19,7 @@ import type { FormulaDependencyTreeVirtual } from '../../dependency/dependency-t
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ErrorType } from '../../../basics/error-type';
import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
+import { IFeatureCalculationManagerService } from '../../../services/feature-calculation-manager.service';
import { IOtherFormulaManagerService } from '../../../services/other-formula-manager.service';
import { IFormulaRuntimeService } from '../../../services/runtime.service';
import { FormulaDependencyTree } from '../../dependency/dependency-tree';
@@ -297,6 +298,59 @@ describe('Test dependency', () => {
]);
});
+ it('orders a newly registered feature after formulas in its dependency range', async () => {
+ formulaCurrentConfigService.load({
+ formulaData: {
+ [testUnitId]: {
+ [testSheetId]: {
+ 0: {
+ 1: { f: '=A1' },
+ },
+ },
+ },
+ },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [{
+ unitId: testUnitId,
+ sheetId: testSheetId,
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ excludedCell: {},
+ allUnitData: {
+ [testUnitId]: testSheetData,
+ },
+ });
+
+ get(IFeatureCalculationManagerService).register(testUnitId, testSheetId, 'feature-1', {
+ unitId: testUnitId,
+ subUnitId: testSheetId,
+ dependencyRanges: [{
+ unitId: testUnitId,
+ sheetId: testSheetId,
+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 },
+ }],
+ getDirtyData: () => ({
+ runtimeCellData: {},
+ dirtyRanges: {
+ [testUnitId]: {
+ [testSheetId]: [{ startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 }],
+ },
+ },
+ }),
+ });
+
+ const treeList = await formulaDependencyGenerator.generate();
+ const executionOrder = treeList.toReversed().map((tree) => tree.featureId ?? tree.formula);
+
+ expect(executionOrder).toEqual(['=A1', 'feature-1']);
+ });
+
it('ignores a non-reference result while collecting dependency ranges', async () => {
formulaCurrentConfigService.load({
formulaData: {
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
index d4e1fed6e9..7eefde7b05 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
@@ -712,6 +712,11 @@ describe('lexer nodeMaker test', () => {
});
describe('moveFormulaRefOffset', () => {
+ it('preserves escaped quotes and reference-like text while moving cell references', () => {
+ expect(lexerTreeBuilder.moveFormulaRefOffset('=IF(A1="a""b","[@Column]","""quoted""")', 1, 1))
+ .toBe('=IF(B2="a""b","[@Column]","""quoted""")');
+ });
+
it('move all', () => {
const result = lexerTreeBuilder.moveFormulaRefOffset('=sum(A1:B1)', 1, 1, false);
expect(result).toStrictEqual('=sum(B2:C2)');
@@ -992,6 +997,12 @@ describe('lexer nodeMaker test', () => {
expect(JSON.stringify(exprTreeNode)).toStrictEqual('{"value":"SUM(Table1[Column1])+MAX(Table2[ColumnA],Table2[ColumnB])","children":[{"value":"SUM(Table1[Column1])","children":[{"value":"Table1[Column1]","children":[],"startIndex":-1}],"startIndex":0},{"value":"MAX(Table2[ColumnA],Table2[ColumnB])","children":[{"value":"Table2[ColumnA]","children":[],"startIndex":-1},{"value":"Table2[ColumnB]","children":[],"startIndex":-1}],"startIndex":23}],"startIndex":-1}');
});
+ it('keeps missing table references in the expression tree', () => {
+ const exprTreeNode = lexerTreeBuilder.getFormulaExprTree('=SUM(Tout[Quantity])', 'mockUnitId', hasFunction, getDefinedNameName, getTable) || {};
+
+ expect(JSON.stringify(exprTreeNode)).toStrictEqual('{"value":"SUM(Tout[Quantity])","children":[{"value":"Tout[Quantity]","children":[],"startIndex":-1}],"startIndex":0}');
+ });
+
it('builds ExprTree with mixed defined names and table references', () => {
const exprTreeNode = lexerTreeBuilder.getFormulaExprTree('=SUM(defineName1, Table1[Column1]) + OFFSET(Table2[ColumnC], defineName2, 0)', 'mockUnitId', hasFunction, getDefinedNameName, getTable) || {};
diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
index 7f154fbf3c..8b099d6f99 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
@@ -23,7 +23,14 @@ import { AbsoluteRefType, Disposable, isValidRange, MAX_COLUMN_COUNT, MAX_ROW_CO
import { FormulaAstLRU } from '../../basics/cache-lru';
import { ERROR_TYPE_COUNT_ARRAY, ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { isFormulaLexerToken, isTokenCannotBeAtEnd, isTokenCannotPrecedeSuffixToken } from '../../basics/match-token';
-import { isReferenceString, regexTestSingeRange } from '../../basics/regex';
+import {
+ isReferenceString,
+ regexTestReferenceTableAllColumn,
+ regexTestReferenceTableMultipleColumn,
+ regexTestReferenceTableSingleColumn,
+ regexTestReferenceTableTitleOnlyAnyHash,
+ regexTestSingeRange,
+} from '../../basics/regex';
import {
matchToken,
OPERATOR_TOKEN_PRIORITY,
@@ -390,6 +397,11 @@ export class LexerTreeBuilder extends Disposable {
for (let i = 0, len = sequenceNodes.length; i < len; i++) {
const node = sequenceNodes[i];
+ if (typeof node !== 'string' && node.nodeType === sequenceNodeType.STRING) {
+ // The lexer decodes doubled quotes; serializing a formula must escape them again.
+ newSequenceNodes.push({ ...node, token: `"${node.token.slice(1, -1).replace(/"/g, '""')}"` });
+ continue;
+ }
if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
newSequenceNodes.push(node);
continue;
@@ -2485,7 +2497,13 @@ export class LexerTreeBuilder extends Disposable {
private _getTableNameFromStructuredRef(token: string, getTable: (unitId: string, tableName: string) => Nullable<ISuperTable>) {
const { tableName } = splitTableStructuredRef(token);
- if (getTable(this._currentUnitId, tableName)) {
+ const isExplicitStructuredReference = token.includes('[') && (
+ regexTestReferenceTableAllColumn(token)
+ || regexTestReferenceTableSingleColumn(token)
+ || regexTestReferenceTableMultipleColumn(token)
+ || regexTestReferenceTableTitleOnlyAnyHash(token)
+ );
+ if (getTable(this._currentUnitId, tableName) || isExplicitStructuredReference) {
return tableName;
}
return null;
diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts
index bfe37d5f73..8197d25f1b 100644
--- a/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts
+++ b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts
@@ -16,10 +16,13 @@
import type { IFormulaCurrentConfigService } from '../../../services/current-data.service';
import type { IFormulaUnitReferenceResolver } from '../../../services/unit-reference-resolver.service';
+import type { BaseValueObject } from '../../value-object/base-value-object';
import { describe, expect, it, vi } from 'vitest';
+import { ErrorType } from '../../../basics/error-type';
import { ReferenceObjectType } from '../../utils/value-object';
+import { ErrorValueObject } from '../../value-object/base-value-object';
import { BaseAstNode } from '../base-ast-node';
-import { ReferenceNode } from '../reference-node';
+import { ReferenceNode, ReferenceNodeFactory } from '../reference-node';
import { UnionNode } from '../union-node';
describe('ReferenceNode external range loading', () => {
@@ -33,6 +36,7 @@ describe('ReferenceNode external range loading', () => {
getUnitStylesData: () => ({}),
};
const runtime = {
+ markExternalReferenceUnavailable: vi.fn(),
currentUnitId: 'host',
currentSubUnitId: 'host-sheet',
currentRow: 0,
@@ -82,4 +86,78 @@ describe('ReferenceNode external range loading', () => {
token: "'[Sales]Data'!A1:B2",
}));
});
+
+ it('returns REF for a missing local structured table reference', () => {
+ const currentConfig = {
+ getSheetNameMap: () => ({}),
+ getUnitData: () => ({}),
+ getArrayFormulaCellData: () => ({}),
+ getArrayFormulaRange: () => ({}),
+ getUnitStylesData: () => ({}),
+ };
+ const runtime = {
+ markExternalReferenceUnavailable: vi.fn(),
+ currentUnitId: 'host',
+ currentSubUnitId: 'host-sheet',
+ currentRow: 0,
+ currentColumn: 0,
+ getUnitData: () => ({}),
+ getRuntimeArrayFormulaCellData: () => ({}),
+ getUnitArrayFormula: () => ({}),
+ getRuntimeFeatureCellData: () => ({}),
+ };
+ const factory = new ReferenceNodeFactory(
+ currentConfig as never,
+ runtime as never,
+ {} as never,
+ {
+ getTableMap: () => null,
+ getTableOptionMap: () => new Map(),
+ } as never,
+ { resolve: () => ({ unitId: 'host' }) } as IFormulaUnitReferenceResolver,
+ { load: vi.fn() } as never
+ );
+
+ const node = factory.checkAndCreateNodeType('Tout[Quantity]');
+ expect(node).toBeInstanceOf(ReferenceNode);
+ node?.execute();
+ expect((node?.getValue() as BaseValueObject).getValue()).toBe(ErrorType.REF);
+ });
+
+ it('keeps ordinary cell references out of the structured-table path', () => {
+ const currentConfig = {
+ getSheetNameMap: () => ({}),
+ getUnitData: () => ({}),
+ getArrayFormulaCellData: () => ({}),
+ getArrayFormulaRange: () => ({}),
+ getUnitStylesData: () => ({}),
+ };
+ const runtime = {
+ markExternalReferenceUnavailable: vi.fn(),
+ currentUnitId: 'host',
+ currentSubUnitId: 'host-sheet',
+ currentRow: 0,
+ currentColumn: 0,
+ getUnitData: () => ({}),
+ getRuntimeArrayFormulaCellData: () => ({}),
+ getUnitArrayFormula: () => ({}),
+ getRuntimeFeatureCellData: () => ({}),
+ };
+ const factory = new ReferenceNodeFactory(
+ currentConfig as never,
+ runtime as never,
+ {} as never,
+ {
+ getTableMap: () => null,
+ getTableOptionMap: () => new Map(),
+ } as never,
+ { resolve: () => ({ unitId: 'host' }) } as IFormulaUnitReferenceResolver,
+ { load: vi.fn() } as never
+ );
+
+ const node = factory.checkAndCreateNodeType('G2');
+ expect(node).toBeInstanceOf(ReferenceNode);
+ node?.execute();
+ expect(node?.getValue()).not.toBeInstanceOf(ErrorValueObject);
+ });
});
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 f88fd62970..aaecd43d84 100644
--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts
@@ -57,6 +57,7 @@ type ReferenceNodeCurrentConfigService = Pick<
type ReferenceNodeRuntimeService = Pick<
IFormulaRuntimeService,
+ | 'markExternalReferenceUnavailable'
| 'currentColumn'
| 'currentRow'
| 'currentSubUnitId'
@@ -111,6 +112,7 @@ export class ReferenceNode extends BaseAstNode {
hostUnitId: runtimeService.currentUnitId,
qualifier: unitQualifier,
referenceKind: 'table',
+ onUnavailable: () => runtimeService.markExternalReferenceUnavailable(),
});
if (typeof resolution === 'string') {
this.setValue(ErrorValueObject.create(resolution));
@@ -138,6 +140,7 @@ export class ReferenceNode extends BaseAstNode {
hostUnitId: runtimeService.currentUnitId,
qualifier: unitQualifier,
referenceKind: 'a1',
+ onUnavailable: () => runtimeService.markExternalReferenceUnavailable(),
});
if (typeof resolution === 'string') {
this.setValue(ErrorValueObject.create(resolution));
@@ -171,6 +174,7 @@ export class ReferenceNode extends BaseAstNode {
hostUnitId,
qualifier: unitQualifier,
referenceKind,
+ onUnavailable: () => this._runtimeService.markExternalReferenceUnavailable(),
});
if (typeof resolution === 'string') {
this.setValue(ErrorValueObject.create(resolution));
@@ -189,6 +193,9 @@ export class ReferenceNode extends BaseAstNode {
resolution,
});
if (error) {
+ if (error === ErrorType.NA) {
+ this._runtimeService.markExternalReferenceUnavailable();
+ }
this.setValue(ErrorValueObject.create(error));
return AstNodePromiseType.ERROR;
}
@@ -354,25 +361,21 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
}
private _getTableReferenceNode(tokenTrim: string, isPrepareMerge: boolean, isSuperTableDirectly: boolean = false) {
- if (!this._checkTokenIsTableReference(tokenTrim) && !isSuperTableDirectly) {
+ if ((!tokenTrim.includes('[') || !this._checkTokenIsTableReference(tokenTrim)) && !isSuperTableDirectly) {
return;
}
const { unitQualifier, tableName, columnStruct } = splitTableStructuredRef(tokenTrim);
- const tableMap = this._getTableMap();
- const hasLocalTable = Array.from(tableMap?.keys() || []).some((name) => name.toLocaleLowerCase() === tableName.toLocaleLowerCase());
- if (unitQualifier || hasLocalTable) {
- return new ReferenceNode(
- this._currentConfigService,
- this._formulaRuntimeService,
- tokenTrim,
- ReferenceObjectType.COLUMN,
- this._unitReferenceResolver,
- this._superTableService,
- this._externalReferenceDataLoader,
- isPrepareMerge,
- { unitQualifier, tableName, columnStruct }
- );
- }
+ return new ReferenceNode(
+ this._currentConfigService,
+ this._formulaRuntimeService,
+ tokenTrim,
+ ReferenceObjectType.COLUMN,
+ this._unitReferenceResolver,
+ this._superTableService,
+ this._externalReferenceDataLoader,
+ isPrepareMerge,
+ { unitQualifier, tableName, columnStruct }
+ );
}
private _checkTokenIsTableReference(token: string): boolean {
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 6b33d74937..ec86fab4f1 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -281,8 +281,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
this._dependencyTreeCache.set(FDtree.treeId, FDtree);
- const treeCache = this._dependencyManagerService.getFeatureFormulaDependency(params.unitId, params.subUnitId, featureId);
- if (treeCache) {
+ if (treeId != null) {
FDtree.isCache = true;
}
diff --git a/packages/engine-formula/src/engine/reference-object/__tests__/table-reference-object.spec.ts b/packages/engine-formula/src/engine/reference-object/__tests__/table-reference-object.spec.ts
index 26f729ae3b..b5d10accea 100644
--- a/packages/engine-formula/src/engine/reference-object/__tests__/table-reference-object.spec.ts
+++ b/packages/engine-formula/src/engine/reference-object/__tests__/table-reference-object.spec.ts
@@ -117,6 +117,39 @@ describe('TableReferenceObject current row', () => {
});
});
+ it('matches escaped hash characters in table column names', () => {
+ const table = {
+ sheetId: 'sheet',
+ titleMap: new Map([['Account #', 1], ['Unit #', 2]]),
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ };
+
+ expect(new TableReferenceObject(
+ "Table1[Account '#]",
+ table,
+ "[Account '#]",
+ options
+ ).getRangeData()).toEqual({
+ startRow: 1,
+ endRow: 3,
+ startColumn: 1,
+ endColumn: 1,
+ });
+ const currentRow = new TableReferenceObject(
+ "Table1[[#This Row],[Unit '#]]",
+ table,
+ "[[#This Row],[Unit '#]]",
+ options
+ );
+ currentRow.setCurrentRowAndColumn(2, 4);
+ expect(currentRow.getRangeData()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 2,
+ });
+ });
+
it('treats commas inside single-bracket column titles as title text', () => {
const reference = new TableReferenceObject('Table1[Deposit,\r\nCredit (+)]', {
sheetId: 'sheet',
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 a8889d177f..6bfc43a78a 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
@@ -349,7 +349,7 @@ export class TableReferenceObject extends BaseReferenceObject {
/** 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 key = this._unescapeColumnName(name.trim());
const hit = titleMap.get(key);
if (hit !== undefined) return hit;
@@ -367,6 +367,10 @@ export class TableReferenceObject extends BaseReferenceObject {
return -1;
}
+ private _unescapeColumnName(name: string): string {
+ return name.replace(/'(['#\[\]@])/g, '$1');
+ }
+
/** Resolve #This Row's row number; takes first data row (tableStartRow+1) when no context available */
private _resolveThisRow(dataStartRow: number, dataEndRow: number): number {
this._isCurrentRowForRange = true;
diff --git a/packages/engine-formula/src/engine/utils/reference.ts b/packages/engine-formula/src/engine/utils/reference.ts
index 33466ad333..3c08878a89 100644
--- a/packages/engine-formula/src/engine/utils/reference.ts
+++ b/packages/engine-formula/src/engine/utils/reference.ts
@@ -210,6 +210,10 @@ export function handleRefStringInfo(refString: string) {
if (unitIdMatch != null) {
unitQualifier = unitIdMatch[0].trim();
unitQualifier = unquoteSheetName(unitQualifier.slice(1, unitQualifier.length - 1));
+ const pathPrefix = refString.slice(0, unitIdMatch.index);
+ if (pathPrefix.startsWith("'") && /[\\/]$/.test(pathPrefix)) {
+ refString = `'${refString.slice(unitIdMatch.index)}`;
+ }
refString = refString.replace(UNIT_NAME_REGEX_PRECOMPILING, '');
}
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts
index 4066416339..2ec106f359 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts
@@ -33,6 +33,18 @@ describe('StringValueObject', () => {
expect(date1900Value.convertToNumberObjectValue().getValue()).toBe(1462);
expect(date1904Value.convertToNumberObjectValue().getValue()).toBe(0);
expect(date1900Value.convertToNumberObjectValue().getValue()).toBe(1462);
+ expect(
+ StringValueObject.create('March 2025')
+ .withDateSystem(DateSystem.Date1904)
+ .convertToNumberObjectValue()
+ .getValue()
+ ).toBe(44255);
+ expect(
+ StringValueObject.create('April2024')
+ .withDateSystem(DateSystem.Date1904)
+ .convertToNumberObjectValue()
+ .getValue()
+ ).toBe(43921);
});
it('does not reuse a hyperlink object as a plain string', () => {
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index 1d0a47e423..8b9b651725 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DateSystem, getNumfmtParseValueFilter, isRealNum, numfmt, Tools } from '@univerjs/core';
+import { DateSystem, excelDateSerial, getNumfmtParseValueFilter, isRealNum, numfmt, Tools } from '@univerjs/core';
import { FormulaAstLRU } from '../../basics/cache-lru';
import { reverseCompareOperator } from '../../basics/calculate';
import { BooleanValue, ConcatenateType } from '../../basics/common';
@@ -29,6 +29,45 @@ export type PrimitiveValueType = string | boolean | number | null;
export type FormulaFunctionValueType = PrimitiveValueType | PrimitiveValueType[][] | BaseValueObject;
export type FormulaFunctionResultValueType = PrimitiveValueType | PrimitiveValueType[][];
+function parseCompactEnglishMonthYear(rawValue: string, dateSystem: DateSystem): number | null {
+ const match = rawValue.trim().match(/^([A-Za-z]{3,9})(\d{4})$/);
+ if (!match) {
+ return null;
+ }
+ const months: Record<string, number> = {
+ jan: 0,
+ january: 0,
+ feb: 1,
+ february: 1,
+ mar: 2,
+ march: 2,
+ apr: 3,
+ april: 3,
+ may: 4,
+ jun: 5,
+ june: 5,
+ jul: 6,
+ july: 6,
+ aug: 7,
+ august: 7,
+ sep: 8,
+ sept: 8,
+ september: 8,
+ oct: 9,
+ october: 9,
+ nov: 10,
+ november: 10,
+ dec: 11,
+ december: 11,
+ };
+ const month = months[match[1].toLowerCase()];
+ const year = Number(match[2]);
+ if (month === undefined || year < 1900 || year > 9999) {
+ return null;
+ }
+ return excelDateSerial(new Date(Date.UTC(year, month, 1)), dateSystem);
+}
+
export class NullValueObject extends BaseValueObject {
private static _instance: NullValueObject;
@@ -1587,6 +1626,11 @@ export class StringValueObject extends BaseValueObject {
return createNumberValueObjectByRawValue(parseData.v, parseData.z).withDateSystem(this.getDateSystem());
}
+ const compactMonthYear = parseCompactEnglishMonthYear(rawValue, this.getDateSystem());
+ if (compactMonthYear !== null) {
+ return createNumberValueObjectByRawValue(compactMonthYear).withDateSystem(this.getDateSystem());
+ }
+
return createNumberValueObjectByRawValue(rawValue).withDateSystem(this.getDateSystem());
}
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index fd001acfba..125d5606c5 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -633,7 +633,7 @@ export class BaseFunction {
createReferenceObject(reference: BaseReferenceObject, range: IRange) {
const unitId = reference.getForcedUnitId() || reference.getDefaultUnitId() || '';
- const sheetId = reference.getForcedSheetId() || reference.getDefaultUnitId() || '';
+ const sheetId = reference.getForcedSheetId() || reference.getDefaultSheetId() || '';
const sheetName = reference.getForcedSheetName();
const gridRangeName = {
diff --git a/packages/engine-formula/src/functions/engineering/convert/__tests__/index.spec.ts b/packages/engine-formula/src/functions/engineering/convert/__tests__/index.spec.ts
index ce863ef229..3838006a9e 100644
--- a/packages/engine-formula/src/functions/engineering/convert/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/engineering/convert/__tests__/index.spec.ts
@@ -131,7 +131,7 @@ describe('Test convert function', () => {
toUnit = StringValueObject.create('Rank');
result = testFunction.calculate(number, fromUnit, toUnit);
- expect(getObjectValue(result)).toStrictEqual(491.67);
+ expect(getObjectValue(result)).toBeCloseTo(491.67, 12);
toUnit = StringValueObject.create('Reau');
result = testFunction.calculate(number, fromUnit, toUnit);
@@ -145,13 +145,20 @@ describe('Test convert function', () => {
let result = testFunction.calculate(number, fromUnit, toUnit);
expect(getObjectValue(result)).toStrictEqual(0);
+ const precise = testFunction.calculate(
+ NumberValueObject.create(4),
+ fromUnit,
+ StringValueObject.create('C')
+ );
+ expect(getObjectValue(precise)).toBeCloseTo(-15.555555555555555, 12);
+
toUnit = StringValueObject.create('K');
result = testFunction.calculate(number, fromUnit, toUnit);
expect(getObjectValue(result)).toStrictEqual(273.15);
toUnit = StringValueObject.create('Rank');
result = testFunction.calculate(number, fromUnit, toUnit);
- expect(getObjectValue(result)).toStrictEqual(491.67);
+ expect(getObjectValue(result)).toBeCloseTo(491.67, 12);
toUnit = StringValueObject.create('Reau');
result = testFunction.calculate(number, fromUnit, toUnit);
@@ -171,7 +178,7 @@ describe('Test convert function', () => {
toUnit = StringValueObject.create('Rank');
result = testFunction.calculate(number, fromUnit, toUnit);
- expect(getObjectValue(result)).toStrictEqual(491.67);
+ expect(getObjectValue(result)).toBeCloseTo(491.67, 12);
toUnit = StringValueObject.create('Reau');
result = testFunction.calculate(number, fromUnit, toUnit);
diff --git a/packages/engine-formula/src/functions/engineering/convert/index.ts b/packages/engine-formula/src/functions/engineering/convert/index.ts
index acf25dd363..88490ec1a0 100644
--- a/packages/engine-formula/src/functions/engineering/convert/index.ts
+++ b/packages/engine-formula/src/functions/engineering/convert/index.ts
@@ -106,7 +106,6 @@ export class Convert extends BaseFunction {
if (from[3] === 'temperature') {
result = this._getTemperatureConversion(numberValue, from[1] as string, to[1] as string);
- result = +result.toFixed(2);
} else {
result = (numberValue * (from[6] as number) * fromMultiplier) / ((to[6] as number) * toMultiplier);
}
diff --git a/packages/engine-formula/src/functions/financial/irr/__tests__/index.spec.ts b/packages/engine-formula/src/functions/financial/irr/__tests__/index.spec.ts
index 7461306531..94113cf6e2 100644
--- a/packages/engine-formula/src/functions/financial/irr/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/financial/irr/__tests__/index.spec.ts
@@ -34,6 +34,25 @@ describe('Test irr function', () => {
expect(getObjectValue(result, true)).toBe(0.0866309480365);
});
+ it('handles long cashflows when low bracket rates overflow', () => {
+ const cashflows = [
+ -149150,
+ ...Array.from({ length: 24 }, () => 250),
+ ...Array.from({ length: 276 }, () => 832.1256634329588),
+ ];
+ const values = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([cashflows]),
+ rowCount: 1,
+ columnCount: cashflows.length,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ expect(getObjectValue(testFunction.calculate(values), true)).toBe(0.00308889248291);
+ });
+
it('Value is normal, but no positive and negative number', () => {
const values = ArrayValueObject.create('{700000,120000,150000,180000,210000,260000}');
const guess = NumberValueObject.create(0.1);
diff --git a/packages/engine-formula/src/functions/information/cell/__tests__/index.spec.ts b/packages/engine-formula/src/functions/information/cell/__tests__/index.spec.ts
index 6f7d5f9342..b3446c6e04 100644
--- a/packages/engine-formula/src/functions/information/cell/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/information/cell/__tests__/index.spec.ts
@@ -50,6 +50,7 @@ const getTestWorkbookData = (): IWorkbookData => {
1: {
v: 2,
t: CellValueType.NUMBER,
+ s: 'date-style',
},
},
1: {
@@ -150,7 +151,11 @@ const getTestWorkbookData = (): IWorkbookData => {
locale: LocaleType.ZH_CN,
name: '',
sheetOrder: ['sheet1', 'sheet2'],
- styles: {},
+ styles: {
+ 'date-style': {
+ n: { pattern: 'yyyy-mm-dd' },
+ },
+ },
};
};
@@ -240,6 +245,9 @@ describe('Test cell function', () => {
result = await calculate('=Cell("width", D3)');
expect(result).toStrictEqual([[88, true]]);
+ result = await calculate('=Cell("format", B1)');
+ expect(result).toBe('D4');
+
result = await calculate('=Cell("address", \'Startup Costs\'!B2)');
expect(result).toBe("'Startup Costs'!$B$2");
});
diff --git a/packages/engine-formula/src/functions/information/cell/index.ts b/packages/engine-formula/src/functions/information/cell/index.ts
index 408052b0b2..b9dc201da0 100644
--- a/packages/engine-formula/src/functions/information/cell/index.ts
+++ b/packages/engine-formula/src/functions/information/cell/index.ts
@@ -80,7 +80,14 @@ export class Cell extends BaseFunction {
const { columnData, defaultColumnWidth } = currentActiveSheetData;
const forcedSheetName = (_reference as BaseReferenceObject).getForcedSheetName();
- _reference = (_reference as BaseReferenceObject).toArrayValueObject();
+ const referenceObject = _reference as BaseReferenceObject;
+ const cellData = referenceObject.getCellData(
+ referenceObject.getRangePosition().startRow,
+ referenceObject.getRangePosition().startColumn
+ );
+ const numberFormat = referenceObject.getCurrentStylesData()?.getStyleByCell(cellData)?.n?.pattern;
+
+ _reference = referenceObject.toArrayValueObject();
const _currentRow = (_reference as ArrayValueObject).getCurrentRow();
const _currentColumn = (_reference as ArrayValueObject).getCurrentColumn();
@@ -107,8 +114,7 @@ export class Cell extends BaseFunction {
// This value is not supported in Excel for the web. google sheet return #VALUE!.
return ErrorValueObject.create(ErrorType.VALUE);
case 'format':
- // This value is not supported in Excel for the web. google sheet return G.
- return StringValueObject.create('G');
+ return StringValueObject.create(getCellFormatCode(numberFormat));
case 'parentheses':
// This value is not supported in Excel for the web. return 0.
return NumberValueObject.create(0);
@@ -155,3 +161,29 @@ export class Cell extends BaseFunction {
return ArrayValueObject.createByArray(resultArray);
}
}
+
+function getCellFormatCode(pattern?: string): string {
+ if (!pattern || /^general$/iu.test(pattern.trim())) return 'G';
+
+ const normalized = pattern
+ .split(';')[0]
+ .replace(/"[^"]*"/gu, '')
+ .replace(/\\./gu, '')
+ .replace(/_.|\*./gu, '')
+ .toLocaleLowerCase();
+ const hasDate = /[yd]/u.test(normalized);
+ const hasTime = /h|s/u.test(normalized);
+
+ if (hasDate) return 'D4';
+ if (hasTime) return /s/u.test(normalized) ? 'D8' : 'D9';
+ if (/%/u.test(normalized)) return `P${decimalPlaces(normalized)}`;
+ if (/[eE][+-]?0+/u.test(normalized)) return `S${decimalPlaces(normalized)}`;
+ if (/[$£¥€]/u.test(normalized)) return `C${decimalPlaces(normalized)}`;
+ if (/,/u.test(normalized)) return `,${decimalPlaces(normalized)}`;
+ if (/[0#?]/u.test(normalized)) return `F${decimalPlaces(normalized)}`;
+ return 'G';
+}
+
+function decimalPlaces(pattern: string): number {
+ return pattern.match(/\.([0#?]+)/u)?.[1]?.length ?? 0;
+}
diff --git a/packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts b/packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts
index d658d35893..30901bd0d8 100644
--- a/packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts
@@ -23,8 +23,13 @@ import { Lexer } from '../../../../engine/analysis/lexer';
import { AstTreeBuilder } from '../../../../engine/analysis/parser';
import { Interpreter } from '../../../../engine/interpreter/interpreter';
import { generateExecuteAstNodeData } from '../../../../engine/utils/ast-node-tool';
+import { IFormulaCurrentConfigService } from '../../../../services/current-data.service';
import { IFunctionService } from '../../../../services/function.service';
+import { IFormulaRuntimeService } from '../../../../services/runtime.service';
+import { ISheetRowFilteredService } from '../../../../services/sheet-row-filtered.service';
import { createFunctionTestBed } from '../../../__tests__/create-function-test-bed';
+import { FUNCTION_NAMES_MATH } from '../../../math/function-names';
+import { Subtotal } from '../../../math/subtotal';
import { FUNCTION_NAMES_META } from '../../../meta/function-names';
import { Multiply } from '../../../meta/multiply';
import { getObjectValue } from '../../../util';
@@ -38,9 +43,10 @@ describe('Test byrow', () => {
let lexer: Lexer;
let astTreeBuilder: AstTreeBuilder;
let interpreter: Interpreter;
+ let testBed: ReturnType<typeof createFunctionTestBed>;
beforeEach(() => {
- const testBed = createFunctionTestBed();
+ testBed = createFunctionTestBed();
get = testBed.get;
@@ -53,7 +59,8 @@ describe('Test byrow', () => {
functionService.registerExecutors(
new Byrow(FUNCTION_NAMES_LOGICAL.BYROW),
new Lambda(FUNCTION_NAMES_LOGICAL.LAMBDA),
- new Multiply(FUNCTION_NAMES_META.MULTIPLY)
+ new Multiply(FUNCTION_NAMES_META.MULTIPLY),
+ new Subtotal(FUNCTION_NAMES_MATH.SUBTOTAL)
);
});
@@ -95,5 +102,51 @@ describe('Test byrow', () => {
result = await interpreter.executeAsync(generateExecuteAstNodeData(astNode as BaseAstNode));
expect(getObjectValue(result)).toStrictEqual(ErrorType.VALUE);
});
+
+ it('keeps row references so SUBTOTAL can observe filtered rows', async () => {
+ get(ISheetRowFilteredService).register((_unitId, _sheetId, row) => row === 1);
+ get(IFormulaCurrentConfigService).load({
+ formulaData: {},
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ excludedCell: {},
+ allUnitData: { [testBed.unitId]: testBed.sheetData },
+ dirtyUnitOtherFormulaMap: {},
+ });
+ const sheetItem = testBed.sheetData[testBed.sheetId];
+ get(IFormulaRuntimeService).setCurrent(
+ 0,
+ 0,
+ sheetItem.rowCount,
+ sheetItem.columnCount,
+ testBed.sheetId,
+ testBed.unitId
+ );
+
+ const lexerNode = lexer.treeBuilder('=BYROW(A1:A3,LAMBDA(x,SUBTOTAL(3,x)))');
+ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+ const result = await interpreter.executeAsync(generateExecuteAstNodeData(astNode as BaseAstNode));
+
+ expect(getObjectValue(result)).toStrictEqual([
+ [1],
+ [0],
+ [1],
+ ]);
+
+ const multiColumnLexerNode = lexer.treeBuilder('=BYROW(A1:B3,LAMBDA(x,SUBTOTAL(3,x)))');
+ const multiColumnAstNode = astTreeBuilder.parse(multiColumnLexerNode as LexerNode);
+ const multiColumnResult = await interpreter.executeAsync(generateExecuteAstNodeData(multiColumnAstNode as BaseAstNode));
+
+ expect(getObjectValue(multiColumnResult)).toStrictEqual([
+ [2],
+ [0],
+ [2],
+ ]);
+ });
});
});
diff --git a/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts
index 89619f3d3a..b023e00a07 100644
--- a/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts
@@ -17,6 +17,7 @@
import { describe, expect, it } from 'vitest';
import { ErrorType } from '../../../../basics/error-type';
import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { StringValueObject } from '../../../../engine/value-object/primitive-object';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
import { ImageFunction } from '../index';
@@ -51,6 +52,14 @@ describe('ImageFunction', () => {
});
});
+ it('should propagate scalar optional argument errors', () => {
+ const result = fn.calculate(
+ StringValueObject.create('https://image'),
+ ErrorValueObject.create(ErrorType.REF)
+ );
+ expect(result.getValue()).toBe(ErrorType.REF);
+ });
+
it('should validate sizing and size constraints', () => {
const source = StringValueObject.create('https://image');
diff --git a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
index 89747e2d4d..0188ec40eb 100644
--- a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
@@ -627,8 +627,7 @@ describe('Test index', () => {
// null
let result = await calculate('=INDEX(A6:B7,2)');
- // reference Google Sheets
- expect(result).toStrictEqual([['Alex', 'Mickey']]);
+ expect(result).toBe(ErrorType.REF);
// blank cell
result = await calculate('=INDEX(A6:B7,2,)');
@@ -692,8 +691,7 @@ describe('Test index', () => {
// null
let result = await calculate('=INDEX(A6:B7,A3:A5)');
- // reference Google Sheets
- expect(result).toStrictEqual([['Tom'], ['Tom'], ['Tom']]);
+ expect(result).toStrictEqual([[ErrorType.REF], ['Tom'], ['Tom']]);
// blank cell
result = await calculate('=INDEX(A6:B7,A3:A5,)');
@@ -742,6 +740,10 @@ describe('Test index', () => {
});
describe('Reference is Array', () => {
+ it('returns a whole row when column number is omitted', async () => {
+ expect(await calculate('=INDEX({1,2,3;4,5,6},2)')).toStrictEqual([[4, 5, 6]]);
+ });
+
it('Row number 1, column number 1', async () => {
// number
let result = await calculate('=INDEX({1,2;3,4},0,2)');
diff --git a/packages/engine-formula/src/functions/lookup/index/index.ts b/packages/engine-formula/src/functions/lookup/index/index.ts
index 51840b3cf2..0d1bdaf95a 100644
--- a/packages/engine-formula/src/functions/lookup/index/index.ts
+++ b/packages/engine-formula/src/functions/lookup/index/index.ts
@@ -198,6 +198,16 @@ export class Index extends BaseFunction {
_reference = (reference as CubeValueObject).getCubeValues()[areaNumValue - 1];
}
+ if (
+ !columnNum &&
+ rowNumValue > 0 &&
+ referenceRowColumnCount.rowCount > 1 &&
+ referenceRowColumnCount.columnCount > 1 &&
+ _reference.isReferenceObject()
+ ) {
+ return ErrorValueObject.create(ErrorType.REF);
+ }
+
if (_reference.isReferenceObject()) {
return this._calculateReferenceObject(_reference as BaseReferenceObject, rowNumValue, columnNumValue);
}
diff --git a/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts
index d8cc08be18..b2e490f7f2 100644
--- a/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/xlookup/__tests__/index.spec.ts
@@ -120,6 +120,25 @@ describe('Test xlookup', () => {
expect(getObjectValue(resultObject)).toBe(0);
});
+ it('Blank lookup value should match a blank cell', () => {
+ const lookupArray = ArrayValueObject.createByArray([
+ [null],
+ ['key'],
+ ]);
+ const returnArray = ArrayValueObject.createByArray([
+ ['blank-match'],
+ ['key-match'],
+ ]);
+
+ const resultObject = testFunction.calculate(
+ NullValueObject.create(),
+ lookupArray,
+ returnArray
+ ) as BaseValueObject;
+
+ expect(getObjectValue(resultObject)).toBe('blank-match');
+ });
+
it('keeps blank, numeric zero, text zero, and empty text distinct', () => {
const lookupArray = ArrayValueObject.create({
calculateValueList: [
diff --git a/packages/engine-formula/src/functions/math/minverse/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/minverse/__tests__/index.spec.ts
index 094f7c467c..6acb0b202c 100644
--- a/packages/engine-formula/src/functions/math/minverse/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/minverse/__tests__/index.spec.ts
@@ -71,6 +71,46 @@ describe('Test minverse function', () => {
]);
});
+ it('Returns Excel-compatible values for non-zero floating-point pivots', () => {
+ const values = [
+ [0, 90, 161, 235, 307, 380, 452, 525],
+ [-90, 0, 71, 145, 217, 290, 362, 435],
+ [-161, -71, 0, 74, 146, 219, 291, 364],
+ [-235, -145, -74, 0, 72, 145, 217, 290],
+ [-307, -217, -146, -72, 0, 73, 145, 218],
+ [-380, -290, -219, -145, -73, 0, 72, 145],
+ [-452, -362, -291, -217, -145, -72, 0, 73],
+ [-525, -435, -364, -290, -218, -145, -73, 0],
+ ];
+ const array = ArrayValueObject.create({
+ calculateValueList: transformToValueObject(values),
+ rowCount: values.length,
+ columnCount: values[0].length,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ const result = getObjectValue(testFunction.calculate(array)) as number[][];
+ const expectedFirstRow = [
+ 20_312_366_176_490.105,
+ 3_127_499_741_229.562,
+ -30_395_388_110_074.422,
+ 32_643_278_549_083.152,
+ -51_212_808_262_633.188,
+ 4_691_249_611_844.3125,
+ 781_874_935_307.3981,
+ 20_051_927_358_753.352,
+ ];
+
+ expect(result).toHaveLength(8);
+ expect(result[0]).toHaveLength(8);
+ result[0].forEach((value, index) => {
+ expect(Math.abs((value - expectedFirstRow[index]) / expectedFirstRow[index])).toBeLessThan(1e-12);
+ });
+ });
+
it('ArrayRowCount !== arrayColumnCount', () => {
const array = ArrayValueObject.create({
calculateValueList: transformToValueObject([
diff --git a/packages/engine-formula/src/functions/math/randarray/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/randarray/__tests__/index.spec.ts
index 32adde058c..63b85dac00 100644
--- a/packages/engine-formula/src/functions/math/randarray/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/randarray/__tests__/index.spec.ts
@@ -221,6 +221,11 @@ describe('Test randarray function', () => {
]);
});
+ it('explicit implicit intersection keeps a legacy scalar formula from spilling', async () => {
+ const result = await calculate('=@RANDARRAY(10,1,1,1,TRUE)');
+ expect(result).toBe(1);
+ });
+
it('rows and columns is exceed', async () => {
const result = await calculate('=RANDARRAY(10000,10000)');
expect(result).toBe(ErrorType.VALUE);
diff --git a/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts
index d9b9b80fe0..e1f988fb7f 100644
--- a/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts
@@ -244,13 +244,16 @@ describe('Test sumif function', () => {
const error = ErrorValueObject.create(ErrorType.NAME);
const result = await calculate(`=SUMIF(${error},A1:A4)`);
- expect(result).toBe(ErrorType.VALUE);
+ expect(result).toBe(ErrorType.NAME);
const result2 = await calculate(`=SUMIF(A1:A4,${error})`);
expect(result2).toBe(0);
const result3 = await calculate(`=SUMIF(A1:A4,">40",${error})`);
- expect(result3).toBe(ErrorType.VALUE);
+ expect(result3).toBe(ErrorType.NAME);
+
+ const result4 = await calculate('=SUMIF(#REF!,A1:A4,#REF!)');
+ expect(result4).toBe(ErrorType.REF);
});
it('Range or sumRange is not referenceObject', async () => {
diff --git a/packages/engine-formula/src/functions/math/sumif/index.ts b/packages/engine-formula/src/functions/math/sumif/index.ts
index dcb085334d..bda471d2b7 100644
--- a/packages/engine-formula/src/functions/math/sumif/index.ts
+++ b/packages/engine-formula/src/functions/math/sumif/index.ts
@@ -31,6 +31,12 @@ export class Sumif extends BaseFunction {
override needsReferenceObject = true;
override calculate(range: FunctionVariantType, criteria: FunctionVariantType, sumRange?: FunctionVariantType): BaseValueObject {
+ if (range.isError()) {
+ return range as BaseValueObject;
+ }
+ if (sumRange?.isError()) {
+ return sumRange as BaseValueObject;
+ }
if (!range.isReferenceObject() || (sumRange && !sumRange.isReferenceObject())) {
return ErrorValueObject.create(ErrorType.VALUE);
}
diff --git a/packages/engine-formula/src/functions/math/sumproduct/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/sumproduct/__tests__/index.spec.ts
index bbcb16bb94..6ceced651b 100644
--- a/packages/engine-formula/src/functions/math/sumproduct/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/sumproduct/__tests__/index.spec.ts
@@ -134,6 +134,15 @@ describe('Test sumproduct function', () => {
});
describe('Sumproduct', () => {
+ it.each([
+ '=SUMPRODUCT({1;2},{1;2;3})',
+ '=SUMPRODUCT({1;2;3},{1;2})',
+ '=SUMPRODUCT({1,2},{1,2,3})',
+ '=SUMPRODUCT({1,2,3},{1,2})',
+ ])('rejects different dimensions: %s', (formula) => {
+ expect(calculate(formula)).toBe(ErrorType.VALUE);
+ });
+
it('Array1 is array, not includes error', () => {
const array1 = ArrayValueObject.create({
calculateValueList: [
diff --git a/packages/engine-formula/src/functions/math/sumproduct/index.ts b/packages/engine-formula/src/functions/math/sumproduct/index.ts
index d42ff6a402..56e0f048d9 100644
--- a/packages/engine-formula/src/functions/math/sumproduct/index.ts
+++ b/packages/engine-formula/src/functions/math/sumproduct/index.ts
@@ -84,9 +84,7 @@ export class Sumproduct extends BaseFunction {
const variantRowCount = arr.getRowCount();
const variantColumnCount = arr.getColumnCount();
- // Keep original rule:
- // only when BOTH row and column mismatch => #VALUE!
- if (variantRowCount !== rowCount && variantColumnCount !== columnCount) {
+ if (variantRowCount !== rowCount || variantColumnCount !== columnCount) {
return ErrorValueObject.create(ErrorType.VALUE);
}
}
diff --git a/packages/engine-formula/src/functions/statistical/forecast/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/forecast/__tests__/index.spec.ts
index 0393f29bfb..adfbc683a6 100644
--- a/packages/engine-formula/src/functions/statistical/forecast/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/forecast/__tests__/index.spec.ts
@@ -59,6 +59,30 @@ describe('Test forecast function', () => {
expect(getObjectValue(result, true)).toBe(29.9520353143);
});
+ it('accepts equally sized row and column ranges', () => {
+ const x = NumberValueObject.create(2.5);
+ const knownYs = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([[1, 3]]),
+ rowCount: 1,
+ columnCount: 2,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const knownXs = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([[1], [3]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ expect(getObjectValue(testFunction.calculate(x, knownYs, knownXs))).toBe(2.5);
+ });
+
it('X value is array', () => {
const x = ArrayValueObject.create({
calculateValueList: transformToValueObject([
diff --git a/packages/engine-formula/src/functions/statistical/growth/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/growth/__tests__/index.spec.ts
index feae0fb56f..bfe80c7892 100644
--- a/packages/engine-formula/src/functions/statistical/growth/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/growth/__tests__/index.spec.ts
@@ -581,7 +581,7 @@ describe('Test growth function', () => {
[27.2459520893],
[43.0060060724],
[67.8822509939],
- [107.147824707258],
+ [expect.closeTo(107.147824707258, 9)],
]);
const knownYs3 = ArrayValueObject.create({
diff --git a/packages/engine-formula/src/functions/statistical/linest/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/linest/__tests__/index.spec.ts
index 3f58db373e..786a03577c 100644
--- a/packages/engine-formula/src/functions/statistical/linest/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/linest/__tests__/index.spec.ts
@@ -147,17 +147,17 @@ describe('Test linest function', () => {
const stats = BooleanValueObject.create(true);
const result = testFunction.calculate(knownYs, knownXs, constb, stats);
expect(getObjectValue(result, true)).toStrictEqual([
- [204.080843005, -3407.54648312088, 12743.5528364893, -127.712022706619, 303849.43123395],
- [651.098478042223, 27243.5182021205, 20457.1543147678, 281.254697108, 634296.647114014],
+ [204.080843005, -3407.54648311873, 12743.5528364872, -127.712022706613, 303849.431233932],
+ [651.098478042223, 27243.5182021205, 20457.1543147677, 281.254697108, 634296.647114014],
[0.107464822024, 49689.6546787527, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[0.180606027654, 6, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [1783709761.98331, 14814370692.5621, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [1783709761.98333, 14814370692.5621, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
const constb2 = BooleanValueObject.create(false);
const result2 = testFunction.calculate(knownYs, knownXs, constb2, stats);
expect(getObjectValue(result2, true)).toStrictEqual([
- [104.931508746584, -10969.5506756924, 12875.3758749945, 6.2539663735, 0],
+ [104.931508746583, -10969.5506756927, 12875.3758749944, 6.2539663735, 0],
[582.358051352254, 20946.2250961889, 19296.6787389021, 28.2242490263, ErrorType.NA],
[0.378600130052, 46875.144599683, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[1.06622202487, 7, ErrorType.NA, ErrorType.NA, ErrorType.NA],
@@ -167,7 +167,7 @@ describe('Test linest function', () => {
const stats2 = BooleanValueObject.create(false);
const result3 = testFunction.calculate(knownYs, knownXs, constb, stats2);
expect(getObjectValue(result3, true)).toStrictEqual([
- [204.080843005, -3407.54648312088, 12743.5528364893, -127.712022706619, 303849.43123395],
+ [204.080843005, -3407.54648311873, 12743.5528364872, -127.712022706613, 303849.431233932],
]);
});
@@ -201,24 +201,76 @@ describe('Test linest function', () => {
const stats = BooleanValueObject.create(true);
const result = testFunction.calculate(knownYs, knownXs, constb, stats);
expect(getObjectValue(result, true)).toStrictEqual([
- [0.25951909813, 0.000629921633028, 0.172592800629, 0.548068078609, -0.134842435655],
+ [0.259519098763, 0.000629921769464, 0.172592784662, 0.548068059432, -0.134842435684],
[0, 0, 0, 0, 0],
[1, 0, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[ErrorType.NUM, 0, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [152301876.8, 2.44622825105e-7, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [152301876.8, 2.64699020724e-23, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
const constb2 = BooleanValueObject.create(false);
const result2 = testFunction.calculate(knownYs, knownXs, constb2, stats);
expect(getObjectValue(result2, true)).toStrictEqual([
- [0.254604257643, 0.000585979549214, 0.176345787942, 0.549325160682, 0],
- [0.0772515444895, 0.00105259139493, 0.127125044698, 0.0480042261908, ErrorType.NA],
- [0.999999999828, 0.18882049421, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [1451318743.33408, 1, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [206976507.964347, 0.0356531790337, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [0.254604259712, 0.000585979662783, 0.176345792867, 0.549325164445, 0],
+ [0.0772515108466, 0.00105259093653, 0.127124989335, 0.0480042052851, ErrorType.NA],
+ [0.999999999828, 0.188820411979, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [1451320007.4257, 1, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [206976507.964347, 0.03565314798, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
});
+ it('Keeps high-order polynomial coefficients stable', () => {
+ const xValues = [155, 178, 195, 205, 189, 179, 142, 130, 152, 166, 194];
+ const yValues = [
+ 975097,
+ 1076088.07,
+ 985880.56,
+ 1264998.15,
+ 1487692.02,
+ 879096.99,
+ 1013152.71,
+ 480886.67,
+ 651359.67,
+ 472135.74,
+ 720614.91,
+ ];
+ const knownYs = ArrayValueObject.create({
+ calculateValueList: transformToValueObject(yValues.map((value) => [value])),
+ rowCount: yValues.length,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const knownXs = ArrayValueObject.create({
+ calculateValueList: transformToValueObject(
+ xValues.map((value) => Array.from({ length: 6 }, (_, index) => value ** (index + 1)))
+ ),
+ rowCount: xValues.length,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = getObjectValue(testFunction.calculate(knownYs, knownXs)) as number[][];
+ const expected = [
+ 0.003030803284094725,
+ -3.014286876228756,
+ 1242.0301184586228,
+ -271378.1017228177,
+ 33159765.83632094,
+ -2148345015.0620275,
+ 57656015344.78786,
+ ];
+
+ result[0].forEach((actual, index) => {
+ const relativeError = Math.abs(actual - expected[index]) / Math.max(Math.abs(expected[index]), 1);
+ expect(relativeError).toBeLessThan(1e-8);
+ });
+ });
+
it('Stats value test', () => {
const knownYs = ArrayValueObject.create({
calculateValueList: transformToValueObject([
diff --git a/packages/engine-formula/src/functions/statistical/logest/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/logest/__tests__/index.spec.ts
index 6d0b487dfa..093e538355 100644
--- a/packages/engine-formula/src/functions/statistical/logest/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/logest/__tests__/index.spec.ts
@@ -100,6 +100,7 @@ describe('Test logest function', () => {
]);
});
+ // Coefficients verified using 80-digit QR least squares on log(knownYs).
it('KnownYs is one column, and knownXs is multiple columns', () => {
const knownYs = ArrayValueObject.create({
calculateValueList: transformToValueObject([
@@ -147,7 +148,7 @@ describe('Test logest function', () => {
const stats = BooleanValueObject.create(true);
const result = testFunction.calculate(knownYs, knownXs, constb, stats);
expect(getObjectValue(result, true)).toStrictEqual([
- [1.00225626311, 0.955992743217, 1.32201735202, 0.997967326319, 1251594.75697854],
+ [1.00225626311, 0.955992743218, 1.32201735202, 0.997967326319, expect.closeTo(1251594.756974595, 6)],
[0.0111189448553, 0.465243257003, 0.349351101858, 0.00480304527334, 10.8320164753],
[0.123427911828, 0.848560623139, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[0.211211228649, 6, ErrorType.NA, ErrorType.NA, ErrorType.NA],
@@ -160,14 +161,14 @@ describe('Test logest function', () => {
[0.997675048746, 0.67406990963, 1.33009450491, 1.00416405143, 1],
[0.0110423660294, 0.397171265872, 0.365893438396, 0.000535173314646, ErrorType.NA],
[0.994809235519, 0.888821753471, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [335.387237981475, 7, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [expect.closeTo(335.387237981475, 9), 7, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[1059.82918504031, 5.5300287661, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
const stats2 = BooleanValueObject.create(false);
const result3 = testFunction.calculate(knownYs, knownXs, constb, stats2);
expect(getObjectValue(result3, true)).toStrictEqual([
- [1.00225626311, 0.955992743217, 1.32201735202, 0.997967326319, 1251594.75697854],
+ [1.00225626311, 0.955992743218, 1.32201735202, 0.997967326319, expect.closeTo(1251594.756974595, 6)],
]);
});
@@ -201,7 +202,7 @@ describe('Test logest function', () => {
const stats = BooleanValueObject.create(true);
const result = testFunction.calculate(knownYs, knownXs, constb, stats);
expect(getObjectValue(result, true)).toStrictEqual([
- [1.03240326243, 0.999873102005, 1.02157358567, 0.950065530365, 1.95065522079],
+ [1.03240326225, 0.999873102003, 1.02157358597, 0.950065530249, 1.95065522079],
[0, 0, 0, 0, 0],
[1, 0, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[ErrorType.NUM, 0, ErrorType.NA, ErrorType.NA, ErrorType.NA],
@@ -211,10 +212,10 @@ describe('Test logest function', () => {
const constb2 = BooleanValueObject.create(false);
const result2 = testFunction.calculate(knownYs, knownXs, constb2, stats);
expect(getObjectValue(result2, true)).toStrictEqual([
- [1.05785486342, 1.00009083808, 1.00275120551, 0.944165822215, 1],
+ [1.05785486328, 1.00009083808, 1.00275120574, 0.944165822137, 1],
[0.382793300408, 0.00521575247085, 0.629924174927, 0.237868333877, ErrorType.NA],
- [0.994573882203, 0.935634628939, ErrorType.NA, ErrorType.NA, ErrorType.NA],
- [45.8234560762, 1, ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [0.994573882203, expect.closeTo(0.935634628939, 9), ErrorType.NA, ErrorType.NA, ErrorType.NA],
+ [expect.closeTo(45.8234560762, 8), 1, ErrorType.NA, ErrorType.NA, ErrorType.NA],
[160.457642442172, 0.875412158869, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
});
diff --git a/packages/engine-formula/src/functions/statistical/trend/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/trend/__tests__/index.spec.ts
index 98cd32bb0e..8b01e0f80d 100644
--- a/packages/engine-formula/src/functions/statistical/trend/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/trend/__tests__/index.spec.ts
@@ -570,19 +570,9 @@ describe('Test trend function', () => {
]);
const result4 = testFunction.calculate(knownYs2, knownXs2, newXs3, constb2);
- expect(getObjectValue(result4)).toStrictEqual([
- [1],
- [2],
- [3],
- [4],
- [5],
- [6],
- [7],
- [8],
- [9],
- [10],
- [11],
- ]);
+ expect(getObjectValue(result4)).toStrictEqual(
+ Array.from({ length: 11 }, (_, index) => [expect.closeTo(index + 1, 11)])
+ );
const knownYs3 = ArrayValueObject.create({
calculateValueList: transformToValueObject([
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 9cce58ea1e..f6b2046868 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -497,12 +497,13 @@ export class FormulaDataModel extends Disposable {
const startRow = 0;
const endRow = sheet.getRowCount() - 1;
- const sheetRowData: IObjectArrayPrimitiveType<Partial<IRowData>> = Object.create(null);
+ const sheetRowData: IObjectArrayPrimitiveType<Partial<IRowData> & { filtered?: boolean }> = Object.create(null);
for (let i = startRow; i <= endRow; i++) {
if (!sheet.getRowVisible(i)) {
sheetRowData[i] = {
hd: BooleanNumber.TRUE,
+ ...(sheet.getRowFiltered(i) ? { filtered: true } : {}),
};
}
}
diff --git a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
index 7c654ae2d4..7bdc05a173 100644
--- a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
@@ -24,6 +24,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
+import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';
import { FormulaDataModel } from '../../models/formula-data.model';
import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';
import { ISheetRowFilteredService } from '../sheet-row-filtered.service';
@@ -107,6 +108,22 @@ function createService(withCurrentWorkbook = true) {
}
describe('FormulaCurrentConfigService', () => {
+ it('distinguishes transported filter exclusions from manual hiding and clears stale exclusions', () => {
+ const testBed = createFunctionTestBed();
+ try {
+ const service = testBed.get(IFormulaCurrentConfigService);
+ const localFilter = testBed.get(ISheetRowFilteredService).register((_unitId, _sheetId, row) => row === 3);
+ service.loadDataLite({ test: { sheet1: { 1: { hd: 1, filtered: true }, 2: { hd: 1 } } } });
+ expect(service.getFilteredOutRows('test', 'sheet1', 0, 4)).toEqual([1, 3]);
+ expect(service.getUnitData().test.sheet1.rowData[2]).toEqual({ hd: 1 });
+ localFilter.dispose();
+ service.loadDataLite({ test: { sheet1: {} } });
+ expect(service.getFilteredOutRows('test', 'sheet1', 0, 4)).toEqual([]);
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+
it('should load explicit dataset config and merge dirty names to sheet-id map', () => {
const { service } = createService();
const unitData = {
diff --git a/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.ts b/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.ts
index 784721a0b0..93ad06c58d 100644
--- a/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.ts
@@ -27,11 +27,16 @@ describe('SheetRowFilteredService', () => {
service = injector.get(ISheetRowFilteredService);
});
- it('delegates row visibility checks to the active filter feature', () => {
- service.register((unitId, subUnitId, row) => unitId === 'book-1' && subUnitId === 'sheet-1' && row === 3);
+ it('combines row visibility checks from every filter feature', () => {
+ const sheetFilter = service.register((unitId, subUnitId, row) => unitId === 'book-1' && subUnitId === 'sheet-1' && row === 3);
+ service.register((unitId, subUnitId, row) => unitId === 'book-1' && subUnitId === 'sheet-1' && row === 4);
expect(service.getRowFiltered('book-1', 'sheet-1', 3)).toBe(true);
- expect(service.getRowFiltered('book-1', 'sheet-1', 4)).toBe(false);
+ expect(service.getRowFiltered('book-1', 'sheet-1', 4)).toBe(true);
expect(service.getRowFiltered('book-1', 'sheet-2', 3)).toBe(false);
+
+ sheetFilter.dispose();
+ expect(service.getRowFiltered('book-1', 'sheet-1', 3)).toBe(false);
+ expect(service.getRowFiltered('book-1', 'sheet-1', 4)).toBe(true);
});
});
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index b52e35d3ee..c0fc653252 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -159,6 +159,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _externalReferences: IFormulaExternalReferences = Object.create(null);
+ private _calculationRowData: IUnitRowData = Object.create(null);
+
private _calculationGeneration = 0;
private _forceCalculate: boolean = false;
@@ -203,6 +205,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._sheetNameMap = Object.create(null);
this._unitNameMap = Object.create(null);
this._externalReferences = Object.create(null);
+ this._calculationRowData = Object.create(null);
this._clearDependencyTreeCache = Object.create(null);
this._dirtyRanges = [];
this._dirtyNameMap = Object.create(null);
@@ -361,7 +364,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
const filteredOutRows: number[] = [];
for (let r = startRow; r <= endRow; r++) {
- if (this._sheetRowFilteredService.getRowFiltered(unitId, sheetId, r)) {
+ if (this._calculationRowData[unitId]?.[sheetId]?.[r]?.filtered
+ || this._sheetRowFilteredService.getRowFiltered(unitId, sheetId, r)) {
filteredOutRows.push(r);
}
}
@@ -371,6 +375,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
load(config: IFormulaDatasetConfig) {
this._calculationGeneration++;
+ this._calculationRowData = Object.create(null);
if (config.allUnitData && config.unitSheetNameMap && config.unitStylesData) {
this._unitData = copyUnitData(config.allUnitData);
this._unitStylesData = config.unitStylesData;
@@ -523,6 +528,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
* @param rowData
*/
private _applyUnitRowData(rowData: IUnitRowData) {
+ this._calculationRowData = rowData;
for (const unitId of Object.keys(rowData)) {
if (rowData[unitId] == null) {
continue;
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 59b4739049..7fd198bcdd 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -129,6 +129,8 @@ export interface IFormulaRuntimeService {
getFunctionDefinitionPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>>;
+ markExternalReferenceUnavailable(): void;
+
setRuntimeData(functionVariant: FunctionVariantType): void;
getUnitData(): IRuntimeUnitDataType;
@@ -212,6 +214,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
private _formulaExecuteStage: FormulaExecuteStageType = FormulaExecuteStageType.IDLE;
private _stopState = false;
+ private _externalReferenceUnavailable = false;
private _currentRow: number = -1;
private _currentColumn: number = -1;
@@ -427,6 +430,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
sheetId: string,
unitId: string
) {
+ this._externalReferenceUnavailable = false;
this._currentRow = row;
this._currentColumn = column;
this._currentRowCount = rowCount;
@@ -510,7 +514,23 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
subComponentData[formulaId][y][x] = cellDatas;
}
+ markExternalReferenceUnavailable(): void {
+ this._externalReferenceUnavailable = true;
+ }
+
+ // eslint-disable-next-line max-lines-per-function
setRuntimeData(functionVariant: FunctionVariantType) {
+ if (this._externalReferenceUnavailable) {
+ const cell = this._currentConfigService.getUnitData()[this._currentUnitId]?.[this._currentSubUnitId]
+ ?.cellData
+ .getValue(this._currentRow, this._currentColumn);
+ // Leaving the original cell in place also lets downstream formulas read its cached value.
+ const formula = this._currentConfigService.getFormulaData()[this._currentUnitId]?.[this._currentSubUnitId]
+ ?.[this._currentRow]?.[this._currentColumn]?.f;
+ if (cell?.f && cell.v != null && (formula == null || formula === cell.f)) {
+ return;
+ }
+ }
const row = this._currentRow;
const column = this._currentColumn;
const rowCount = this._currentRowCount;
diff --git a/packages/engine-formula/src/services/sheet-row-filtered.service.ts b/packages/engine-formula/src/services/sheet-row-filtered.service.ts
index ae5bbbb833..bfe6bd1bd9 100644
--- a/packages/engine-formula/src/services/sheet-row-filtered.service.ts
+++ b/packages/engine-formula/src/services/sheet-row-filtered.service.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { createIdentifier, Disposable } from '@univerjs/core';
+import type { IDisposable } from '@univerjs/core';
+import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
type CallbackFunction = (unitId: string, subUnitId: string, row: number) => boolean;
@@ -22,24 +23,32 @@ type CallbackFunction = (unitId: string, subUnitId: string, row: number) => bool
* The service that gets the row filter status
*/
export interface ISheetRowFilteredService {
- register(callback: CallbackFunction): void;
+ register(callback: CallbackFunction): IDisposable;
getRowFiltered(unitId: string, subUnitId: string, row: number): boolean;
}
export class SheetRowFilteredService extends Disposable implements ISheetRowFilteredService {
- private _getRowFilteredCallback: CallbackFunction | undefined;
+ private _getRowFilteredCallbacks = new Set<CallbackFunction>();
register(callback: CallbackFunction) {
- this._getRowFilteredCallback = callback;
+ this._getRowFilteredCallbacks.add(callback);
+ return toDisposable(() => this._getRowFilteredCallbacks.delete(callback));
}
getRowFiltered(unitId: string, subUnitId: string, row: number): boolean {
- if (!this._getRowFilteredCallback) {
- return false;
+ for (const callback of this._getRowFilteredCallbacks) {
+ if (callback(unitId, subUnitId, row)) {
+ return true;
+ }
}
- return this._getRowFilteredCallback(unitId, subUnitId, row) ?? false;
+ return false;
+ }
+
+ override dispose(): void {
+ this._getRowFilteredCallbacks.clear();
+ super.dispose();
}
}
diff --git a/packages/engine-formula/src/services/unit-reference-resolver.service.ts b/packages/engine-formula/src/services/unit-reference-resolver.service.ts
index 9f359ce6f2..d3aaaaf38e 100644
--- a/packages/engine-formula/src/services/unit-reference-resolver.service.ts
+++ b/packages/engine-formula/src/services/unit-reference-resolver.service.ts
@@ -25,6 +25,8 @@ export interface IFormulaUnitReferenceResolveInput {
hostUnitId: string;
qualifier: string;
referenceKind: FormulaUnitReferenceKind;
+ /** Called only when the source workbook cannot be resolved. */
+ onUnavailable?: () => void;
}
export interface IFormulaUnitReferenceResolution {
@@ -62,6 +64,7 @@ export class FormulaUnitReferenceResolver implements IFormulaUnitReferenceResolv
hostUnitId,
qualifier,
referenceKind,
+ onUnavailable,
}: IFormulaUnitReferenceResolveInput): IFormulaUnitReferenceResolution | ErrorType {
const unitNameMap = this._currentConfigService.getUnitNameMap();
const unitData = this._currentConfigService.getUnitData();
@@ -95,6 +98,9 @@ export class FormulaUnitReferenceResolver implements IFormulaUnitReferenceResolv
);
if (matches.length !== 1) {
+ if (matches.length === 0) {
+ onUnavailable?.();
+ }
return ErrorType.REF;
}
diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts
index 24f29caad8..8ebcc2a9d0 100644
--- a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts
+++ b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts
@@ -31,7 +31,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
import { BORDER_TYPE } from '../../../basics/const';
import { FontCache } from '../../docs/layout/shaping-engine/font-cache';
-import { getGeneralNumberDisplayText, SpreadsheetSkeleton } from '../sheet.render-skeleton';
+import { getCustomNumberDisplayText, getGeneralNumberDisplayText, SpreadsheetSkeleton } from '../sheet.render-skeleton';
describe('Rich-text render snapshot isolation', () => {
it.each(['font cache', 'row height', 'column width'])(
@@ -303,3 +303,22 @@ describe('General number display', () => {
expect(getGeneralNumberDisplayText(148706409, '148706409', '13.33px SimSun', 70)).toBe('148706409');
});
});
+
+describe('Custom number display', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('uses hashes when a formatted number does not fit', () => {
+ vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({
+ fontBoundingBoxAscent: 0,
+ fontBoundingBoxDescent: 0,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ width: text.length * 7,
+ }));
+
+ expect(getCustomNumberDisplayText('2022-11-01 0:00:00', '13.33px SimSun', 66)).toBe('#########');
+ expect(getCustomNumberDisplayText('10/1/2022', '13.33px SimSun', 70)).toBe('10/1/2022');
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts
index 6da740c3a7..939462b371 100644
--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts
@@ -100,6 +100,14 @@ export const FULL_WIDTH_HORIZONTAL_ALIGNMENTS = new Set([
HorizontalAlign.DISTRIBUTED,
]);
+function getNumberOverflowText(fontString: string, availableWidth: number): string {
+ const hashWidth = FontCache.getMeasureText('#', fontString).width;
+ if (hashWidth <= 0) {
+ return '#';
+ }
+ return '#'.repeat(Math.max(1, Math.floor(availableWidth / hashWidth)));
+}
+
export function getShrinkToFitScale(contentWidth: number, availableWidth: number, fontSize: number): number {
if (contentWidth <= availableWidth || contentWidth <= 0 || availableWidth <= 0 || fontSize <= 0) {
return 1;
@@ -141,11 +149,22 @@ export function getGeneralNumberDisplayText(
return '0';
}
- const hashWidth = FontCache.getMeasureText('#', fontString).width;
- if (hashWidth <= 0) {
- return '#';
+ return getNumberOverflowText(fontString, availableWidth);
+}
+
+export function getCustomNumberDisplayText(
+ displayText: string,
+ fontString: string,
+ availableWidth: number
+): string {
+ if (
+ availableWidth <= 0 ||
+ FontCache.getMeasureText(displayText, fontString).width <= availableWidth
+ ) {
+ return displayText;
}
- return '#'.repeat(Math.max(1, Math.floor(availableWidth / hashWidth)));
+
+ return getNumberOverflowText(fontString, availableWidth);
}
export function scaleDocumentDataForShrinkToFit(documentData: IDocumentData, scale: number, fallbackFontSize: number): IDocumentData {
@@ -1445,23 +1464,15 @@ export class SpreadsheetSkeleton extends SheetSkeleton {
}
}
- private _applyGeneralNumberDisplay(row: number, col: number, fontCache: IFontCacheItem, style: IStyleData): void {
+ private _applyNumberDisplay(row: number, col: number, fontCache: IFontCacheItem, style: IStyleData): void {
const cellData = fontCache.cellData;
if (!cellData || style.stf === BooleanNumber.TRUE || fontCache.documentSkeleton) {
return;
}
- if (!isDefaultFormat(style.n?.pattern)) {
- return;
- }
if (cellData.t !== CellValueType.NUMBER && (Tools.isDefine(cellData.t) || typeof cellData.v !== 'number')) {
return;
}
- const value = Number(cellData.v);
- if (!Number.isFinite(value)) {
- return;
- }
-
const cellInfo = this.getCellWithCoordByIndex(row, col, false);
const startX = cellInfo.isMergedMainCell ? cellInfo.mergeInfo.startX : cellInfo.startX;
const endX = cellInfo.isMergedMainCell ? cellInfo.mergeInfo.endX : cellInfo.endX;
@@ -1472,12 +1483,15 @@ export class SpreadsheetSkeleton extends SheetSkeleton {
- (padding.r ?? DEFAULT_PADDING_DATA.r)
- (extension?.leftOffset ?? 0)
- (extension?.rightOffset ?? 0);
- fontCache.displayText = getGeneralNumberDisplayText(
- value,
- fontCache.displayText ?? getDisplayValueFromCell(cellData),
- fontCache.fontString,
- availableWidth
- );
+ const displayText = fontCache.displayText ?? getDisplayValueFromCell(cellData);
+ if (isDefaultFormat(style.n?.pattern)) {
+ const value = Number(cellData.v);
+ if (Number.isFinite(value)) {
+ fontCache.displayText = getGeneralNumberDisplayText(value, displayText, fontCache.fontString, availableWidth);
+ }
+ } else {
+ fontCache.displayText = getCustomNumberDisplayText(displayText, fontCache.fontString, availableWidth);
+ }
}
_setFontStylesCache(row: number, col: number, cellData: Nullable<ICellDataForSheetInterceptor>, style: IStyleData, hasMergeData = true) {
@@ -1495,7 +1509,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {
const cacheItem = cacheValue as IFontCacheItem;
cacheItem.cellData = cellData;
setRenderTextCache(cacheItem, cellData);
- this._applyGeneralNumberDisplay(row, col, cacheItem, style);
+ this._applyNumberDisplay(row, col, cacheItem, style);
this._stylesCache.fontMatrix.setValue(row, col, cacheValue as IFontCacheItem);
return;
}
@@ -1554,7 +1568,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {
}
const fontCacheItem = config as IFontCacheItem;
setRenderTextCache(fontCacheItem, cellData);
- this._applyGeneralNumberDisplay(row, col, fontCacheItem, style);
+ this._applyNumberDisplay(row, col, fontCacheItem, style);
this._applyShrinkToFit(row, col, fontCacheItem, style);
this._calculateOverflowCell(row, col, fontCacheItem, hasMergeData);
this._stylesCache.fontMatrix.setValue(row, col, fontCacheItem);
diff --git a/packages/protocol/src/ts/univer/workbook.ts b/packages/protocol/src/ts/univer/workbook.ts
index d4bef82d1e..ffee929952 100644
--- a/packages/protocol/src/ts/univer/workbook.ts
+++ b/packages/protocol/src/ts/univer/workbook.ts
@@ -26,6 +26,20 @@ export enum CellValueType {
UNRECOGNIZED = -1,
}
+export enum FormulaType {
+ FORMULA_TYPE_NORMAL = 0,
+ FORMULA_TYPE_SHARED = 1,
+ FORMULA_TYPE_ARRAY = 2,
+ FORMULA_TYPE_DATA_TABLE = 3,
+ UNRECOGNIZED = -1,
+}
+
+export enum BooleanNumber {
+ BOOLEAN_NUMBER_FALSE = 0,
+ BOOLEAN_NUMBER_TRUE = 1,
+ UNRECOGNIZED = -1,
+}
+
export interface IWorksheetMeta {
type: number;
id: string;
@@ -83,6 +97,12 @@ export interface ICellData {
ref: string;
/** New Excel formulas need to add prefixes for differentiation, e.g., _xlfn._xlws. _xlfn. _xlws. _xludf. */
xf: string;
+ ft?:
+ | FormulaType
+ | undefined;
+ fd?:
+ | BooleanNumber
+ | undefined;
}
export interface ISheetBlock {
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts
index 9c57289e15..2cc007648a 100644
--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts
@@ -38,7 +38,7 @@ describe('DataValidationRejectInputController', () => {
| undefined;
const open = vi.fn();
const close = vi.fn();
- const getRuleById = vi.fn(() => ({ type: 'list', errorStyle: DataValidationErrorStyle.STOP }));
+ const getRuleById = vi.fn(() => ({ type: 'list', errorStyle: DataValidationErrorStyle.STOP, showErrorMessage: true }));
const model = {
getRuleIdByLocation: vi.fn(() => 'rule-1'),
getRuleById,
@@ -82,7 +82,10 @@ describe('DataValidationRejectInputController', () => {
await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(true);
- getRuleById.mockReturnValue({ type: 'list', errorStyle: DataValidationErrorStyle.WARNING });
+ getRuleById.mockReturnValue({ type: 'list', errorStyle: DataValidationErrorStyle.STOP, showErrorMessage: false });
+ await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(true);
+
+ getRuleById.mockReturnValue({ type: 'list', errorStyle: DataValidationErrorStyle.WARNING, showErrorMessage: true });
await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(true);
controller.showReject('Bad input');
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-reject-input.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-reject-input.controller.ts
index 29947bf240..a05837e9d1 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-reject-input.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-reject-input.controller.ts
@@ -49,7 +49,7 @@ export class DataValidationRejectInputController extends Disposable {
return next(Promise.resolve(false))!;
}
- if (!rule || rule.errorStyle !== DataValidationErrorStyle.STOP) {
+ if (!rule || rule.showErrorMessage === false || rule.errorStyle !== DataValidationErrorStyle.STOP) {
return next(Promise.resolve(true))!;
}
const validator = this._dataValidatorRegistryService.getValidatorItem(rule.type);
diff --git a/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts
index 8df2d1ed58..066b461016 100644
--- a/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts
+++ b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts
@@ -53,6 +53,7 @@ interface IRule {
formula1?: string;
renderMode?: DataValidationRenderMode;
errorStyle?: DataValidationErrorStyle;
+ showErrorMessage?: boolean;
bizInfo?: Record<string, unknown>;
}
@@ -413,6 +414,26 @@ describe('DataValidationDropdownManagerService', () => {
});
});
+ it('allows an invalid date selection when the error alert is disabled', async () => {
+ testBed = createTestBed();
+ setRule(testBed, {
+ uid: 'rule-date-alert-disabled',
+ type: 'date',
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: false,
+ }, {
+ dropdownType: DataValidatorDropdownType.DATE,
+ validator: () => false,
+ });
+
+ showDropdown(testBed, 4);
+ const dropdown = getDropdown(testBed);
+ await expect((dropdown.props as { onChange: (value: ReturnType<typeof dateKit>) => Promise<boolean> }).onChange(dateKit('2026-06-17'))).resolves.toBe(true);
+ expect(getSetRangeValue(testBed)).toMatchObject({
+ v: expect.any(Number),
+ });
+ });
+
it('keeps an unchanged date value and closes cell editing when confirmed', async () => {
testBed = createTestBed();
setRule(testBed, {
diff --git a/packages/sheets-data-validation-ui/src/services/dropdown-manager.service.ts b/packages/sheets-data-validation-ui/src/services/dropdown-manager.service.ts
index a673a20508..71e00560e1 100644
--- a/packages/sheets-data-validation-ui/src/services/dropdown-manager.service.ts
+++ b/packages/sheets-data-validation-ui/src/services/dropdown-manager.service.ts
@@ -221,6 +221,7 @@ export class DataValidationDropdownManagerService extends Disposable {
const handleSerialSave = async (serial: number, targetPatternType: DatePatternType, interceptValue: string) => {
if (
+ rule.showErrorMessage === false ||
rule.errorStyle !== DataValidationErrorStyle.STOP ||
(await validator.validator({
value: serial,
diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
index a4d4805643..65cf91bdd6 100644
--- a/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
+++ b/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
@@ -268,5 +268,11 @@ describe('Test FDataValidationBuilder', () => {
error: 'Choose an approval state',
});
expect(copiedRule.uid).not.toBe(rule.uid);
+
+ const disabledAlert = new FDataValidationBuilder({
+ ...rule,
+ showErrorMessage: false,
+ });
+ expect(disabledAlert.getAllowInvalid()).toBe(true);
});
});
diff --git a/packages/sheets-data-validation/src/facade/f-data-validation-builder.ts b/packages/sheets-data-validation/src/facade/f-data-validation-builder.ts
index 69b0d5ead2..8e3a42a2d8 100644
--- a/packages/sheets-data-validation/src/facade/f-data-validation-builder.ts
+++ b/packages/sheets-data-validation/src/facade/f-data-validation-builder.ts
@@ -128,7 +128,7 @@ export class FDataValidationBuilder {
* ```
*/
getAllowInvalid(): boolean {
- return this._rule.errorStyle !== DataValidationErrorStyle.STOP;
+ return this._rule.showErrorMessage === false || this._rule.errorStyle !== DataValidationErrorStyle.STOP;
}
/**
diff --git a/packages/sheets-data-validation/src/facade/f-data-validation.ts b/packages/sheets-data-validation/src/facade/f-data-validation.ts
index c083b05f07..65642484b3 100644
--- a/packages/sheets-data-validation/src/facade/f-data-validation.ts
+++ b/packages/sheets-data-validation/src/facade/f-data-validation.ts
@@ -70,7 +70,7 @@ export class FDataValidation {
* ```
*/
getAllowInvalid(): boolean {
- return this.rule.errorStyle !== DataValidationErrorStyle.STOP;
+ return this.rule.showErrorMessage === false || this.rule.errorStyle !== DataValidationErrorStyle.STOP;
};
/**
diff --git a/packages/sheets-filter/src/commands/mutations/__tests__/sheets-filter.mutation.spec.ts b/packages/sheets-filter/src/commands/mutations/__tests__/sheets-filter.mutation.spec.ts
index 6f5ee00126..b2881ac496 100644
--- a/packages/sheets-filter/src/commands/mutations/__tests__/sheets-filter.mutation.spec.ts
+++ b/packages/sheets-filter/src/commands/mutations/__tests__/sheets-filter.mutation.spec.ts
@@ -191,7 +191,7 @@ describe('test mutations of sheets filter', () => {
expect(filterModel!.getRange()).toEqual({ startRow: 0, startColumn: 0, endRow: 5, endColumn: 5 });
expect(filterModel!.filteredOutRows.size).toBe(0);
- expect(commandService.syncExecuteCommand(SetSheetsFilterCriteriaMutation.id, {
+ const params = {
unitId: 'test',
subUnitId: 'sheet1',
col: 0,
@@ -199,8 +199,10 @@ describe('test mutations of sheets filter', () => {
colId: 0,
filters: ['A'],
},
- } as ISetSheetsFilterCriteriaMutationParams)).toBeTruthy();
+ } as ISetSheetsFilterCriteriaMutationParams;
+ expect(commandService.syncExecuteCommand(SetSheetsFilterCriteriaMutation.id, params)).toBeTruthy();
expect(filterModel!.filteredOutRows.size).toBe(5);
+ expect(params.filteredOutRows).toEqual(Array.from(filterModel!.filteredOutRows));
});
it('should return false when set filter criteria on a non-existing filter model', () => {
diff --git a/packages/sheets-filter/src/commands/mutations/sheets-filter.mutation.ts b/packages/sheets-filter/src/commands/mutations/sheets-filter.mutation.ts
index f788c215e4..37e31c4f7f 100644
--- a/packages/sheets-filter/src/commands/mutations/sheets-filter.mutation.ts
+++ b/packages/sheets-filter/src/commands/mutations/sheets-filter.mutation.ts
@@ -32,6 +32,7 @@ import { SheetsFilterService } from '../../services/sheet-filter.service';
*/
export interface ISetSheetsFilterRangeMutationParams extends ISheetCommandSharedParams {
range: IRange;
+ filteredOutRows?: number[];
}
/**
@@ -51,6 +52,7 @@ export const SetSheetsFilterRangeMutation: IMutation<ISetSheetsFilterRangeMutati
// check if the range is in bound?
const filterModel = sheetsFilterService.ensureFilterModel(unitId, subUnitId);
filterModel.setRange(range);
+ params.filteredOutRows = Array.from(filterModel.filteredOutRows);
return true;
},
@@ -66,6 +68,7 @@ export interface ISetSheetsFilterCriteriaMutationParams extends ISheetCommandSha
col: number;
criteria: Nullable<IFilterColumn>;
reCalc?: boolean;
+ filteredOutRows?: number[];
}
/**
@@ -82,6 +85,7 @@ export const SetSheetsFilterCriteriaMutation: IMutation<ISetSheetsFilterCriteria
if (!filterModel) return false;
filterModel.setCriteria(col, criteria, reCalc);
+ params.filteredOutRows = Array.from(filterModel.filteredOutRows);
return true;
},
};
@@ -95,7 +99,11 @@ export const RemoveSheetsFilterMutation: IMutation<ISheetCommandSharedParams> =
handler: (accessor, params) => {
const { unitId, subUnitId } = params;
const sheetsFilterService = accessor.get(SheetsFilterService);
- return sheetsFilterService.removeFilterModel(unitId, subUnitId);
+ const removed = sheetsFilterService.removeFilterModel(unitId, subUnitId);
+ if (removed) {
+ (params as ISheetCommandSharedParams & { filteredOutRows?: number[] }).filteredOutRows = [];
+ }
+ return removed;
},
};
@@ -114,6 +122,9 @@ export const ReCalcSheetsFilterMutation: IMutation<ISheetCommandSharedParams> =
}
filterModel.reCalc();
+ (params as ISheetCommandSharedParams & { filteredOutRows?: number[] }).filteredOutRows = Array.from(
+ filterModel.filteredOutRows
+ );
return true;
},
};
diff --git a/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts
index d6ca073367..b817b41b22 100644
--- a/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts
+++ b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Injector, IUniverInstanceService } from '@univerjs/core';
+import { Injector, IUniverInstanceService, toDisposable } from '@univerjs/core';
import { IActiveDirtyManagerService, ISheetRowFilteredService } from '@univerjs/engine-formula';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SheetsFilterFormulaService } from '../sheet-filter-formula.service';
@@ -31,7 +31,12 @@ describe('SheetsFilterFormulaService', () => {
}
class TestSheetRowFilteredService {
- register = (callback: never) => (rowFilteredCallback = callback);
+ register = (callback: never) => {
+ rowFilteredCallback = callback;
+ return toDisposable(() => {
+ rowFilteredCallback = undefined;
+ });
+ };
}
class TestSheetsFilterService {
diff --git a/packages/sheets-filter/src/services/sheet-filter-formula.service.ts b/packages/sheets-filter/src/services/sheet-filter-formula.service.ts
index b1b4794485..2f75824bb7 100644
--- a/packages/sheets-filter/src/services/sheet-filter-formula.service.ts
+++ b/packages/sheets-filter/src/services/sheet-filter-formula.service.ts
@@ -87,8 +87,8 @@ export class SheetsFilterFormulaService extends Disposable {
}
private _registerSheetRowFiltered() {
- this._sheetRowFilteredService.register((unitId, subUnitId, row) => {
+ this.disposeWithMe(this._sheetRowFilteredService.register((unitId, subUnitId, row) => {
return this._sheetsFilterService.getFilterModel(unitId, subUnitId)?.isRowFiltered(row) ?? false;
- });
+ }));
}
}
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
index cf73353681..6a90a3475d 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
@@ -18,7 +18,9 @@ import type { Dependency, ICellData, IDisposable, IRange, IWorkbookData, Nullabl
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo } from '@univerjs/sheets-ui';
import {
+ BooleanNumber,
DisposableCollection,
+ FormulaType,
ICommandService,
ILogService,
Inject,
@@ -472,46 +474,53 @@ describe('Test cut command with formulas', () => {
univer.dispose();
});
- it('pastes cross-page formula payload with relative reference offsets', async () => {
- get(SheetsSelectionsService).addSelections([
- {
- range: { startRow: 4, startColumn: 3, endRow: 4, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },
- primary: null,
- style: null,
- },
- ]);
-
- const formulaItem = {
- types: ['web application/x-univer-sheets-formula', 'text/html'],
- getType: async (type: string) => {
- if (type === 'web application/x-univer-sheets-formula') {
- return new Blob([JSON.stringify({
- rowCount: 1,
- columnCount: 1,
- origin: {
- row: 1,
- column: 1,
- },
- formulas: [
- {
- row: 0,
- column: 0,
- f: '=C2',
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])(
+ 'pastes cross-page formula payload with relative reference offsets and array metadata (%s)',
+ async (fd) => {
+ get(SheetsSelectionsService).addSelections([
+ {
+ range: { startRow: 4, startColumn: 3, endRow: 4, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ const formulaItem = {
+ types: ['web application/x-univer-sheets-formula', 'text/html'],
+ getType: async (type: string) => {
+ if (type === 'web application/x-univer-sheets-formula') {
+ return new Blob([JSON.stringify({
+ rowCount: 1,
+ columnCount: 1,
+ origin: {
+ row: 1,
+ column: 1,
},
- ],
- })], { type });
- }
+ formulas: [
+ {
+ row: 0,
+ column: 0,
+ f: '=C2',
+ ft: FormulaType.ARRAY,
+ fd,
+ },
+ ],
+ })], { type });
+ }
- return new Blob([
- '<google-sheets-html-origin><table><tbody><tr><td>formula result</td></tr></tbody></table></google-sheets-html-origin>',
- ], { type });
- },
- } as unknown as ClipboardItem;
+ return new Blob([
+ '<google-sheets-html-origin><table><tbody><tr><td>formula result</td></tr></tbody></table></google-sheets-html-origin>',
+ ], { type });
+ },
+ } as unknown as ClipboardItem;
- await sheetClipboardService.paste(formulaItem);
+ await sheetClipboardService.paste(formulaItem);
- expect(getValues(4, 3, 4, 3)?.[0][0]?.f).toBe('=E5');
- });
+ expect(getValues(4, 3, 4, 3)?.[0][0]?.f).toBe('=E5');
+ expect(getValues(4, 3, 4, 3)?.[0][0]?.ft).toBe(FormulaType.ARRAY);
+ expect(getValues(4, 3, 4, 3)?.[0][0]?.fd).toBe(fd);
+ }
+ );
it('keeps non-formula html cells when formula payload restores formulas', async () => {
get(SheetsSelectionsService).addSelections([
@@ -934,6 +943,8 @@ describe('Test paste with formula', () => {
12: {
3: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1163,6 +1174,8 @@ describe('Test paste with formula', () => {
5: {
5: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1172,6 +1185,8 @@ describe('Test paste with formula', () => {
},
6: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1181,6 +1196,8 @@ describe('Test paste with formula', () => {
},
7: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1190,6 +1207,8 @@ describe('Test paste with formula', () => {
},
8: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1201,6 +1220,8 @@ describe('Test paste with formula', () => {
6: {
5: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1210,6 +1231,8 @@ describe('Test paste with formula', () => {
},
6: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1219,6 +1242,8 @@ describe('Test paste with formula', () => {
},
7: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1228,6 +1253,8 @@ describe('Test paste with formula', () => {
},
8: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1239,6 +1266,8 @@ describe('Test paste with formula', () => {
7: {
5: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1248,6 +1277,8 @@ describe('Test paste with formula', () => {
},
6: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1257,6 +1288,8 @@ describe('Test paste with formula', () => {
},
7: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1266,6 +1299,8 @@ describe('Test paste with formula', () => {
},
8: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1277,6 +1312,8 @@ describe('Test paste with formula', () => {
8: {
5: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1286,6 +1323,8 @@ describe('Test paste with formula', () => {
},
6: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1295,6 +1334,8 @@ describe('Test paste with formula', () => {
},
7: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1304,6 +1345,8 @@ describe('Test paste with formula', () => {
},
8: {
custom: null,
+ ft: null,
+ fd: null,
s: null,
f: null,
si: null,
@@ -1481,6 +1524,92 @@ describe('getSetCellFormulaMutations matrix branches', () => {
return { get, has };
}
+ it.each([
+ [PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, COPY_TYPE.COPY],
+ [PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA, COPY_TYPE.COPY],
+ [PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE, COPY_TYPE.COPY],
+ [PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, COPY_TYPE.CUT],
+ ])('replaces formula metadata and restores it on undo for %s / %s', (pasteType, copyType) => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+ const worksheet = get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;
+ const previous: ICellData = { f: '=OLD()', ft: FormulaType.ARRAY, fd: BooleanNumber.TRUE };
+
+ for (const source of [
+ { f: '=A1', v: 12 },
+ { f: '=A1', v: 12, ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE },
+ { f: '=A1', v: 12, ft: FormulaType.ARRAY, fd: BooleanNumber.TRUE },
+ ]) {
+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 8: { 4: previous }, 9: { 4: previous } },
+ });
+ const result = get(Injector).invoke((accessor) => getSetCellFormulaMutations(
+ 'test',
+ 'sheet1',
+ { rows: [8, 9], cols: [4] },
+ new ObjectMatrix<ICellDataWithSpanInfo>({ 0: { 0: source }, 1: { 0: source } }),
+ accessor,
+ { copyType, pasteType },
+ get(LexerTreeBuilder),
+ get(FormulaDataModel),
+ false,
+ { unitId: 'test', subUnitId: 'sheet1', range: { rows: [0], cols: [0] } }
+ ));
+ const keepsFormula = pasteType !== PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE;
+ for (const mutations of [result.redos, result.undos, result.redos]) {
+ mutations.forEach((mutation) => {
+ expect(commandService.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);
+ });
+ for (const row of [8, 9]) {
+ const cell = worksheet.getCellRaw(row, 4);
+ if (mutations === result.undos) {
+ expect(cell).toMatchObject(previous);
+ } else {
+ expect(cell?.ft).toBe(keepsFormula ? source.ft : undefined);
+ expect(cell?.fd).toBe(keepsFormula ? source.fd : undefined);
+ if (!keepsFormula) {
+ expect(cell?.f).toBeUndefined();
+ expect(cell?.v).toBe(12);
+ } else if (row === 8) {
+ expect(cell?.f).toBe(copyType === COPY_TYPE.CUT ? '=A1' : '=E9');
+ } else if (copyType === COPY_TYPE.COPY) {
+ expect(cell?.si).toBeTruthy();
+ }
+ }
+ }
+ }
+ }
+ });
+
+ it('clears imported metadata when external formula text replaces an array formula', () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 8: { 4: { f: '=OLD()', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE } } },
+ });
+ const result = get(Injector).invoke((accessor) => getSetCellFormulaMutations(
+ 'test',
+ 'sheet1',
+ { rows: [8], cols: [4] },
+ new ObjectMatrix<ICellDataWithSpanInfo>({ 0: { 0: { v: '=A1' } } }),
+ accessor,
+ { copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE },
+ get(LexerTreeBuilder),
+ get(FormulaDataModel),
+ false,
+ null
+ ));
+ result.redos.forEach((mutation) => commandService.syncExecuteCommand(mutation.id, mutation.params));
+ const worksheet = get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;
+ expect(worksheet.getCellRaw(8, 4)).toMatchObject({ f: '=A1' });
+ expect(worksheet.getCellRaw(8, 4)?.ft).toBeUndefined();
+ expect(worksheet.getCellRaw(8, 4)?.fd).toBeUndefined();
+ });
+
it('converts pasted formula-looking text into cell formulas when there is no paste source', () => {
const matrix = new ObjectMatrix<ICellDataWithSpanInfo>({
0: {
diff --git a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
index c392e50e2d..f843760cfe 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
@@ -14,9 +14,24 @@
* limitations under the License.
*/
-import type { IAccessor, ICellData, ICellDataWithSpanAndDisplay, IMutationInfo, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type {
+ IAccessor,
+ ICellData,
+ ICellDataWithSpanAndDisplay,
+ IMutationInfo,
+ IRange,
+ Nullable,
+ Workbook,
+ Worksheet,
+} from '@univerjs/core';
import type { IDiscreteRange, ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import type { ICellDataWithSpanInfo, ICopyPastePayload, IPasteHookValueType, ISheetClipboardHook, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import type {
+ ICellDataWithSpanInfo,
+ ICopyPastePayload,
+ IPasteHookValueType,
+ ISheetClipboardHook,
+ ISheetDiscreteRangeLocation,
+} from '@univerjs/sheets-ui';
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Disposable,
@@ -32,7 +47,12 @@ import {
} from '@univerjs/core';
import { FormulaDataModel, LexerTreeBuilder } from '@univerjs/engine-formula';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';
-import { COPY_TYPE, ISheetClipboardService, PREDEFINED_HOOK_NAME_COPY, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';
+import {
+ COPY_TYPE,
+ ISheetClipboardService,
+ PREDEFINED_HOOK_NAME_COPY,
+ PREDEFINED_HOOK_NAME_PASTE,
+} from '@univerjs/sheets-ui';
export const DEFAULT_PASTE_FORMULA = 'default-paste-formula';
@@ -118,10 +138,14 @@ export class FormulaClipboardController extends Disposable {
matrixFragment.setValue(rowIndexInMatrix, columnIndexInMatrix, {
...getEmptyCell(),
f: formulaString,
+ ft: cellData.ft,
+ fd: cellData.fd,
});
plainMatrix.setValue(rowIndexInMatrix, columnIndexInMatrix, {
...getEmptyCell(),
f: formulaString,
+ ft: cellData.ft,
+ fd: cellData.fd,
displayV: formulaString,
});
} else {
@@ -256,6 +280,25 @@ export function getSetCellFormulaMutations(
};
}
+ const worksheet = accessor.get(IUniverInstanceService).getUnit<Workbook>(unitId)?.getSheetBySheetId(subUnitId);
+ matrix.forValue((row, col, source) => {
+ const targetRow = range.rows[row];
+ const targetCol = range.cols[col];
+ const value = valueMatrix.getValue(targetRow, targetCol);
+ if (!value) {
+ return;
+ }
+
+ // Paste replaces the target formula; omitted source metadata must not retain target flags.
+ const target = worksheet?.getCellRaw(targetRow, targetCol);
+ const keepsFormula = pasteFrom && copyInfo.pasteType !== PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE
+ && (isFormulaString(value.f) || isFormulaId(value.si));
+ if (source.ft != null || source.fd != null || target?.ft != null || target?.fd != null) {
+ value.ft = keepsFormula ? source.ft ?? null : null;
+ value.fd = keepsFormula ? source.fd ?? null : null;
+ }
+ });
+
// set cell value and style
const setValuesMutation: ISetRangeValuesMutationParams = {
unitId,
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
index 41195fc737..3525bf0f20 100644
--- a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { Dependency, Direction, Nullable } from '@univerjs/core';
+import type { Dependency, Direction, ICellData, Nullable } from '@univerjs/core';
import type { IAutoFillLocation } from '@univerjs/sheets';
+import { BooleanNumber, FormulaType } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AutoFillService, IAutoFillService } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
import { FormulaAutoFillController } from '../formula-auto-fill.controller';
@@ -175,4 +175,26 @@ describe('FormulaAutoFillController', () => {
},
]);
});
+
+ it.each([undefined, BooleanNumber.FALSE, BooleanNumber.TRUE])(
+ 'preserves source formula metadata when filling shared followers (%s)',
+ (fd) => {
+ const source: ICellData = { f: '=A1' };
+ if (fd !== undefined) {
+ source.ft = FormulaType.ARRAY;
+ source.fd = fd;
+ }
+ const rule = testBed.injector.get(IAutoFillService).getRules().find((rule) => rule.type === AUTO_FILL_DATA_TYPE.FORMULA)!;
+ const result = rule.applyFunctions![AUTO_FILL_APPLY_TYPE.COPY]!({
+ data: [source],
+ index: [0],
+ }, 2, 2, { formula: [{ data: [source], index: [0] }] }, createLocation([0], [1, 2]));
+ expect(result[0]?.f).toBe('=A2');
+ expect(result[1]?.si).toBe(result[0]?.si);
+ for (const cell of result) {
+ expect(cell?.ft).toBe(source.ft);
+ expect(cell?.fd).toBe(fd);
+ }
+ }
+ );
});
diff --git a/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts b/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
index 3f939daccd..b3087587cd 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'نص التلميح',
addTitle: 'إدراج ارتباط تشعبي',
label: 'التسمية',
type: 'النوع',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts b/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
index 91ff2da23f..cc535c6774 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Text d’ajuda',
addTitle: 'Insereix enllaç',
label: 'Etiqueta',
type: 'Tipus',
diff --git a/packages/sheets-hyper-link-ui/src/locale/de-DE.ts b/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
index 6868cad204..34643017ed 100644
--- a/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Hinweistext',
addTitle: 'Link einfügen',
label: 'Beschriftung',
type: 'Typ',
diff --git a/packages/sheets-hyper-link-ui/src/locale/en-US.ts b/packages/sheets-hyper-link-ui/src/locale/en-US.ts
index cd711d896f..201cf50740 100644
--- a/packages/sheets-hyper-link-ui/src/locale/en-US.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/en-US.ts
@@ -17,6 +17,7 @@
const locale = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Screen tip',
addTitle: 'Insert Link',
label: 'Label',
type: 'Type',
diff --git a/packages/sheets-hyper-link-ui/src/locale/es-ES.ts b/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
index ad52d2a1ea..bedbb55a36 100644
--- a/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Texto de ayuda',
addTitle: 'Insertar enlace',
label: 'Etiqueta',
type: 'Tipo',
diff --git a/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts b/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
index 3b6aac3671..90a3f79508 100644
--- a/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'متن راهنما',
addTitle: 'درج لینک',
label: 'برچسب',
type: 'نوع',
diff --git a/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts b/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
index bba5837f95..fd196382bc 100644
--- a/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Info-bulle',
addTitle: 'Insérer un lien',
label: 'Titre',
type: 'Type',
diff --git a/packages/sheets-hyper-link-ui/src/locale/id-ID.ts b/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
index f3c561cc9e..573b1a477f 100644
--- a/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Teks petunjuk',
addTitle: 'Sisipkan Tautan',
label: 'Label',
type: 'Tipe',
diff --git a/packages/sheets-hyper-link-ui/src/locale/it-IT.ts b/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
index 1233ceb113..55890b581d 100644
--- a/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Suggerimento',
addTitle: 'Inserisci collegamento',
label: 'Etichetta',
type: 'Tipo',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts b/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
index 4e59bd08d8..bfce3a0f5d 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'ヒント',
addTitle: 'リンクの挿入',
label: '表示文字列',
type: '種類',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts b/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
index e3975e4038..412da4ba41 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: '설명',
addTitle: '링크 삽입',
label: '표시 텍스트',
type: '유형',
diff --git a/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts b/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
index 76a6ec476e..22d643ccaf 100644
--- a/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Podpowiedź',
addTitle: 'Wstaw łącze',
label: 'Etykieta',
type: 'Typ',
diff --git a/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts b/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
index 42ef20ce66..8710cb0c35 100644
--- a/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Texto de dica',
addTitle: 'Inserir Link',
label: 'Rótulo',
type: 'Tipo',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts b/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
index 0d8af723e9..1ef3e22b97 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Подсказка',
addTitle: 'Вставить ссылку',
label: 'Метка',
type: 'Тип',
diff --git a/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts b/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
index 277bd7e2f0..64c3306307 100644
--- a/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Pomocný text',
addTitle: 'Vložiť odkaz',
label: 'Popisok',
type: 'Typ',
diff --git a/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts b/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
index 57383d3c98..24f874b2ea 100644
--- a/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: 'Văn bản gợi ý',
addTitle: 'Chèn liên kết',
label: 'Văn bản',
labelPlaceholder: 'Nhập văn bản',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts b/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
index 448959005d..254e17725c 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: '提示文字',
addTitle: '插入链接',
label: '文本',
labelPlaceholder: '输入文本',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts b/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
index ecad8d6f2b..62025525f9 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: '提示文字',
addTitle: '插入連結',
label: '文字',
labelPlaceholder: '輸入文字',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts b/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
index ecad8d6f2b..62025525f9 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-hyper-link-ui': {
form: {
+ tooltip: '提示文字',
addTitle: '插入連結',
label: '文字',
labelPlaceholder: '輸入文字',
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
index 43302cb087..1c207d94ea 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
@@ -65,6 +65,7 @@ import { isBlankInput, resolveRangePayload } from './CellLinkEdit/utils';
export const CellLinkEdit = () => {
const [id, setId] = useState('');
const [display, setDisplay] = useState('');
+ const [tooltip, setTooltip] = useState('');
const [showLabel, setShowLabel] = useState(true);
const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
const [payload, setPayload] = useState('');
@@ -128,6 +129,7 @@ export const CellLinkEdit = () => {
id: customRange?.rangeId ?? '',
display: label ?? '',
payload: customRange?.properties?.url ?? '',
+ tooltip: customRange?.properties?.tooltip ?? customRange?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -145,6 +147,7 @@ export const CellLinkEdit = () => {
id: '',
display: '',
payload: range?.properties?.url ?? '',
+ tooltip: range?.properties?.tooltip ?? range?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -160,6 +163,7 @@ export const CellLinkEdit = () => {
id: '',
display: label ?? '',
payload: customRange?.properties?.url ?? '',
+ tooltip: customRange?.properties?.tooltip ?? customRange?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -167,6 +171,7 @@ export const CellLinkEdit = () => {
}
setId(link.id);
+ setTooltip(link.tooltip);
const customLink = sidePanelService.findCustomHyperLink(link);
if (customLink) {
const customLinkInfo = customLink.convert(link);
@@ -377,6 +382,7 @@ export const CellLinkEdit = () => {
subUnitId: editing.subUnitId,
payload: {
display: showLabel ? display : '',
+ tooltip,
payload: formatUrl(type, payload),
},
row: editing.row,
@@ -394,6 +400,7 @@ export const CellLinkEdit = () => {
column: editing.col,
payload: formatUrl(type, payload),
display: showLabel ? display : '',
+ tooltip,
},
documentId: editorBridgeService.getCurrentEditorId(),
});
@@ -456,6 +463,9 @@ export const CellLinkEdit = () => {
</FormLayout>
)
: null}
+ <FormLayout label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.tooltip')}>
+ <Input value={tooltip} onChange={setTooltip} />
+ </FormLayout>
<FormLayout label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.type')}>
<Select
className="univer-w-full"
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
index 739beeb658..cf4ec8e1ac 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
@@ -65,12 +65,13 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
return null;
}
const linkObj = parserHyperLinkService.parseHyperLink(customRange.properties.url ?? '');
+ const tooltip = customRange.properties.tooltip ?? customRange.properties._xlsxHyperlinkTooltip;
const isError = linkObj.type === SheetHyperLinkType.INVALID;
return (
<div
className={clsx(`
- univer-mb-1 univer-flex univer-max-w-80 univer-flex-row univer-items-center univer-justify-between
+ univer-mb-1 univer-grid univer-max-w-80 univer-grid-cols-[minmax(0,1fr)_auto] univer-items-center
univer-gap-2 univer-overflow-hidden univer-rounded-lg univer-bg-gray-0 univer-p-2 univer-shadow-md
dark:!univer-bg-gray-900
`, borderClassName)}
@@ -192,6 +193,16 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
</>
)}
</div>
+ {typeof tooltip === 'string' && tooltip && (
+ <div
+ className="
+ univer-col-span-2 univer-max-h-32 univer-overflow-y-auto univer-whitespace-pre-wrap
+ univer-break-words univer-text-sm univer-text-gray-500
+ "
+ >
+ {tooltip}
+ </div>
+ )}
</div>
);
};
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
index 58cd909fd1..7ed5f8917d 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
@@ -65,6 +65,7 @@ import { isBlankInput, resolveRangePayload } from './CellLinkEdit/utils';
export const MobileCellLinkEdit = () => {
const [id, setId] = useState('');
const [display, setDisplay] = useState('');
+ const [tooltip, setTooltip] = useState('');
const [showLabel, setShowLabel] = useState(true);
const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
const [payload, setPayload] = useState('');
@@ -128,6 +129,7 @@ export const MobileCellLinkEdit = () => {
id: customRange?.rangeId ?? '',
display: label ?? '',
payload: customRange?.properties?.url ?? '',
+ tooltip: customRange?.properties?.tooltip ?? customRange?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -145,6 +147,7 @@ export const MobileCellLinkEdit = () => {
id: '',
display: '',
payload: range?.properties?.url ?? '',
+ tooltip: range?.properties?.tooltip ?? range?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -160,6 +163,7 @@ export const MobileCellLinkEdit = () => {
id: '',
display: label ?? '',
payload: customRange?.properties?.url ?? '',
+ tooltip: customRange?.properties?.tooltip ?? customRange?.properties?._xlsxHyperlinkTooltip ?? '',
row,
column: col,
};
@@ -167,6 +171,7 @@ export const MobileCellLinkEdit = () => {
}
setId(link.id);
+ setTooltip(link.tooltip);
const customLink = sidePanelService.findCustomHyperLink(link);
if (customLink) {
const customLinkInfo = customLink.convert(link);
@@ -377,6 +382,7 @@ export const MobileCellLinkEdit = () => {
subUnitId: editing.subUnitId,
payload: {
display: showLabel ? display : '',
+ tooltip,
payload: formatUrl(type, payload),
},
row: editing.row,
@@ -394,6 +400,7 @@ export const MobileCellLinkEdit = () => {
column: editing.col,
payload: formatUrl(type, payload),
display: showLabel ? display : '',
+ tooltip,
},
documentId: editorBridgeService.getCurrentEditorId(),
});
@@ -453,6 +460,9 @@ export const MobileCellLinkEdit = () => {
</FormLayout>
)
: null}
+ <FormLayout label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.tooltip')}>
+ <Input value={tooltip} onChange={setTooltip} />
+ </FormLayout>
<FormLayout label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.type')}>
<MobileSelect
className="univer-w-full"
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
index e45b61dbaf..e6c30e64c2 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
@@ -57,6 +57,7 @@ export function MobileCellLinkPopupPure(props: IMobileCellLinkPopupPureProps) {
}
const linkObj = parserHyperLinkService.parseHyperLink(customRange.properties.url);
+ const tooltip = customRange.properties.tooltip ?? customRange.properties._xlsxHyperlinkTooltip;
const isError = linkObj.type === SheetHyperLinkType.INVALID;
const close = () => popupService.hideCurrentPopup(undefined, true);
@@ -74,6 +75,16 @@ export function MobileCellLinkPopupPure(props: IMobileCellLinkPopupPureProps) {
close();
}}
/>
+ {typeof tooltip === 'string' && tooltip && (
+ <div
+ className="
+ univer-max-h-32 univer-overflow-y-auto univer-whitespace-pre-wrap univer-break-words
+ univer-text-sm univer-text-gray-500
+ "
+ >
+ {tooltip}
+ </div>
+ )}
{copyPermission && (
<MobileActionRow
title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
index 956b53316f..ad2a1e9d2a 100644
--- a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
@@ -57,7 +57,10 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { of } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
-import { CloseHyperLinkPopupOperation, OpenHyperLinkEditPanelOperation } from '../../commands/operations/popup.operations';
+import {
+ CloseHyperLinkPopupOperation,
+ OpenHyperLinkEditPanelOperation,
+} from '../../commands/operations/popup.operations';
import { ISheetsHyperLinkPopupService, SheetsHyperLinkPopupService } from '../../services/popup.service';
import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
@@ -395,6 +398,22 @@ describe('CellLinkPopupPure', () => {
currentTestBed = undefined;
});
+ it.each([CellLinkPopupPure, MobileCellLinkPopupPure])('renders the tip inside the existing link card', (Popup) => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const customRange = { ...currentTestBed.customRange, properties: { ...currentTestBed.customRange.properties, tooltip: '<b>Read this first</b>' } };
+ act(() => root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <Popup unitId={UNIT_ID} subUnitId={SUB_UNIT_ID} row={0} col={0} customRange={customRange} type={HyperLinkEditSourceType.VIEWING} editPermission copyPermission />
+ </RediContext.Provider>
+ ));
+ expect(container.textContent).toContain('<b>Read this first</b>');
+ expect(container.querySelector('b')).toBeNull();
+ expect(container.firstElementChild?.textContent).toContain('<b>Read this first</b>');
+ });
+
it('opens the edit panel for the selected sheet hyperlink range', async () => {
currentTestBed = createPopupTestBed();
container = document.createElement('div');
@@ -514,9 +533,10 @@ describe('CellLinkEdit', () => {
});
const inputs = Array.from(container.querySelectorAll('input'));
- expect(inputs).toHaveLength(2);
+ expect(inputs).toHaveLength(3);
expect(inputs[0].hasAttribute('dir')).toBe(false);
- expect(inputs[1].dir).toBe('ltr');
+ expect(inputs[1].hasAttribute('dir')).toBe(false);
+ expect(inputs[2].dir).toBe('ltr');
}
});
@@ -544,10 +564,11 @@ describe('CellLinkEdit', () => {
});
const inputs = Array.from(container.querySelectorAll('input'));
- expect(inputs).toHaveLength(1);
+ expect(inputs).toHaveLength(2);
await act(async () => {
- inputText(inputs[0], 'docs.univer.ai');
+ inputText(inputs[0], 'Documentation tip');
+ inputText(inputs[1], 'docs.univer.ai');
await Promise.resolve();
});
renderManagerService.enableScrollRender = true;
@@ -567,6 +588,7 @@ describe('CellLinkEdit', () => {
expect(body?.dataStream).toBe('Univer\r\n');
expect(linkRange?.properties?.url).toBe('http://docs.univer.ai');
+ expect(linkRange?.properties?.tooltip).toBe('Documentation tip');
expect(popupService.currentEditing).toBeNull();
});
diff --git a/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
index 43e0e4b54f..914a7eee0f 100644
--- a/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
+++ b/packages/sheets-hyper-link/src/commands/commands/add-hyper-link.command.ts
@@ -17,9 +17,26 @@
import type { ICellData, ICommand, IDocumentData, IMutationInfo } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ISheetHyperLink } from '../../types/interfaces/i-hyper-link';
-import { BuildTextUtils, CellValueType, CommandType, CustomRangeType, generateRandomId, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute, TextX, Tools } from '@univerjs/core';
+import {
+ BuildTextUtils,
+ CellValueType,
+ CommandType,
+ CustomRangeType,
+ generateRandomId,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ sequenceExecute,
+ TextX,
+ Tools,
+} from '@univerjs/core';
import { addCustomRangeBySelectionFactory } from '@univerjs/docs';
-import { getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
+import {
+ getSheetCommandTarget,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+ SheetInterceptorService,
+} from '@univerjs/sheets';
import { HyperLinkModel } from '../../models/hyper-link.model';
import { AddHyperLinkMutation } from '../mutations/add-hyper-link.mutation';
import { RemoveHyperLinkMutation } from '../mutations/remove-hyper-link.mutation';
@@ -36,7 +53,6 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
type: CommandType.COMMAND,
id: 'sheets.command.add-hyper-link',
- // eslint-disable-next-line max-lines-per-function
async handler(accessor, params) {
if (!params) return false;
@@ -76,6 +92,7 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
rangeId: id,
properties: {
url: payload,
+ tooltip: link.tooltip,
// refId: id,
},
}],
@@ -90,6 +107,7 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {
rangeType: CustomRangeType.HYPERLINK,
properties: {
url: payload,
+ tooltip: link.tooltip,
refId: id,
},
});
@@ -196,6 +214,7 @@ export const AddRichHyperLinkCommand: ICommand<IAddRichHyperLinkCommandParams> =
rangeType: CustomRangeType.HYPERLINK,
properties: {
url: payload,
+ tooltip: link.tooltip,
refId: newId,
},
});
diff --git a/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
index 39e0822ac5..9a846b4d97 100644
--- a/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
+++ b/packages/sheets-hyper-link/src/commands/commands/update-hyper-link.command.ts
@@ -16,9 +16,27 @@
import type { DocumentDataModel, ICellData, ICommand, IMutationInfo } from '@univerjs/core';
import type { ICellLinkContent } from '../../types/interfaces/i-hyper-link';
-import { CellValueType, CommandType, CustomRangeType, generateRandomId, getBodySlice, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute, TextX, Tools, UniverInstanceType } from '@univerjs/core';
+import {
+ CellValueType,
+ CommandType,
+ CustomRangeType,
+ generateRandomId,
+ getBodySlice,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ sequenceExecute,
+ TextX,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
import { replaceSelectionFactory } from '@univerjs/docs';
-import { getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
+import {
+ getSheetCommandTarget,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+ SheetInterceptorService,
+} from '@univerjs/sheets';
import { HyperLinkModel } from '../../models/hyper-link.model';
import { AddHyperLinkMutation } from '../mutations/add-hyper-link.mutation';
import { RemoveHyperLinkMutation } from '../mutations/remove-hyper-link.mutation';
@@ -35,7 +53,6 @@ export interface IUpdateHyperLinkCommandParams {
export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {
type: CommandType.COMMAND,
id: 'sheets.command.update-hyper-link',
- // eslint-disable-next-line max-lines-per-function
async handler(accessor, params) {
if (!params) return false;
@@ -84,6 +101,7 @@ export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {
endIndex: display.length - 1,
properties: {
url: payload,
+ tooltip: link.tooltip ?? range.properties?.tooltip ?? range.properties?._xlsxHyperlinkTooltip,
},
}],
textRuns: textRun ? [textRun] : undefined,
@@ -211,6 +229,7 @@ export const UpdateRichHyperLinkCommand: ICommand<IUpdateRichHyperLinkCommandPar
endIndex: display.length - 1,
properties: {
url: payload.payload,
+ tooltip: payload.tooltip ?? range.properties?.tooltip ?? range.properties?._xlsxHyperlinkTooltip,
},
}],
textRuns: textRun ? [textRun] : undefined,
diff --git a/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts b/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts
index 428df0ece1..fdcb385a0c 100644
--- a/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts
@@ -15,7 +15,17 @@
*/
import type { IWorkbookData, UnitModel } from '@univerjs/core';
-import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ ICommandService,
+ ILogService,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ RedoCommand,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
import { DocSelectionManagerService } from '@univerjs/docs';
import { IDefinedNamesService } from '@univerjs/engine-formula';
@@ -66,6 +76,23 @@ describe('FRangeSheetsHyperlinkMixin', () => {
univer.dispose();
});
+ it('persists, preserves and clears hyperlink tips through undoable facade edits', async () => {
+ const cell = univerAPI.getActiveWorkbook()!.getActiveSheet().getRange('A1');
+ await expect(cell.setHyperLink('https://univer.ai', 'Original', 'Imported tip')).resolves.toBe(true);
+ expect(cell.getHyperLinks()[0].tooltip).toBe('Imported tip');
+ await cell.updateHyperLink('https://docs.univer.ai', 'Edited');
+ expect(cell.getHyperLinks()[0]).toMatchObject({ label: 'Edited', tooltip: 'Imported tip' });
+ await cell.updateHyperLink('https://docs.univer.ai', undefined, '');
+ expect(cell.getHyperLinks()[0]).toMatchObject({ label: 'Edited', tooltip: '' });
+ const commands = univer.__getInjector().get(ICommandService);
+ await commands.executeCommand(UndoCommand.id);
+ expect(cell.getHyperLinks()[0].tooltip).toBe('Imported tip');
+ await commands.executeCommand(RedoCommand.id);
+ expect(cell.getHyperLinks()[0].tooltip).toBe('');
+ const body = cell.getCellData()?.p?.body;
+ expect(JSON.parse(JSON.stringify(body)).customRanges[0].properties.tooltip).toBe('');
+ });
+
it('should set, read, update and cancel hyperlinks through the real facade API', async () => {
const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
const a1 = worksheet.getRange('A1');
diff --git a/packages/sheets-hyper-link/src/facade/f-range.ts b/packages/sheets-hyper-link/src/facade/f-range.ts
index f351d716ce..a54ed2e1a1 100644
--- a/packages/sheets-hyper-link/src/facade/f-range.ts
+++ b/packages/sheets-hyper-link/src/facade/f-range.ts
@@ -14,9 +14,18 @@
* limitations under the License.
*/
-import type { IAddHyperLinkCommandParams, ICancelHyperLinkCommandParams, IUpdateHyperLinkCommandParams } from '@univerjs/sheets-hyper-link';
+import type {
+ IAddHyperLinkCommandParams,
+ ICancelHyperLinkCommandParams,
+ IUpdateHyperLinkCommandParams,
+} from '@univerjs/sheets-hyper-link';
import { CustomRangeType, DataStreamTreeTokenType, generateRandomId } from '@univerjs/core';
-import { AddHyperLinkCommand, CancelHyperLinkCommand, SheetsHyperLinkParserService, UpdateHyperLinkCommand } from '@univerjs/sheets-hyper-link';
+import {
+ AddHyperLinkCommand,
+ CancelHyperLinkCommand,
+ SheetsHyperLinkParserService,
+ UpdateHyperLinkCommand,
+} from '@univerjs/sheets-hyper-link';
import { FRange } from '@univerjs/sheets/facade';
export interface ICellHyperLink {
@@ -25,6 +34,7 @@ export interface ICellHyperLink {
column: number;
url: string;
label: string;
+ tooltip?: string;
}
/**
@@ -37,6 +47,7 @@ export interface IFRangeSheetsHyperlinkMixin {
* When the hyperlink is a range link or a sheet link, the url should be the url of the target range or sheet.
* @param {string} url - The hyperlink url, can be a URL, a range link, or a sheet link.
* @param {string} [label] - The display text of the hyperlink. If omitted, the existing cell text is linked. Supply a label when linking an empty cell.
+ * @param {string} [tooltip] - Optional text shown inside the hyperlink popup.
* @return {Promise<boolean>} A promise that resolves to true if the hyperlink is set successfully, otherwise false.
*
* @example
@@ -68,7 +79,7 @@ export interface IFRangeSheetsHyperlinkMixin {
* await fRange4.setHyperLink(definedNameHyperlinkUrl, 'Link to MyDefinedName');
* ```
*/
- setHyperLink(url: string, label?: string): Promise<boolean>;
+ setHyperLink(url: string, label?: string, tooltip?: string): Promise<boolean>;
/**
* Gets the first hyperlink from each cell containing hyperlinks in this range.
@@ -87,7 +98,8 @@ export interface IFRangeSheetsHyperlinkMixin {
/**
* Update the hyperlink of this range top left cell.
* @param {string} url - The new hyperlink url, can be a URL, a range link, or a sheet link.
- * @param {string} [label] - The new display text of the hyperlink. If omitted, the replacement display text is empty. Supply a label to keep the link visible.
+ * @param {string} [label] - The new display text of the hyperlink. If omitted, the existing hyperlink label is preserved.
+ * @param {string} [tooltip] - Omit to preserve the current tooltip; use an empty string to clear it.
*
* @returns {Promise<boolean>} A promise resolving to whether the update succeeded.
* @throws {Error} The promise rejects if the top-left cell contains no hyperlink.
@@ -108,7 +120,7 @@ export interface IFRangeSheetsHyperlinkMixin {
* await fRange.updateHyperLink(rangeUrl, 'Link to B2:D4');
* ```
*/
- updateHyperLink(url: string, label?: string): Promise<boolean>;
+ updateHyperLink(url: string, label?: string, tooltip?: string): Promise<boolean>;
/**
* Cancel all hyperlinks in this range. If a hyperlink is provided, only cancel the specified hyperlink.
@@ -157,7 +169,7 @@ export interface IFRangeSheetsHyperlinkMixin {
}
export class FRangeSheetsHyperlinkMixin extends FRange implements IFRangeSheetsHyperlinkMixin {
- override setHyperLink(url: string, label?: string): Promise<boolean> {
+ override setHyperLink(url: string, label?: string, tooltip?: string): Promise<boolean> {
return this._commandService.executeCommand<IAddHyperLinkCommandParams>(AddHyperLinkCommand.id, {
unitId: this.getUnitId(),
subUnitId: this._worksheet.getSheetId(),
@@ -167,6 +179,7 @@ export class FRangeSheetsHyperlinkMixin extends FRange implements IFRangeSheetsH
column: this._range.startColumn,
payload: url,
display: label,
+ tooltip,
},
});
}
@@ -193,6 +206,7 @@ export class FRangeSheetsHyperlinkMixin extends FRange implements IFRangeSheetsH
column,
url,
label,
+ tooltip: properties?.tooltip ?? properties?._xlsxHyperlinkTooltip,
});
}
});
@@ -200,7 +214,7 @@ export class FRangeSheetsHyperlinkMixin extends FRange implements IFRangeSheetsH
return hyperlinks;
}
- override updateHyperLink(url: string, label?: string): Promise<boolean> {
+ override updateHyperLink(url: string, label?: string, tooltip?: string): Promise<boolean> {
const hyperlink = this.getHyperLinks().find((link) => link.row === this._range.startRow && link.column === this._range.startColumn);
if (!hyperlink) {
@@ -217,7 +231,8 @@ export class FRangeSheetsHyperlinkMixin extends FRange implements IFRangeSheetsH
column,
payload: {
payload: url,
- display: label,
+ display: label ?? hyperlink.label,
+ tooltip,
},
});
}
diff --git a/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts b/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts
index df37cf810d..d0360cd9c1 100644
--- a/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts
+++ b/packages/sheets-hyper-link/src/types/interfaces/i-hyper-link.ts
@@ -23,6 +23,8 @@ export interface ICellLinkContent {
* file: file://a.xlsx
*/
payload: string;
+ /** Optional text shown inside the hyperlink popup. Empty string clears it on update. */
+ tooltip?: string;
/**
* only for notify, if you wan't to read the display of text, use cell-value of cell-matrix instead
*/
diff --git a/packages/sheets-table-ui/src/const.ts b/packages/sheets-table-ui/src/const.ts
index c7abf752bd..72fa068ec1 100644
--- a/packages/sheets-table-ui/src/const.ts
+++ b/packages/sheets-table-ui/src/const.ts
@@ -21,6 +21,8 @@ export const UNIVER_SHEET_TABLE_FILTER_PANEL_ID = 'UNIVER_SHEET_Table_FILTER_PAN
export const TABLE_SELECTOR_DIALOG = 'TABLE_SELECTOR_DIALOG';
export const SHEET_TABLE_RENAME_DIALOG = 'SHEET_TABLE_RENAME_DIALOG';
export const SHEET_TABLE_RENAME_DIALOG_ID = 'SHEET_TABLE_RENAME_DIALOG_ID';
+export const SHEET_TABLE_SETTINGS_DIALOG = 'SHEET_TABLE_SETTINGS_DIALOG';
+export const SHEET_TABLE_SETTINGS_DIALOG_ID = 'SHEET_TABLE_SETTINGS_DIALOG_ID';
export const SHEET_TABLE_THEME_PANEL_ID = 'SHEET_TABLE_THEME_PANEL_ID';
export const SHEET_TABLE_THEME_PANEL = 'SHEET_TABLE_THEME_PANEL';
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
index 931f9c6103..ddbb6c0457 100644
--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
@@ -184,6 +184,7 @@ describe('SheetTableControlsRenderController', () => {
rename: 'sheets-table-ui.rename',
'update-range': 'sheets-table-ui.updateRange',
'set-theme': 'sheets-table-ui.setTheme',
+ settings: 'sheets-table-ui.settings',
delete: 'sheets-table-ui.removeTable',
});
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
index 6bd626a783..a8897dd7a5 100644
--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
@@ -128,14 +128,14 @@ describe('SheetsTableFilterButtonRenderController', () => {
endRow: 8,
startColumn: 2,
endColumn: 4,
- });
+ }, new Set([2, 4]));
const rawCell = { v: 'Header', fontRenderExtension: { leftOffset: 3 } };
const headerResult = interceptor.handler(rawCell, {
unitId: 'u1',
subUnitId: 's1',
row: 4,
- col: 3,
+ col: 2,
rawData: rawCell,
}, (cell: unknown) => cell);
@@ -146,6 +146,13 @@ describe('SheetsTableFilterButtonRenderController', () => {
});
const bodyCell = { v: 'Body' };
+ expect(interceptor.handler(bodyCell, {
+ unitId: 'u1',
+ subUnitId: 's1',
+ row: 4,
+ col: 3,
+ rawData: bodyCell,
+ }, (cell: unknown) => cell)).toBe(bodyCell);
expect(interceptor.handler(bodyCell, {
unitId: 'u1',
subUnitId: 's1',
diff --git a/packages/sheets-table-ui/src/controllers/components.controller.ts b/packages/sheets-table-ui/src/controllers/components.controller.ts
index 08b0e8cf9d..58a27aa4cd 100644
--- a/packages/sheets-table-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/components.controller.ts
@@ -20,6 +20,7 @@ import { ComponentManager, IconManager } from '@univerjs/ui';
import {
SHEET_TABLE_MENU,
SHEET_TABLE_RENAME_DIALOG,
+ SHEET_TABLE_SETTINGS_DIALOG,
SHEET_TABLE_THEME_PANEL,
SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,
TABLE_SELECTOR_DIALOG,
@@ -28,6 +29,7 @@ import { SheetTableFilterPanel } from '../views/components/SheetTableFilterPanel
import { SheetTableMenu } from '../views/components/SheetTableMenu';
import { SheetTableRenameDialog } from '../views/components/SheetTableRenameDialog';
import { SheetTableSelector } from '../views/components/SheetTableSelector';
+import { SheetTableSettingsDialog } from '../views/components/SheetTableSettingsDialog';
import { SheetTableThemePanel } from '../views/components/SheetTableThemePanel';
export class ComponentsController extends Disposable {
@@ -46,6 +48,7 @@ export class ComponentsController extends Disposable {
[SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, SheetTableFilterPanel],
[SHEET_TABLE_MENU, SheetTableMenu],
[SHEET_TABLE_RENAME_DIALOG, SheetTableRenameDialog],
+ [SHEET_TABLE_SETTINGS_DIALOG, SheetTableSettingsDialog],
] as const).forEach(([key, comp]) => {
this.disposeWithMe(this._componentManager.register(key, comp));
});
diff --git a/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts
index 65f1106137..7f4468702b 100644
--- a/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts
@@ -20,6 +20,7 @@ import { ComponentManager, IconManager } from '@univerjs/ui';
import {
SHEET_TABLE_MOBILE_MENU,
SHEET_TABLE_RENAME_DIALOG,
+ SHEET_TABLE_SETTINGS_DIALOG,
SHEET_TABLE_THEME_PANEL,
SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,
TABLE_SELECTOR_DIALOG,
@@ -28,6 +29,7 @@ import { MobileSheetTableFilterPanel } from '../../views/components/MobileSheetT
import { MobileSheetTableMenu } from '../../views/components/MobileSheetTableMenu';
import { MobileSheetTableRenameDialog } from '../../views/components/MobileSheetTableRenameDialog';
import { MobileSheetTableSelector } from '../../views/components/MobileSheetTableSelector';
+import { MobileSheetTableSettingsDialog } from '../../views/components/MobileSheetTableSettingsDialog';
import { MobileSheetTableThemePanel } from '../../views/components/MobileSheetTableThemePanel';
export class MobileComponentsController extends Disposable {
@@ -41,6 +43,7 @@ export class MobileComponentsController extends Disposable {
[SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, MobileSheetTableFilterPanel],
[SHEET_TABLE_MOBILE_MENU, MobileSheetTableMenu],
[SHEET_TABLE_RENAME_DIALOG, MobileSheetTableRenameDialog],
+ [SHEET_TABLE_SETTINGS_DIALOG, MobileSheetTableSettingsDialog],
[TABLE_SELECTOR_DIALOG, MobileSheetTableSelector],
[SHEET_TABLE_THEME_PANEL, MobileSheetTableThemePanel],
] as const).forEach(([key, component]) => {
diff --git a/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts
index 8d49cce406..7a42527c85 100644
--- a/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts
@@ -44,6 +44,7 @@ export class SheetTableControlsMobileRenderController extends SheetTableControls
rename: this._localeService.t<LocaleKey>('sheets-table-ui.rename'),
'update-range': this._localeService.t<LocaleKey>('sheets-table-ui.updateRange'),
'set-theme': this._localeService.t<LocaleKey>('sheets-table-ui.setTheme'),
+ settings: this._localeService.t<LocaleKey>('sheets-table-ui.settings'),
delete: this._localeService.t<LocaleKey>('sheets-table-ui.removeTable'),
},
onSelect: (action: SheetTableMenuAction) => this._handleTableMenuAction(action, unitId, subUnitId, tableId),
diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
index 13ef99750b..71874e300c 100644
--- a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
@@ -72,6 +72,8 @@ import {
SHEET_TABLE_MENU,
SHEET_TABLE_RENAME_DIALOG,
SHEET_TABLE_RENAME_DIALOG_ID,
+ SHEET_TABLE_SETTINGS_DIALOG,
+ SHEET_TABLE_SETTINGS_DIALOG_ID,
SHEET_TABLE_THEME_PANEL,
SHEET_TABLE_THEME_PANEL_ID,
} from '../const';
@@ -107,6 +109,7 @@ export class SheetTableControlsRenderController extends Disposable implements IR
protected readonly _shape: SheetTableControlsShape;
private readonly _topGapBaseBySkeleton = new WeakMap<SpreadsheetSkeleton, TopGapSnapshot>();
protected _menuPopup: IDisposable | null = null;
+ private _settingsDialog: IDisposable | null = null;
constructor(
private readonly _context: IRenderContext<Workbook>,
@@ -140,6 +143,8 @@ export class SheetTableControlsRenderController extends Disposable implements IR
this._context.scene.addObjects([this._shape], TABLE_CONTROLS_LAYER_INDEX);
this.disposeWithMe(toDisposable(() => {
this._closeFloatingControls();
+ this._settingsDialog?.dispose();
+ this._settingsDialog = null;
this._context.scene.removeObjects([this._shape]);
}));
@@ -346,6 +351,7 @@ export class SheetTableControlsRenderController extends Disposable implements IR
rename: this._localeService.t<LocaleKey>('sheets-table-ui.rename'),
'update-range': this._localeService.t<LocaleKey>('sheets-table-ui.updateRange'),
'set-theme': this._localeService.t<LocaleKey>('sheets-table-ui.setTheme'),
+ settings: this._localeService.t<LocaleKey>('sheets-table-ui.settings'),
delete: this._localeService.t<LocaleKey>('sheets-table-ui.removeTable'),
},
onSelect: (action: SheetTableMenuAction) => this._handleTableMenuAction(action, unitId, subUnitId, tableId),
@@ -381,6 +387,9 @@ export class SheetTableControlsRenderController extends Disposable implements IR
this._closeFloatingControls();
switch (action) {
+ case 'settings':
+ this._openSettingsDialog(unitId, tableId);
+ break;
case 'rename':
this._openRenameDialog(unitId, tableId);
break;
@@ -399,6 +408,29 @@ export class SheetTableControlsRenderController extends Disposable implements IR
}
}
+ private _openSettingsDialog(unitId: string, tableId: string): void {
+ this._settingsDialog?.dispose();
+ this._dialogService.open({
+ id: SHEET_TABLE_SETTINGS_DIALOG_ID,
+ title: { title: this._localeService.t<LocaleKey>('sheets-table-ui.settings') },
+ draggable: true,
+ mask: true,
+ children: {
+ label: {
+ name: SHEET_TABLE_SETTINGS_DIALOG,
+ props: {
+ unitId,
+ tableId,
+ onClose: () => this._dialogService.close(SHEET_TABLE_SETTINGS_DIALOG_ID),
+ },
+ },
+ },
+ width: 400,
+ onClose: () => this._dialogService.close(SHEET_TABLE_SETTINGS_DIALOG_ID),
+ });
+ this._settingsDialog = toDisposable(() => this._dialogService.close(SHEET_TABLE_SETTINGS_DIALOG_ID));
+ }
+
private _openRenameDialog(unitId: string, tableId: string): void {
this._dialogService.open({
id: SHEET_TABLE_RENAME_DIALOG_ID,
diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts
index 411b46215d..26e12ed109 100644
--- a/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts
@@ -16,14 +16,23 @@
import type { ICommandInfo, IDisposable, IRange, Workbook } from '@univerjs/core';
import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ITableRangeWithState } from '@univerjs/sheets-table';
+import type { ISetSheetTableMutationParams, ITableRangeWithState } from '@univerjs/sheets-table';
import type { ISheetsTableFilterButtonShapeProps } from '../views/widgets/table-filter-button.shape';
import { ICommandService, Inject, Injector, InterceptorEffectEnum, RxDisposable, VerticalAlign } from '@univerjs/core';
-import { INTERCEPTOR_POINT, SetVerticalTextAlignCommand, SheetInterceptorService, SheetRangeThemeModel } from '@univerjs/sheets';
-import { TableManager } from '@univerjs/sheets-table';
+import {
+ INTERCEPTOR_POINT,
+ SetVerticalTextAlignCommand,
+ SheetInterceptorService,
+ SheetRangeThemeModel,
+} from '@univerjs/sheets';
+import { SetSheetTableMutation, TableManager } from '@univerjs/sheets-table';
import { getCoordByCell, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { map, merge, of, startWith, switchMap, takeUntil } from 'rxjs';
-import { FILTER_ICON_PADDING, FILTER_ICON_SIZE, SheetsTableFilterButtonShape } from '../views/widgets/table-filter-button.shape';
+import {
+ FILTER_ICON_PADDING,
+ FILTER_ICON_SIZE,
+ SheetsTableFilterButtonShape,
+} from '../views/widgets/table-filter-button.shape';
const SHEETS_FILTER_BUTTON_Z_INDEX = 5000;
@@ -119,9 +128,16 @@ export class SheetsTableFilterButtonRenderController extends RxDisposable implem
private _initCommandExecuted() {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (command.id !== SetVerticalTextAlignCommand.id) {
+ if (command.id !== SetVerticalTextAlignCommand.id && command.id !== SetSheetTableMutation.id) {
return;
}
+ if (command.id === SetSheetTableMutation.id) {
+ const params = command.params as ISetSheetTableMutationParams | undefined;
+ if (!params?.config.filterButtons || params.unitId !== this._context.unitId
+ || params.subUnitId !== this._context.unit.getActiveSheet()?.getSheetId()) {
+ return;
+ }
+ }
const { unit: workbook, unitId } = this._context;
const worksheetId = workbook.getActiveSheet()?.getSheetId() || '';
@@ -160,8 +176,17 @@ export class SheetsTableFilterButtonRenderController extends RxDisposable implem
const headerStyle = table ? this._rangeThemeModel.getRangeThemeStyle(unitId, table.getTableStyleId())?.getHeaderRowStyle() : null;
const iconColor = headerStyle?.cl?.rgb ?? '#fff';
const hoverIconColor = headerStyle?.bg?.rgb ?? '#202124';
- this._interceptCellContent(unitId, worksheetId, range);
+ const visibleColumns = new Set<number>();
+ for (let col = startColumn; col <= endColumn; col++) {
+ if (table?.getTableColumnByIndex(col - startColumn)?.isShowFilterButton() !== false) {
+ visibleColumns.add(col);
+ }
+ }
+ this._interceptCellContent(unitId, worksheetId, range, visibleColumns);
for (let col = startColumn; col <= endColumn; col++) {
+ if (!visibleColumns.has(col)) {
+ continue;
+ }
const key = `sheets-table-filter-button-${startRow}-${col}`;
const startPosition = getCoordByCell(startRow, col, scene, skeleton);
const cellStyle = worksheet.getCellStyle(startRow, col);
@@ -197,7 +222,7 @@ export class SheetsTableFilterButtonRenderController extends RxDisposable implem
scene.makeDirty();
}
- private _interceptCellContent(workbookId: string, worksheetId: string, range: IRange): void {
+ private _interceptCellContent(workbookId: string, worksheetId: string, range: IRange, visibleColumns: Set<number>): void {
const { startRow, startColumn, endColumn } = range;
this._buttonRenderDisposable = this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
effect: InterceptorEffectEnum.Style,
@@ -208,7 +233,8 @@ export class SheetsTableFilterButtonRenderController extends RxDisposable implem
subUnitId !== worksheetId ||
row !== startRow ||
col < startColumn ||
- col > endColumn
+ col > endColumn ||
+ !visibleColumns.has(col)
) {
return next(cell);
}
diff --git a/packages/sheets-table-ui/src/locale/ar-SA.ts b/packages/sheets-table-ui/src/locale/ar-SA.ts
index 4434770720..83c4bd8ac7 100644
--- a/packages/sheets-table-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-table-ui/src/locale/ar-SA.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'عمود محسوب',
+ columnFormula: 'الصيغة',
+ columnFormulaHint: 'يستبدل فورًا {0} خلية بيانات دون الرأس والإجمالي. إيقاف التعبئة يحافظ على الخلايا الحالية. يمكن التراجع.',
+ applyColumnFormula: 'تطبيق على العمود بالكامل',
+ stopColumnFormula: 'إيقاف التعبئة التلقائية',
+ columnFormulaApplied: 'تم تطبيق إعداد العمود',
+ settings: 'إعدادات الجدول',
+ showFilterButtons: 'إظهار أزرار التصفية',
+ columnFilterButtons: 'أزرار تصفية الأعمدة',
+ filterButtonsHint: 'يؤدي إخفاء الأزرار إلى الاحتفاظ بمعايير التصفية الحالية.',
+ settingsError: 'تعذر الحفظ. ربما تغير الجدول. أعد فتح الإعدادات وحاول مجددًا.',
title: 'جدول',
selectRange: 'حدد نطاق الجدول',
rename: 'إعادة تسمية الجدول',
diff --git a/packages/sheets-table-ui/src/locale/ca-ES.ts b/packages/sheets-table-ui/src/locale/ca-ES.ts
index 5a16f07407..a181f7cfc0 100644
--- a/packages/sheets-table-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-table-ui/src/locale/ca-ES.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Columna calculada',
+ columnFormula: 'Fórmula',
+ columnFormulaHint: 'Substitueix immediatament les {0} cel·les de dades, sense capçalera ni totals. Aturar conserva les cel·les existents. Es pot desfer.',
+ applyColumnFormula: 'Aplica a tota la columna',
+ stopColumnFormula: 'Atura l’emplenament automàtic',
+ columnFormulaApplied: 'Configuració aplicada',
+ settings: 'Configuració de taula',
+ showFilterButtons: 'Mostra els botons de filtre',
+ columnFilterButtons: 'Botons de filtre per columna',
+ filterButtonsHint: 'Amagar els botons conserva els criteris de filtre existents.',
+ settingsError: 'No s’ha pogut desar. La taula pot haver canviat. Torneu a obrir la configuració.',
title: 'Taula',
selectRange: 'Selecciona el rang de la taula',
rename: 'Reanomena la taula',
diff --git a/packages/sheets-table-ui/src/locale/de-DE.ts b/packages/sheets-table-ui/src/locale/de-DE.ts
index ab3ccfaaea..06cdac32aa 100644
--- a/packages/sheets-table-ui/src/locale/de-DE.ts
+++ b/packages/sheets-table-ui/src/locale/de-DE.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Berechnete Spalte',
+ columnFormula: 'Formel',
+ columnFormulaHint: 'Ersetzt sofort alle {0} Datenzellen ohne Kopf- und Ergebniszeile. Beim Stoppen bleiben vorhandene Zellen erhalten. Rückgängig möglich.',
+ applyColumnFormula: 'Auf ganze Spalte anwenden',
+ stopColumnFormula: 'Automatisches Ausfüllen stoppen',
+ columnFormulaApplied: 'Spalteneinstellung angewendet',
+ settings: 'Tabelleneinstellungen',
+ showFilterButtons: 'Filterschaltflächen anzeigen',
+ columnFilterButtons: 'Filterschaltflächen der Spalten',
+ filterButtonsHint: 'Beim Ausblenden bleiben vorhandene Filterkriterien erhalten.',
+ settingsError: 'Speichern fehlgeschlagen. Die Tabelle wurde möglicherweise geändert. Öffnen Sie die Einstellungen erneut.',
title: 'Tabelle',
selectRange: 'Tabellenbereich auswählen',
rename: 'Tabelle umbenennen',
diff --git a/packages/sheets-table-ui/src/locale/en-US.ts b/packages/sheets-table-ui/src/locale/en-US.ts
index 0425033707..f47c9d8615 100644
--- a/packages/sheets-table-ui/src/locale/en-US.ts
+++ b/packages/sheets-table-ui/src/locale/en-US.ts
@@ -16,6 +16,17 @@
const locale = {
'sheets-table-ui': {
+ calculatedColumn: 'Calculated column',
+ columnFormula: 'Formula',
+ columnFormulaHint: 'Apply replaces all {0} data cells in this column immediately. Header and footer are excluded. Stop preserves existing cells. Changes can be undone.',
+ applyColumnFormula: 'Apply to entire column',
+ stopColumnFormula: 'Stop automatic fill',
+ columnFormulaApplied: 'Column setting applied',
+ settings: 'Table Settings',
+ showFilterButtons: 'Show filter buttons',
+ columnFilterButtons: 'Column filter buttons',
+ filterButtonsHint: 'Hiding buttons keeps existing filter criteria.',
+ settingsError: 'Unable to save. The table may have changed. Reopen settings and try again.',
title: 'Table',
selectRange: 'Select Table Range',
rename: 'Rename Table',
diff --git a/packages/sheets-table-ui/src/locale/es-ES.ts b/packages/sheets-table-ui/src/locale/es-ES.ts
index 54d0087d5f..8b01dd9c9d 100644
--- a/packages/sheets-table-ui/src/locale/es-ES.ts
+++ b/packages/sheets-table-ui/src/locale/es-ES.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Columna calculada',
+ columnFormula: 'Fórmula',
+ columnFormulaHint: 'Reemplaza inmediatamente las {0} celdas de datos, sin encabezado ni totales. Detener conserva las celdas existentes. Se puede deshacer.',
+ applyColumnFormula: 'Aplicar a toda la columna',
+ stopColumnFormula: 'Detener relleno automático',
+ columnFormulaApplied: 'Configuración aplicada',
+ settings: 'Configuración de tabla',
+ showFilterButtons: 'Mostrar botones de filtro',
+ columnFilterButtons: 'Botones de filtro por columna',
+ filterButtonsHint: 'Ocultar los botones conserva los criterios de filtro existentes.',
+ settingsError: 'No se pudo guardar. La tabla puede haber cambiado. Vuelva a abrir la configuración.',
title: 'Tabla',
selectRange: 'Seleccionar rango de tabla',
rename: 'Renombrar tabla',
diff --git a/packages/sheets-table-ui/src/locale/fa-IR.ts b/packages/sheets-table-ui/src/locale/fa-IR.ts
index dd856ffcc5..63a73667b6 100644
--- a/packages/sheets-table-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-table-ui/src/locale/fa-IR.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'ستون محاسباتی',
+ columnFormula: 'فرمول',
+ columnFormulaHint: 'بلافاصله {0} سلول داده را بدون سربرگ و جمع جایگزین می‌کند. توقف، سلول‌های موجود را حفظ می‌کند. قابل واگرد است.',
+ applyColumnFormula: 'اعمال به کل ستون',
+ stopColumnFormula: 'توقف پرکردن خودکار',
+ columnFormulaApplied: 'تنظیم ستون اعمال شد',
+ settings: 'تنظیمات جدول',
+ showFilterButtons: 'نمایش دکمه‌های فیلتر',
+ columnFilterButtons: 'دکمه‌های فیلتر ستون‌ها',
+ filterButtonsHint: 'پنهان کردن دکمه‌ها معیارهای فیلتر موجود را حفظ می‌کند.',
+ settingsError: 'ذخیره نشد. ممکن است جدول تغییر کرده باشد. تنظیمات را دوباره باز کنید.',
title: 'جدول',
selectRange: 'انتخاب محدوده جدول',
rename: 'تغییر نام جدول',
diff --git a/packages/sheets-table-ui/src/locale/fr-FR.ts b/packages/sheets-table-ui/src/locale/fr-FR.ts
index eb666b6923..5e85c857a9 100644
--- a/packages/sheets-table-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-table-ui/src/locale/fr-FR.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Colonne calculée',
+ columnFormula: 'Formule',
+ columnFormulaHint: 'Remplace immédiatement les {0} cellules de données, hors en-tête et total. Arrêter conserve les cellules existantes. Annulation possible.',
+ applyColumnFormula: 'Appliquer à toute la colonne',
+ stopColumnFormula: 'Arrêter le remplissage automatique',
+ columnFormulaApplied: 'Paramètre appliqué',
+ settings: 'Paramètres du tableau',
+ showFilterButtons: 'Afficher les boutons de filtre',
+ columnFilterButtons: 'Boutons de filtre des colonnes',
+ filterButtonsHint: 'Masquer les boutons conserve les critères de filtre existants.',
+ settingsError: 'Enregistrement impossible. Le tableau a peut-être changé. Rouvrez les paramètres et réessayez.',
title: 'Tableau',
selectRange: 'Sélectionner la plage du tableau',
rename: 'Renommer le tableau',
diff --git a/packages/sheets-table-ui/src/locale/id-ID.ts b/packages/sheets-table-ui/src/locale/id-ID.ts
index eb696e984c..7fb3eb3695 100644
--- a/packages/sheets-table-ui/src/locale/id-ID.ts
+++ b/packages/sheets-table-ui/src/locale/id-ID.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Kolom terhitung',
+ columnFormula: 'Rumus',
+ columnFormulaHint: 'Langsung mengganti {0} sel data, kecuali header dan total. Berhenti mempertahankan sel yang ada. Perubahan dapat diurungkan.',
+ applyColumnFormula: 'Terapkan ke seluruh kolom',
+ stopColumnFormula: 'Hentikan isi otomatis',
+ columnFormulaApplied: 'Pengaturan kolom diterapkan',
+ settings: 'Pengaturan tabel',
+ showFilterButtons: 'Tampilkan tombol filter',
+ columnFilterButtons: 'Tombol filter kolom',
+ filterButtonsHint: 'Menyembunyikan tombol mempertahankan kriteria filter yang ada.',
+ settingsError: 'Tidak dapat menyimpan. Tabel mungkin telah berubah. Buka kembali pengaturan.',
title: 'Tabel',
selectRange: 'Pilih Rentang Tabel',
rename: 'Ubah Nama Tabel',
diff --git a/packages/sheets-table-ui/src/locale/it-IT.ts b/packages/sheets-table-ui/src/locale/it-IT.ts
index 3658a7ba01..a9c6f14d55 100644
--- a/packages/sheets-table-ui/src/locale/it-IT.ts
+++ b/packages/sheets-table-ui/src/locale/it-IT.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Colonna calcolata',
+ columnFormula: 'Formula',
+ columnFormulaHint: 'Sostituisce subito {0} celle dati, escluse intestazione e totali. Arrestare mantiene le celle esistenti. È possibile annullare.',
+ applyColumnFormula: 'Applica a tutta la colonna',
+ stopColumnFormula: 'Arresta riempimento automatico',
+ columnFormulaApplied: 'Impostazione applicata',
+ settings: 'Impostazioni tabella',
+ showFilterButtons: 'Mostra pulsanti filtro',
+ columnFilterButtons: 'Pulsanti filtro delle colonne',
+ filterButtonsHint: 'Nascondere i pulsanti mantiene i criteri di filtro esistenti.',
+ settingsError: 'Salvataggio non riuscito. La tabella potrebbe essere cambiata. Riapri le impostazioni.',
title: 'Tabella',
selectRange: 'Seleziona Intervallo Tabella',
rename: 'Rinomina Tabella',
diff --git a/packages/sheets-table-ui/src/locale/ja-JP.ts b/packages/sheets-table-ui/src/locale/ja-JP.ts
index 1733e055d9..9640ac2e8f 100644
--- a/packages/sheets-table-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-table-ui/src/locale/ja-JP.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: '集計列',
+ columnFormula: '数式',
+ columnFormulaHint: '適用すると列のデータセル {0} 個を置換します。見出しと集計行は除きます。自動入力の停止は既存セルを保持します。元に戻せます。',
+ applyColumnFormula: '列全体に適用',
+ stopColumnFormula: '自動入力を停止',
+ columnFormulaApplied: '列設定を適用しました',
+ settings: 'テーブル設定',
+ showFilterButtons: 'フィルターボタンを表示',
+ columnFilterButtons: '列のフィルターボタン',
+ filterButtonsHint: 'ボタンを非表示にしても既存のフィルター条件は保持されます。',
+ settingsError: '保存できませんでした。テーブルが変更された可能性があります。設定を開き直してください。',
title: '表',
selectRange: '表の範囲を選択',
rename: '表の名前を変更',
diff --git a/packages/sheets-table-ui/src/locale/ko-KR.ts b/packages/sheets-table-ui/src/locale/ko-KR.ts
index 7ee2e251c0..fdb5482ddc 100644
--- a/packages/sheets-table-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-table-ui/src/locale/ko-KR.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: '계산 열',
+ columnFormula: '수식',
+ columnFormulaHint: '적용하면 머리글과 합계 행을 제외한 데이터 셀 {0}개를 즉시 바꿉니다. 자동 채우기를 중지해도 기존 셀은 유지됩니다. 실행 취소할 수 있습니다.',
+ applyColumnFormula: '전체 열에 적용',
+ stopColumnFormula: '자동 채우기 중지',
+ columnFormulaApplied: '열 설정 적용됨',
+ settings: '표 설정',
+ showFilterButtons: '필터 버튼 표시',
+ columnFilterButtons: '열 필터 버튼',
+ filterButtonsHint: '버튼을 숨겨도 기존 필터 조건은 유지됩니다.',
+ settingsError: '저장하지 못했습니다. 표가 변경되었을 수 있습니다. 설정을 다시 열어 시도하세요.',
title: '표',
selectRange: '표 범위 선택',
rename: '표 이름 바꾸기',
diff --git a/packages/sheets-table-ui/src/locale/pl-PL.ts b/packages/sheets-table-ui/src/locale/pl-PL.ts
index 26e062755c..d3a899b5a8 100644
--- a/packages/sheets-table-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-table-ui/src/locale/pl-PL.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Kolumna obliczeniowa',
+ columnFormula: 'Formuła',
+ columnFormulaHint: 'Natychmiast zastępuje {0} komórek danych bez nagłówka i sumy. Zatrzymanie zachowuje istniejące komórki. Można cofnąć.',
+ applyColumnFormula: 'Zastosuj do całej kolumny',
+ stopColumnFormula: 'Zatrzymaj autowypełnianie',
+ columnFormulaApplied: 'Ustawienie zastosowane',
+ settings: 'Ustawienia tabeli',
+ showFilterButtons: 'Pokaż przyciski filtrów',
+ columnFilterButtons: 'Przyciski filtrów kolumn',
+ filterButtonsHint: 'Ukrycie przycisków zachowuje istniejące kryteria filtrowania.',
+ settingsError: 'Nie można zapisać. Tabela mogła się zmienić. Otwórz ponownie ustawienia.',
title: 'Tabela',
selectRange: 'Zaznacz zakres tabeli',
rename: 'Zmień nazwę tabeli',
diff --git a/packages/sheets-table-ui/src/locale/pt-BR.ts b/packages/sheets-table-ui/src/locale/pt-BR.ts
index 4674abc7c0..44136e81f3 100644
--- a/packages/sheets-table-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-table-ui/src/locale/pt-BR.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Coluna calculada',
+ columnFormula: 'Fórmula',
+ columnFormulaHint: 'Substitui imediatamente {0} células de dados, exceto cabeçalho e totais. Parar mantém as células existentes. É possível desfazer.',
+ applyColumnFormula: 'Aplicar à coluna inteira',
+ stopColumnFormula: 'Parar preenchimento automático',
+ columnFormulaApplied: 'Configuração aplicada',
+ settings: 'Configurações da tabela',
+ showFilterButtons: 'Mostrar botões de filtro',
+ columnFilterButtons: 'Botões de filtro das colunas',
+ filterButtonsHint: 'Ocultar os botões mantém os critérios de filtro existentes.',
+ settingsError: 'Não foi possível salvar. A tabela pode ter mudado. Reabra as configurações.',
title: 'Tabela',
selectRange: 'Selecionar Intervalo da Tabela',
rename: 'Renomear Tabela',
diff --git a/packages/sheets-table-ui/src/locale/ru-RU.ts b/packages/sheets-table-ui/src/locale/ru-RU.ts
index 6e9ccce564..a53955a1b7 100644
--- a/packages/sheets-table-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-table-ui/src/locale/ru-RU.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Вычисляемый столбец',
+ columnFormula: 'Формула',
+ columnFormulaHint: 'Сразу заменяет {0} ячеек данных без заголовка и итогов. Остановка сохраняет текущие ячейки. Действие можно отменить.',
+ applyColumnFormula: 'Применить ко всему столбцу',
+ stopColumnFormula: 'Остановить автозаполнение',
+ columnFormulaApplied: 'Настройка применена',
+ settings: 'Настройки таблицы',
+ showFilterButtons: 'Показывать кнопки фильтра',
+ columnFilterButtons: 'Кнопки фильтра столбцов',
+ filterButtonsHint: 'При скрытии кнопок сохраняются текущие условия фильтрации.',
+ settingsError: 'Не удалось сохранить. Возможно, таблица изменилась. Откройте настройки заново.',
title: 'Таблица',
selectRange: 'Выбрать диапазон таблицы',
rename: 'Переименовать таблицу',
diff --git a/packages/sheets-table-ui/src/locale/sk-SK.ts b/packages/sheets-table-ui/src/locale/sk-SK.ts
index c916733178..94d9a41f7e 100644
--- a/packages/sheets-table-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-table-ui/src/locale/sk-SK.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Vypočítaný stĺpec',
+ columnFormula: 'Vzorec',
+ columnFormulaHint: 'Okamžite nahradí {0} dátových buniek bez hlavičky a súhrnu. Zastavenie zachová existujúce bunky. Zmenu možno vrátiť späť.',
+ applyColumnFormula: 'Použiť na celý stĺpec',
+ stopColumnFormula: 'Zastaviť automatické vypĺňanie',
+ columnFormulaApplied: 'Nastavenie použité',
+ settings: 'Nastavenia tabuľky',
+ showFilterButtons: 'Zobraziť tlačidlá filtra',
+ columnFilterButtons: 'Tlačidlá filtra stĺpcov',
+ filterButtonsHint: 'Skrytie tlačidiel zachová existujúce kritériá filtra.',
+ settingsError: 'Uloženie zlyhalo. Tabuľka sa mohla zmeniť. Znova otvorte nastavenia.',
title: 'Tabuľka',
selectRange: 'Vyberte rozsah tabuľky',
rename: 'Premenovať tabuľku',
diff --git a/packages/sheets-table-ui/src/locale/vi-VN.ts b/packages/sheets-table-ui/src/locale/vi-VN.ts
index 1ca3a0d448..4cc2630276 100644
--- a/packages/sheets-table-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-table-ui/src/locale/vi-VN.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: 'Cột tính toán',
+ columnFormula: 'Công thức',
+ columnFormulaHint: 'Thay ngay {0} ô dữ liệu, không gồm tiêu đề và tổng. Dừng điền tự động giữ nguyên các ô hiện có. Có thể hoàn tác.',
+ applyColumnFormula: 'Áp dụng cho toàn cột',
+ stopColumnFormula: 'Dừng điền tự động',
+ columnFormulaApplied: 'Đã áp dụng thiết lập',
+ settings: 'Cài đặt bảng',
+ showFilterButtons: 'Hiển thị nút lọc',
+ columnFilterButtons: 'Nút lọc theo cột',
+ filterButtonsHint: 'Ẩn nút vẫn giữ các điều kiện lọc hiện có.',
+ settingsError: 'Không thể lưu. Bảng có thể đã thay đổi. Hãy mở lại cài đặt và thử lại.',
title: 'Bảng',
selectRange: 'Chọn phạm vi bảng',
rename: 'Đổi tên bảng',
diff --git a/packages/sheets-table-ui/src/locale/zh-CN.ts b/packages/sheets-table-ui/src/locale/zh-CN.ts
index 95d6341b60..dad8e8b438 100644
--- a/packages/sheets-table-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-table-ui/src/locale/zh-CN.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: '计算列',
+ columnFormula: '公式',
+ columnFormulaHint: '应用后立即覆盖此列的 {0} 个数据单元格,不包含表头和汇总行。停止自动填充会保留现有单元格。操作可撤销。',
+ applyColumnFormula: '应用到整列',
+ stopColumnFormula: '停止自动填充',
+ columnFormulaApplied: '列设置已应用',
+ settings: '表格设置',
+ showFilterButtons: '显示筛选按钮',
+ columnFilterButtons: '各列筛选按钮',
+ filterButtonsHint: '隐藏按钮会保留已有筛选条件。',
+ settingsError: '保存失败,表格可能已发生变化。请重新打开设置后重试。',
title: '表格',
selectRange: '选择表格范围',
rename: '重命名表格',
diff --git a/packages/sheets-table-ui/src/locale/zh-HK.ts b/packages/sheets-table-ui/src/locale/zh-HK.ts
index c5ef608296..639beb6f25 100644
--- a/packages/sheets-table-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-table-ui/src/locale/zh-HK.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: '計算欄',
+ columnFormula: '公式',
+ columnFormulaHint: '套用後立即覆寫此欄的 {0} 個資料儲存格,不含標題和合計列。停止自動填入會保留現有儲存格。操作可復原。',
+ applyColumnFormula: '套用至整欄',
+ stopColumnFormula: '停止自動填入',
+ columnFormulaApplied: '已套用欄設定',
+ settings: '表格設定',
+ showFilterButtons: '顯示篩選按鈕',
+ columnFilterButtons: '各欄篩選按鈕',
+ filterButtonsHint: '隱藏按鈕會保留現有篩選條件。',
+ settingsError: '儲存失敗,表格可能已變更。請重新開啟設定後重試。',
title: '表格',
selectRange: '選擇表格範圍',
rename: '重新命名表格',
diff --git a/packages/sheets-table-ui/src/locale/zh-TW.ts b/packages/sheets-table-ui/src/locale/zh-TW.ts
index c5ef608296..639beb6f25 100644
--- a/packages/sheets-table-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-table-ui/src/locale/zh-TW.ts
@@ -18,6 +18,17 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-table-ui': {
+ calculatedColumn: '計算欄',
+ columnFormula: '公式',
+ columnFormulaHint: '套用後立即覆寫此欄的 {0} 個資料儲存格,不含標題和合計列。停止自動填入會保留現有儲存格。操作可復原。',
+ applyColumnFormula: '套用至整欄',
+ stopColumnFormula: '停止自動填入',
+ columnFormulaApplied: '已套用欄設定',
+ settings: '表格設定',
+ showFilterButtons: '顯示篩選按鈕',
+ columnFilterButtons: '各欄篩選按鈕',
+ filterButtonsHint: '隱藏按鈕會保留現有篩選條件。',
+ settingsError: '儲存失敗,表格可能已變更。請重新開啟設定後重試。',
title: '表格',
selectRange: '選擇表格範圍',
rename: '重新命名表格',
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
index 0a32bdca68..b258bfcbc3 100644
--- a/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
@@ -17,7 +17,7 @@
import type { ISheetTableMenuExtraProps, SheetTableMenuAction } from './SheetTableMenu';
import { MobileActionRow } from '@univerjs/design';
-const ACTIONS: SheetTableMenuAction[] = ['rename', 'update-range', 'set-theme', 'delete'];
+const ACTIONS: SheetTableMenuAction[] = ['rename', 'update-range', 'set-theme', 'settings', 'delete'];
export function MobileSheetTableMenu({ menu }: { menu?: ISheetTableMenuExtraProps }) {
if (!menu) {
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableSettingsDialog.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableSettingsDialog.tsx
new file mode 100644
index 0000000000..2751a2afbb
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableSettingsDialog.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetTableSettingsDialogProps } from './SheetTableSettingsDialog';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetTableSettingsDialog } from './SheetTableSettingsDialog';
+
+export function MobileSheetTableSettingsDialog(props: ISheetTableSettingsDialogProps) {
+ return <SheetTableSettingsDialog {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableCalculatedColumn.tsx b/packages/sheets-table-ui/src/views/components/SheetTableCalculatedColumn.tsx
new file mode 100644
index 0000000000..1cce67f2a9
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/SheetTableCalculatedColumn.tsx
@@ -0,0 +1,96 @@
+/**
+ * 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 { LocaleKey } from '../../locale/types';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { Button, FormLayout, Input, Select } from '@univerjs/design';
+import { SetSheetTableCommand, TableManager } from '@univerjs/sheets-table';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+
+interface ISheetTableCalculatedColumnProps {
+ unitId: string;
+ tableId: string;
+}
+
+export function SheetTableCalculatedColumn({ unitId, tableId }: ISheetTableCalculatedColumnProps) {
+ const localeService = useDependency(LocaleService);
+ const commands = useDependency(ICommandService);
+ const manager = useDependency(TableManager);
+ const table = manager.getTableById(unitId, tableId);
+ const columns = table?.getTableInfo().columns ?? [];
+ const [columnId, setColumnId] = useState(columns[0]?.id ?? '');
+ const [formula, setFormula] = useState(columns[0]?.formula ?? '');
+ const [result, setResult] = useState<boolean>();
+ const range = table?.getTableFilterRange();
+
+ const apply = (value: string) => {
+ try {
+ const success = commands.syncExecuteCommand(SetSheetTableCommand.id, {
+ unitId,
+ tableId,
+ calculatedColumn: { columnId, formula: value },
+ });
+ setResult(success);
+ if (success) {
+ setFormula(value);
+ }
+ } catch {
+ setResult(false);
+ }
+ };
+
+ return (
+ <fieldset className="univer-m-0 univer-min-w-0 univer-border-0 univer-p-0" disabled={!table}>
+ <legend className="univer-mb-2 univer-text-sm">{localeService.t<LocaleKey>('sheets-table-ui.calculatedColumn')}</legend>
+ <Select
+ className="univer-w-full"
+ options={columns.map((column) => ({ value: column.id, label: column.displayName }))}
+ value={columnId}
+ onChange={(id) => {
+ setColumnId(id);
+ setFormula(table?.getColumn(id)?.formula ?? '');
+ setResult(undefined);
+ }}
+ />
+ <FormLayout label={localeService.t<LocaleKey>('sheets-table-ui.columnFormula')}>
+ <Input
+ value={formula}
+ onChange={(value) => {
+ setFormula(value);
+ setResult(undefined);
+ }}
+ />
+ </FormLayout>
+ <p className="univer-text-sm univer-text-gray-500">
+ {localeService.t<LocaleKey>('sheets-table-ui.columnFormulaHint', String(Math.max(0, (range?.endRow ?? -1) - (range?.startRow ?? 0) + 1)))}
+ </p>
+ <div className="univer-flex univer-flex-wrap univer-gap-2">
+ <Button disabled={!columnId || !formula.trim()} onClick={() => apply(formula)}>
+ {localeService.t<LocaleKey>('sheets-table-ui.applyColumnFormula')}
+ </Button>
+ <Button disabled={!table?.getColumn(columnId)?.formula} onClick={() => apply('')}>
+ {localeService.t<LocaleKey>('sheets-table-ui.stopColumnFormula')}
+ </Button>
+ </div>
+ {result !== undefined && (
+ <p role={result ? 'status' : 'alert'} className="univer-text-sm">
+ {localeService.t<LocaleKey>(result ? 'sheets-table-ui.columnFormulaApplied' : 'sheets-table-ui.settingsError')}
+ </p>
+ )}
+ </fieldset>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx b/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
index 3366087169..5f3240fd7e 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
@@ -17,7 +17,7 @@
import type { ICanvasPopup } from '@univerjs/sheets-ui';
import { DropdownMenu } from '@univerjs/design';
-export type SheetTableMenuAction = 'rename' | 'update-range' | 'set-theme' | 'delete';
+export type SheetTableMenuAction = 'rename' | 'update-range' | 'set-theme' | 'settings' | 'delete';
export interface ISheetTableMenuExtraProps {
anchorWidth: number;
@@ -46,6 +46,7 @@ export function SheetTableMenu({ popup }: ISheetTableMenuProps) {
{ type: 'item', children: menu.labels.rename, onSelect: () => menu.onSelect('rename') },
{ type: 'item', children: menu.labels['update-range'], onSelect: () => menu.onSelect('update-range') },
{ type: 'item', children: menu.labels['set-theme'], onSelect: () => menu.onSelect('set-theme') },
+ { type: 'item', children: menu.labels.settings, onSelect: () => menu.onSelect('settings') },
{ type: 'item', children: menu.labels.delete, variant: 'destructive', onSelect: () => menu.onSelect('delete') },
]}
open
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableSettingsDialog.tsx b/packages/sheets-table-ui/src/views/components/SheetTableSettingsDialog.tsx
new file mode 100644
index 0000000000..29cc81e7d8
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/SheetTableSettingsDialog.tsx
@@ -0,0 +1,111 @@
+/**
+ * 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 { LocaleKey } from '../../locale/types';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { ActionRow, Button, Checkbox } from '@univerjs/design';
+import { SetSheetTableCommand, TableManager } from '@univerjs/sheets-table';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+import { SheetTableCalculatedColumn } from './SheetTableCalculatedColumn';
+
+export interface ISheetTableSettingsDialogProps {
+ unitId: string;
+ tableId: string;
+ onClose: () => void;
+ ActionRowComponent?: typeof ActionRow;
+}
+
+export function SheetTableSettingsDialog(props: ISheetTableSettingsDialogProps) {
+ const { unitId, tableId, onClose, ActionRowComponent = ActionRow } = props;
+ const localeService = useDependency(LocaleService);
+ const commandService = useDependency(ICommandService);
+ const tableManager = useDependency(TableManager);
+ const [initial] = useState(() => tableManager.getTableById(unitId, tableId)?.getTableInfo());
+ const [showAutoFilter, setShowAutoFilter] = useState(initial?.showAutoFilter ?? true);
+ const [columns, setColumns] = useState<Record<string, boolean>>(() =>
+ Object.fromEntries((initial?.columns ?? []).map((column) => [column.id, column.showFilterButton !== false])));
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(false);
+
+ const handleConfirm = async () => {
+ if (!initial || saving) {
+ return;
+ }
+ const changedColumns = Object.fromEntries(initial.columns
+ .filter((column) => columns[column.id] !== (column.showFilterButton !== false))
+ .map((column) => [column.id, columns[column.id]]));
+ if (showAutoFilter === initial.showAutoFilter && Object.keys(changedColumns).length === 0) {
+ onClose();
+ return;
+ }
+ setSaving(true);
+ setError(false);
+ try {
+ const success = await commandService.executeCommand(SetSheetTableCommand.id, {
+ unitId,
+ tableId,
+ filterButtons: {
+ ...(showAutoFilter === initial.showAutoFilter ? {} : { showAutoFilter }),
+ columns: changedColumns,
+ },
+ });
+ if (success) {
+ onClose();
+ } else {
+ setError(true);
+ }
+ } catch {
+ setError(true);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <div className="univer-flex univer-flex-col univer-gap-4 univer-py-2">
+ <Checkbox checked={showAutoFilter} disabled={saving || !initial} onChange={(value) => setShowAutoFilter(Boolean(value))}>
+ {localeService.t<LocaleKey>('sheets-table-ui.showFilterButtons')}
+ </Checkbox>
+ <p className="univer-m-0 univer-text-sm univer-text-gray-500">
+ {localeService.t<LocaleKey>('sheets-table-ui.filterButtonsHint')}
+ </p>
+ <fieldset className="univer-m-0 univer-min-w-0 univer-border-0 univer-p-0" disabled={!showAutoFilter || saving}>
+ <legend className="univer-mb-2 univer-text-sm">
+ {localeService.t<LocaleKey>('sheets-table-ui.columnFilterButtons')}
+ </legend>
+ <div className="univer-flex univer-max-h-64 univer-flex-col univer-gap-2 univer-overflow-y-auto">
+ {initial?.columns.map((column) => (
+ <Checkbox
+ key={column.id}
+ checked={columns[column.id]}
+ disabled={!showAutoFilter || saving}
+ onChange={(value) => setColumns((previous) => ({ ...previous, [column.id]: Boolean(value) }))}
+ >
+ {column.displayName}
+ </Checkbox>
+ ))}
+ </div>
+ </fieldset>
+ <SheetTableCalculatedColumn unitId={unitId} tableId={tableId} />
+ {error && <div role="alert" className="univer-text-sm univer-text-red-500">{localeService.t<LocaleKey>('sheets-table-ui.settingsError')}</div>}
+ <ActionRowComponent className="univer-flex univer-justify-end univer-gap-2">
+ <Button disabled={saving} onClick={onClose}>{localeService.t<LocaleKey>('sheets-table-ui.cancel')}</Button>
+ <Button variant="primary" disabled={saving || !initial} onClick={handleConfirm}>{localeService.t<LocaleKey>('sheets-table-ui.confirm')}</Button>
+ </ActionRowComponent>
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSettingsDialog.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSettingsDialog.spec.tsx
new file mode 100644
index 0000000000..dc26bd88df
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSettingsDialog.spec.tsx
@@ -0,0 +1,208 @@
+/**
+ * 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 {
+ ICommandService,
+ IPermissionService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RedoCommand,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { FUniver } from '@univerjs/core/facade';
+import {
+ DefinedNamesService,
+ FormulaDataModel,
+ IDefinedNamesService,
+ LexerTreeBuilder,
+} from '@univerjs/engine-formula';
+import {
+ RangeProtectionRuleModel,
+ SetRangeValuesMutation,
+ SheetInterceptorService,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+} from '@univerjs/sheets';
+import {
+ SetSheetTableCommand,
+ SetSheetTableMutation,
+ TableColumnFilterTypeEnum,
+ TableManager,
+} from '@univerjs/sheets-table';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { SheetTableSettingsDialog } from '../SheetTableSettingsDialog';
+import '@univerjs/sheets/facade';
+import '@univerjs/sheets-table/facade';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+it('saves filter button settings through the command pipeline, supports undo and round trips, and rejects stale columns', async () => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([TableManager]);
+ injector.add([LexerTreeBuilder]);
+ injector.add([FormulaDataModel]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, {
+ id: 'book',
+ sheetOrder: ['sheet'],
+ sheets: { sheet: { id: 'sheet', name: 'Sheet', rowCount: 20, columnCount: 10 } },
+ });
+ injector.get(IUniverInstanceService).focusUnit('book');
+ const manager = injector.get(TableManager);
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(SetSheetTableCommand);
+ commands.registerCommand(SetRangeValuesMutation);
+ commands.registerCommand(SetSheetTableMutation);
+ manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Product', 'Amount'], 'orders');
+ const table = manager.getTableById('book', 'orders')!;
+ const firstColumn = table.getTableColumnByIndex(0)!.id;
+ const lastColumn = table.getTableColumnByIndex(1)!.id;
+ table.getTableFilters().setFilterOutRows([2]);
+ table.getTableFilters().setColumnFilter(1, { filterType: TableColumnFilterTypeEnum.manual, values: ['10'] });
+ const initialFilters = table.getTableFilters().toJSON();
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ let closed = 0;
+ const worksheet = FUniver.newAPI(injector).getActiveWorkbook()!.getActiveSheet();
+
+ try {
+ act(() => root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SheetTableSettingsDialog unitId="book" tableId="orders" onClose={() => { closed++; }} />
+ </RediContext.Provider>
+ ));
+ const initialPermissions = injector.get(IPermissionService);
+ initialPermissions.addPermissionPoint(new WorkbookEditablePermission('book'));
+ initialPermissions.addPermissionPoint(new WorksheetEditPermission('book', 'sheet'));
+ const input = container.querySelector('input:not([type="checkbox"])') as HTMLInputElement;
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, '=$B2');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ const applyButton = Array.from(container.querySelectorAll('button')).find((button) => button.textContent === 'Apply to entire column')!;
+ act(() => applyButton.click());
+ expect(worksheet.getRange('A2:A4').getFormulas()).toEqual([['=$B2'], ['=$B3'], ['=$B4']]);
+ expect(table.getColumn(firstColumn)!.formula).toBe('=$B2');
+ expect(worksheet.getRange('A1').getFormula()).toBe('');
+ const checkboxes = container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
+ act(() => checkboxes[2].click());
+ expect(table.getColumn(lastColumn)!.isShowFilterButton()).toBe(true);
+ act(() => checkboxes[0].click());
+ expect(checkboxes[1].disabled).toBe(true);
+ const confirm = Array.from(container.querySelectorAll('button')).find((button) => button.textContent === 'Confirm')!;
+ await act(async () => confirm.click());
+ expect(closed).toBe(1);
+ expect(table.isShowAutoFilter()).toBe(false);
+ expect(table.getColumn(firstColumn)!.isShowFilterButton()).toBe(true);
+ expect(table.getColumn(lastColumn)!.isShowFilterButton()).toBe(false);
+ expect(table.getTableFilters().toJSON()).toEqual(initialFilters);
+ expect(Array.from(table.getTableFilters().getFilterOutRows()!)).toEqual([2]);
+
+ await commands.executeCommand(UndoCommand.id);
+ expect(table.isShowAutoFilter()).toBe(true);
+ expect(table.getColumn(lastColumn)!.isShowFilterButton()).toBe(true);
+ await commands.executeCommand(RedoCommand.id);
+ expect(table.isShowAutoFilter()).toBe(false);
+ expect(table.getColumn(lastColumn)!.isShowFilterButton()).toBe(false);
+ const saved = JSON.parse(JSON.stringify(manager.toJSON('book')));
+ manager.fromJSON('book', saved);
+ const restored = manager.getTableById('book', 'orders')!;
+ expect(restored.isShowAutoFilter()).toBe(false);
+ expect(restored.getColumn(lastColumn)!.isShowFilterButton()).toBe(false);
+ expect(JSON.stringify(restored.getTableFilters().toJSON())).toBe(JSON.stringify(initialFilters));
+ expect(Array.from(restored.getTableFilters().getFilterOutRows()!)).toEqual([2]);
+ let mutationCompleted = false;
+ const listener = commands.onCommandExecuted((command) => {
+ if (command.id === SetSheetTableMutation.id) {
+ mutationCompleted = true;
+ }
+ });
+ try {
+ const success: boolean = worksheet.setTableFilterButtons('orders', { showAutoFilter: true });
+ expect(success).toBe(true);
+ expect(mutationCompleted).toBe(true);
+ } finally {
+ listener.dispose();
+ }
+ expect(restored.isShowAutoFilter()).toBe(true);
+ expect(restored.getColumn(lastColumn)!.isShowFilterButton()).toBe(false);
+ expect(worksheet.setTableFilterButtons('orders', {
+ showAutoFilter: false,
+ columns: { missing: false },
+ })).toBe(false);
+ expect(restored.isShowAutoFilter()).toBe(true);
+ expect(worksheet.setTableFilterButtons('missing', { showAutoFilter: false })).toBe(false);
+ const permissions = injector.get(IPermissionService);
+ permissions.addPermissionPoint(new WorkbookEditablePermission('book'));
+ permissions.addPermissionPoint(new WorksheetEditPermission('book', 'sheet'));
+ const dataRange = worksheet.getRange('B2:B4');
+ commands.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'book',
+ subUnitId: 'sheet',
+ cellValue: { 1: { 1: { v: 10 } }, 2: { 1: { v: 20 } }, 3: { 1: { v: 30 } } },
+ });
+ const oldCells = dataRange.getValues();
+ expect(worksheet.setTableColumnFormula('orders', lastColumn, '=A2*2')).toBe(true);
+ expect(dataRange.getFormulas()).toEqual([['=A2*2'], ['=A3*2'], ['=A4*2']]);
+ expect(restored.getColumn(lastColumn)!.formula).toBe('=A2*2');
+ await commands.executeCommand(UndoCommand.id);
+ expect(dataRange.getValues()).toEqual(oldCells);
+ expect(restored.getColumn(lastColumn)!.formula).toBe('');
+ await commands.executeCommand(RedoCommand.id);
+ expect(dataRange.getFormulas()).toEqual([['=A2*2'], ['=A3*2'], ['=A4*2']]);
+ expect(worksheet.setTableColumnFormula('orders', lastColumn, '')).toBe(true);
+ expect(restored.getColumn(lastColumn)!.formula).toBe('');
+ expect(dataRange.getFormulas()).toEqual([['=A2*2'], ['=A3*2'], ['=A4*2']]);
+ await commands.executeCommand(UndoCommand.id);
+ expect(restored.getColumn(lastColumn)!.formula).toBe('=A2*2');
+ expect(worksheet.setTableColumnFormula('orders', 'missing', '=1')).toBe(false);
+ expect(worksheet.setTableColumnFormula('orders', lastColumn, '=')).toBe(false);
+ manager.addTable('book', 'sheet', 'Totals', { startRow: 6, endRow: 9, startColumn: 0, endColumn: 1 }, ['Item', 'Total'], 'totals', { showFooter: true });
+ const totalsColumn = manager.getTableById('book', 'totals')!.getTableColumnByIndex(1)!.id;
+ expect(worksheet.setTableColumnFormula('totals', totalsColumn, '=A8')).toBe(true);
+ expect(worksheet.getRange('B7:B10').getFormulas()).toEqual([[''], ['=A8'], ['=A9'], ['']]);
+ permissions.updatePermissionPoint(new WorksheetEditPermission('book', 'sheet').id, false);
+ expect(worksheet.setTableColumnFormula('orders', lastColumn, '=1')).toBe(false);
+ permissions.updatePermissionPoint(new WorksheetEditPermission('book', 'sheet').id, true);
+ const editable = new WorkbookEditablePermission('book');
+ permissions.addPermissionPoint(editable);
+ permissions.updatePermissionPoint(editable.id, false);
+ expect(worksheet.setTableFilterButtons('orders', { showAutoFilter: false })).toBe(false);
+ expect(restored.isShowAutoFilter()).toBe(true);
+ manager.fromJSON('book', JSON.parse(JSON.stringify(manager.toJSON('book'))));
+ expect(manager.getTableById('book', 'orders')!.getColumn(lastColumn)!.formula).toBe('=A2*2');
+ } finally {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+ }
+});
diff --git a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
index 31eda8fba0..8dd096d118 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import { ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
+import { ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix, Univer } from '@univerjs/core';
import { MoveRangeMutation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { SheetsTableController } from '../../../controllers/sheets-table.controller';
import { TableManager } from '../../../models/table-manager';
import {
@@ -29,8 +29,20 @@ import {
SheetTableRemoveRowCommand,
} from '../sheet-table-row-col.command';
+const testUnivers: Univer[] = [];
+afterEach(() => {
+ testUnivers.splice(0).forEach((univer) => univer.dispose());
+});
+
function createAccessor(pairs: Array<[unknown, unknown]>) {
const map = new Map<unknown, unknown>(pairs);
+ if (!map.has(SheetInterceptorService)) {
+ const univer = new Univer();
+ testUnivers.push(univer);
+ const injector = univer.__getInjector();
+ injector.add([SheetInterceptorService]);
+ map.set(SheetInterceptorService, injector.get(SheetInterceptorService));
+ }
return {
get(token: unknown) {
if (!map.has(token)) {
diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
index fcaefb56c9..a339e763e8 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
@@ -17,7 +17,12 @@
import type { ITableManualFilterItem } from '../../../types/type';
import { ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { IDefinedNamesService } from '@univerjs/engine-formula';
-import { AddRangeThemeMutation, RemoveRangeThemeMutation, SheetInterceptorService, SheetRangeThemeModel } from '@univerjs/sheets';
+import {
+ AddRangeThemeMutation,
+ RemoveRangeThemeMutation,
+ SheetInterceptorService,
+ SheetRangeThemeModel,
+} from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { TableManager } from '../../../models/table-manager';
import { TableColumnFilterTypeEnum } from '../../../types/enum';
@@ -209,7 +214,7 @@ describe('sheets-table commands', () => {
});
it('SetSheetTableCommand should execute mutation and build inverse undo config', () => {
- const executeCommand = vi.fn();
+ const syncExecuteCommand = vi.fn((_id: string) => true);
const pushUndoRedo = vi.fn();
const onCommandExecute = vi.fn(() => ({
preRedos: [{ id: 'formula.redo.before', params: { phase: 'pre' } }],
@@ -229,7 +234,7 @@ describe('sheets-table commands', () => {
[LocaleService, { t: () => 'msg' }],
[IUniverInstanceService, { getUnit: () => ({ getSheets: () => [{ getName: () => 'SheetA' }] }) }],
[IDefinedNamesService, { getDefinedNameMap: () => ({}) }],
- [ICommandService, { executeCommand }],
+ [ICommandService, { syncExecuteCommand }],
[IUndoRedoService, { pushUndoRedo }],
[ILogService, { warn: vi.fn() }],
[SheetInterceptorService, { onCommandExecute }],
@@ -261,7 +266,7 @@ describe('sheets-table commands', () => {
oldTableName: 'OldName',
}),
});
- expect(executeCommand.mock.calls.map(([id]) => id)).toEqual([
+ expect(syncExecuteCommand.mock.calls.map(([id]) => id)).toEqual([
'formula.redo.before',
SetSheetTableMutation.id,
'formula.redo.after',
@@ -303,6 +308,7 @@ describe('sheets-table commands', () => {
[TableManager, {
getTable: () => ({
getTableFilterColumn: () => previousFilter,
+ getTableFilters: () => ({ getColumnFilter: () => previousFilter, getFilterOutRows: () => new Set() }),
}),
}],
]);
@@ -333,11 +339,46 @@ describe('sheets-table commands', () => {
tableId: 't1',
column: 1,
tableFilter: previousFilter,
+ filterOutRows: [],
},
}],
}));
});
+ it('SetSheetTableFilterCommand restores the previous filter and cached filtered rows', () => {
+ const syncExecuteCommand = vi.fn(() => true);
+ const pushUndoRedo = vi.fn();
+ const previousFilter = { filterType: 'manual', values: ['original'] };
+ const previousRows = new Set([2, 5]);
+ const accessor = createAccessor([
+ [IUndoRedoService, { pushUndoRedo }],
+ [ICommandService, { syncExecuteCommand }],
+ [TableManager, {
+ getTable: () => ({
+ getTableFilters: () => ({
+ getColumnFilter: () => previousFilter,
+ getFilterOutRows: () => previousRows,
+ }),
+ }),
+ }],
+ ]);
+
+ const result = SetSheetTableFilterCommand.handler(accessor, {
+ unitId: 'u1',
+ tableId: 't1',
+ column: 0,
+ tableFilter: undefined,
+ });
+
+ expect(result).toBe(true);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ undoMutations: [expect.objectContaining({
+ id: SetSheetTableFilterMutation.id,
+ params: expect.objectContaining({ tableFilter: previousFilter, filterOutRows: [2, 5] }),
+ })],
+ }));
+ });
+
it('AddTableThemeCommand should register theme and update table style', () => {
const syncExecuteCommand = vi.fn(() => true);
const pushUndoRedo = vi.fn();
diff --git a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
index 0e017cb120..d5b02d0770 100644
--- a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
+++ b/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
@@ -14,24 +14,34 @@
* limitations under the License.
*/
-import type { ICommand } from '@univerjs/core';
+import type { ICommand, IMutationInfo } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { LocaleKey } from '../../locale/types';
import type { ITableSetConfig } from '../../types/type';
import {
CommandType,
ICommandService,
ILogService,
+ IPermissionService,
IUndoRedoService,
IUniverInstanceService,
LocaleService,
+ sequenceExecute,
} from '@univerjs/core';
-import { IDefinedNamesService } from '@univerjs/engine-formula';
-import { SheetInterceptorService } from '@univerjs/sheets';
+import { IDefinedNamesService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import {
+ checkRangesEditablePermission,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+ SheetInterceptorService,
+ WorkbookEditablePermission,
+} from '@univerjs/sheets';
import { TableManager } from '../../models/table-manager';
import { IRangeOperationTypeEnum } from '../../types/type';
import { getExistingNamesSet } from '../../util';
import { validateSheetTableName } from '../../util/table-name';
import { SetSheetTableMutation } from '../mutations/set-sheet-table.mutation';
+import { getCalculatedColumnFillMutation } from '../utils/calculated-column';
export interface ISetSheetTableCommandParams extends ITableSetConfig {
unitId: string;
@@ -42,20 +52,80 @@ export interface ISetSheetTableCommandParams extends ITableSetConfig {
export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {
id: 'sheet.command.set-table-config',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
handler: (accessor, params) => {
if (!params) {
return false;
}
- const { unitId, tableId, name, updateRange, rowColOperation, theme } = params;
+ const { unitId, tableId, name, updateRange, rowColOperation, theme, filterButtons } = params;
const tableManager = accessor.get(TableManager);
const table = tableManager.getTableById(unitId, tableId);
- if (!table) return false;
+ if (!table) {
+ return false;
+ }
+ const cellRedos: IMutationInfo[] = [];
+ const cellUndos: IMutationInfo[] = [];
const oldTableConfig: ITableSetConfig = {};
const newTableConfig: ITableSetConfig = {};
+ if (params.calculatedColumn) {
+ const { columnId, formula, formulaIsArray } = params.calculatedColumn;
+ const column = table.getColumn(columnId);
+ if (!column || typeof formula !== 'string' || (formulaIsArray !== undefined && typeof formulaIsArray !== 'boolean')) {
+ return false;
+ }
+ // Combining a structural edit and a fill would make the formula anchor ambiguous.
+ if (updateRange || rowColOperation) {
+ return false;
+ }
+ const range = table.getTableFilterRange();
+ const columnIndex = table.getTableInfo().columns.findIndex((item) => item.id === columnId);
+ const sheetColumn = range.startColumn + columnIndex;
+ const editRange = { ...range, startColumn: sheetColumn, endColumn: sheetColumn };
+ if (!checkRangesEditablePermission(accessor, unitId, table.getSubunitId(), [editRange])) {
+ return false;
+ }
+ const normalized = formula.trim();
+ if (normalized === '=') {
+ return false;
+ }
+ oldTableConfig.calculatedColumn = { columnId, formula: column.formula, formulaIsArray: column.formulaIsArray };
+ newTableConfig.calculatedColumn = {
+ columnId,
+ formula: normalized && !normalized.startsWith('=') ? `=${normalized}` : normalized,
+ formulaIsArray: normalized ? formulaIsArray ?? column.formulaIsArray : undefined,
+ };
+ const fill = getCalculatedColumnFillMutation(table, unitId, table.getSubunitId(), range.startRow, range.endRow, () => accessor.get(LexerTreeBuilder), newTableConfig.calculatedColumn);
+ if (fill) {
+ cellRedos.push(fill);
+ cellUndos.push({
+ id: SetRangeValuesMutation.id,
+ params: SetRangeValuesUndoMutationFactory(accessor, fill.params as ISetRangeValuesMutationParams),
+ });
+ }
+ }
+ if (filterButtons) {
+ if (accessor.get(IPermissionService).getPermissionPoint(new WorkbookEditablePermission(unitId).id)?.value === false) {
+ return false;
+ }
+ const { showAutoFilter, columns } = filterButtons;
+ if (showAutoFilter !== undefined && typeof showAutoFilter !== 'boolean') {
+ return false;
+ }
+ const entries = Object.entries(columns ?? {});
+ if (entries.some(([id, visible]) => !table.getColumn(id) || typeof visible !== 'boolean')) {
+ return false;
+ }
+ oldTableConfig.filterButtons = {
+ ...(showAutoFilter === undefined ? {} : { showAutoFilter: table.isShowAutoFilter() }),
+ columns: Object.fromEntries(entries.map(([id]) => [id, table.getColumn(id)!.isShowFilterButton()])),
+ };
+ newTableConfig.filterButtons = {
+ ...(showAutoFilter === undefined ? {} : { showAutoFilter }),
+ columns: Object.fromEntries(entries),
+ };
+ }
const localeService = accessor.get(LocaleService);
const existingNamesSet = getExistingNamesSet(unitId, {
univerInstanceService: accessor.get(IUniverInstanceService),
@@ -121,18 +191,20 @@ export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {
const redos = [
...(interceptorCommands.preRedos ?? []),
{ id: SetSheetTableMutation.id, params: redoParams },
+ ...cellRedos,
...interceptorCommands.redos,
];
const undos = [
...(interceptorCommands.preUndos ?? []),
{ id: SetSheetTableMutation.id, params: undoParams },
+ ...cellUndos,
...interceptorCommands.undos,
];
const commandService = accessor.get(ICommandService);
- redos.forEach((mutation) => {
- commandService.executeCommand(mutation.id, mutation.params);
- });
+ if (!sequenceExecute(redos, commandService).result) {
+ return false;
+ }
const undoRedoService = accessor.get(IUndoRedoService);
undoRedoService.pushUndoRedo({
diff --git a/packages/sheets-table/src/commands/commands/set-table-filter.command.ts b/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
index 505d46c1c6..6290aa2dbd 100644
--- a/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
+++ b/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
@@ -31,13 +31,18 @@ export const SetSheetTableFilterCommand: ICommand<ISetSheetTableParams> = {
const commandService = accessor.get(ICommandService);
const tableManager = accessor.get(TableManager);
const tableId = params.tableId || generateRandomId();
- const previousFilter = tableManager.getTable(params.unitId, tableId)?.getTableFilterColumn(params.column);
+ const tableFilters = tableManager.getTable(params.unitId, tableId)?.getTableFilters();
+ const oldTableFilter = tableFilters?.getColumnFilter(params.column);
+ const oldFilterOutRows = [...(tableFilters?.getFilterOutRows() ?? [])];
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
redos.push({ id: SetSheetTableFilterMutation.id, params: { ...params, tableId } });
- undos.push({ id: SetSheetTableFilterMutation.id, params: { ...params, tableId, tableFilter: previousFilter } });
+ undos.push({
+ id: SetSheetTableFilterMutation.id,
+ params: { ...params, tableId, tableFilter: oldTableFilter, filterOutRows: oldFilterOutRows },
+ });
const res = sequenceExecute(redos, commandService);
diff --git a/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts b/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
index 80cd1324b6..c0d46e2c94 100644
--- a/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
+++ b/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
@@ -17,13 +17,16 @@
/* eslint-disable max-lines-per-function */
import type { IAccessor, ICommand, IMutationInfo } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ITableColumnJson } from '../../types/type';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
-import { getMoveRangeUndoRedoMutations, getSheetCommandTarget, InsertColMutation, InsertRowMutation, RemoveColMutation, RemoveRowMutation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { getMoveRangeCommandMutations, getMoveRangeUndoRedoMutations, getSheetCommandTarget, InsertColMutation, InsertRowMutation, RemoveColMutation, RemoveRowMutation, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { SheetsTableController } from '../../controllers/sheets-table.controller';
import { TableManager } from '../../models/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../types/type';
import { SetSheetTableMutation } from '../mutations/set-sheet-table.mutation';
+import { getCalculatedColumnFillMutation } from '../utils/calculated-column';
interface ISheetTableRowColOperationCommandParams {
tableId: string;
@@ -70,7 +73,7 @@ export const SheetTableInsertRowCommand: ICommand<ISheetTableRowColOperationComm
return false;
}
- const { workbook, worksheet, unitId, subUnitId } = target;
+ const { worksheet, unitId, subUnitId } = target;
const sheetsSelectionsService = accessor.get(SheetsSelectionsService);
const selections = sheetsSelectionsService.getCurrentSelections();
@@ -78,8 +81,6 @@ export const SheetTableInsertRowCommand: ICommand<ISheetTableRowColOperationComm
return false;
}
- const tableManager = accessor.get(TableManager);
-
const selection = selections[0];
const range = selection.range;
@@ -176,28 +177,26 @@ export const SheetTableInsertRowCommand: ICommand<ISheetTableRowColOperationComm
},
});
- const moveRangeMutations = getMoveRangeUndoRedoMutations(
+ const moveRangeMutations = getMoveRangeCommandMutations(
accessor,
{
- unitId,
- subUnitId,
- range: {
+ fromUnitId: unitId,
+ fromSubUnitId: subUnitId,
+ toSubUnitId: subUnitId,
+ fromRange: {
startRow: range.startRow,
endRow: rowContentIndex,
startColumn: oldRange.startColumn,
endColumn: oldRange.endColumn,
},
- },
- {
- unitId,
- subUnitId,
- range: {
+ toRange: {
startRow: range.startRow + insertRowCount,
endRow: rowContentIndex + insertRowCount,
startColumn: oldRange.startColumn,
endColumn: oldRange.endColumn,
},
- }
+ },
+ { includeSelection: false, includeAutoHeight: false }
);
if (moveRangeMutations) {
redos.push(...moveRangeMutations.redos);
@@ -205,6 +204,22 @@ export const SheetTableInsertRowCommand: ICommand<ISheetTableRowColOperationComm
}
}
+ const formulaMutation = getCalculatedColumnFillMutation(
+ table,
+ unitId,
+ subUnitId,
+ range.startRow,
+ range.endRow,
+ () => accessor.get(LexerTreeBuilder)
+ );
+ if (formulaMutation) {
+ redos.push(formulaMutation);
+ undos.push({
+ id: SetRangeValuesMutation.id,
+ params: SetRangeValuesUndoMutationFactory(accessor, formulaMutation.params as ISetRangeValuesMutationParams),
+ });
+ }
+
const commandService = accessor.get(ICommandService);
const res = sequenceExecute(redos, commandService);
@@ -283,35 +298,51 @@ export const SheetTableInsertRowAtCommand: ICommand<ISheetTableInsertAtCommandPa
}];
const rowContentIndex = target.worksheet.getCellMatrix().getDataRange().endRow;
- const moveRangeMutations = getMoveRangeUndoRedoMutations(
- accessor,
- {
- unitId,
- subUnitId,
- range: {
- startRow: index,
- endRow: rowContentIndex,
- startColumn: oldRange.startColumn,
- endColumn: oldRange.endColumn,
- },
- },
- {
- unitId,
- subUnitId,
- range: {
- startRow: index + count,
- endRow: rowContentIndex + count,
- startColumn: oldRange.startColumn,
- endColumn: oldRange.endColumn,
+ const moveRangeMutations = index <= rowContentIndex
+ ? getMoveRangeCommandMutations(
+ accessor,
+ {
+ fromUnitId: unitId,
+ fromSubUnitId: subUnitId,
+ toSubUnitId: subUnitId,
+ fromRange: {
+ startRow: index,
+ endRow: rowContentIndex,
+ startColumn: oldRange.startColumn,
+ endColumn: oldRange.endColumn,
+ },
+ toRange: {
+ startRow: index + count,
+ endRow: rowContentIndex + count,
+ startColumn: oldRange.startColumn,
+ endColumn: oldRange.endColumn,
+ },
},
- }
- );
+ { includeSelection: false, includeAutoHeight: false }
+ )
+ : null;
if (moveRangeMutations) {
redos.push(...moveRangeMutations.redos);
undos.push(...moveRangeMutations.undos);
}
+ const formulaMutation = getCalculatedColumnFillMutation(
+ table,
+ unitId,
+ subUnitId,
+ index,
+ index + count - 1,
+ () => accessor.get(LexerTreeBuilder)
+ );
+ if (formulaMutation) {
+ redos.push(formulaMutation);
+ undos.push({
+ id: SetRangeValuesMutation.id,
+ params: SetRangeValuesUndoMutationFactory(accessor, formulaMutation.params as ISetRangeValuesMutationParams),
+ });
+ }
+
return executeTableMutationSequence(accessor, unitId, redos, undos);
},
};
diff --git a/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
index 28cbe668d3..77d9bd553d 100644
--- a/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
+++ b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
@@ -106,18 +106,51 @@ describe('sheets-table mutations', () => {
});
it('SetSheetTableFilterMutation should delegate to TableManager.addFilter', () => {
+ const params = {
+ unitId: 'u1',
+ tableId: 't1',
+ column: 0,
+ tableFilter: { filterType: 'manual', values: ['A'] } as any,
+ };
+ const setFilterOutRows = vi.fn();
+ const getFilterOutRows = vi.fn(() => new Set([2, 4]));
const tableManager = {
addFilter: vi.fn(),
+ getTable: vi.fn(() => ({
+ getSubunitId: () => 's1',
+ getTableFilters: () => ({ getFilterOutRows, setFilterOutRows }),
+ })),
+ toJSON: vi.fn(() => ({ s1: { tables: [], tableFilteredOutRows: [2, 4] } })),
} as unknown as TableManager;
- const result = SetSheetTableFilterMutation.handler(accessorForTableManager(tableManager), {
+ const result = SetSheetTableFilterMutation.handler(accessorForTableManager(tableManager), params);
+
+ expect(result).toBe(true);
+ expect(tableManager.addFilter).toHaveBeenCalledWith('u1', 't1', 0, { filterType: 'manual', values: ['A'] });
+ expect(params).toMatchObject({ filterOutRows: [2, 4], subUnitId: 's1', tableFilteredOutRows: [2, 4] });
+ expect(setFilterOutRows).not.toHaveBeenCalled();
+ });
+
+ it('SetSheetTableFilterMutation should restore cached rows during undo', () => {
+ const setFilterOutRows = vi.fn();
+ const params = {
unitId: 'u1',
tableId: 't1',
column: 0,
- tableFilter: { filterType: 'manual', values: ['A'] } as any,
- });
+ tableFilter: { filterType: 'manual', values: ['old'] } as any,
+ filterOutRows: [2, 5],
+ };
+ const tableManager = {
+ addFilter: vi.fn(),
+ getTable: vi.fn(() => ({
+ getSubunitId: () => 's1',
+ getTableFilters: () => ({ getFilterOutRows: () => new Set([3]), setFilterOutRows }),
+ })),
+ toJSON: vi.fn(() => ({ s1: { tables: [], tableFilteredOutRows: [2, 5] } })),
+ } as unknown as TableManager;
- expect(result).toBe(true);
- expect(tableManager.addFilter).toHaveBeenCalledWith('u1', 't1', 0, { filterType: 'manual', values: ['A'] });
+ expect(SetSheetTableFilterMutation.handler(accessorForTableManager(tableManager), params)).toBe(true);
+ expect(setFilterOutRows).toHaveBeenCalledWith([2, 5]);
+ expect(params).toMatchObject({ subUnitId: 's1', tableFilteredOutRows: [2, 5] });
});
});
diff --git a/packages/sheets-table/src/commands/mutations/set-table-filter.mutation.ts b/packages/sheets-table/src/commands/mutations/set-table-filter.mutation.ts
index d38813ab68..7df76bb1ab 100644
--- a/packages/sheets-table/src/commands/mutations/set-table-filter.mutation.ts
+++ b/packages/sheets-table/src/commands/mutations/set-table-filter.mutation.ts
@@ -24,6 +24,9 @@ export interface ISetSheetTableParams {
tableId: string;
column: number;
tableFilter: ITableFilterItem | undefined;
+ filterOutRows?: number[];
+ subUnitId?: string;
+ tableFilteredOutRows?: number[];
}
export const SetSheetTableFilterMutation: IMutation<ISetSheetTableParams & { tableId: string }> = {
@@ -32,7 +35,18 @@ export const SetSheetTableFilterMutation: IMutation<ISetSheetTableParams & { tab
handler: (accessor, params) => {
const { tableId, unitId, column, tableFilter } = params;
const tableManager = accessor.get(TableManager);
+ const table = tableManager.getTable(unitId, tableId);
tableManager.addFilter(unitId, tableId, column, tableFilter);
+ if (table) {
+ const tableFilters = table.getTableFilters();
+ if (params.filterOutRows) {
+ tableFilters.setFilterOutRows(params.filterOutRows);
+ } else {
+ params.filterOutRows = [...tableFilters.getFilterOutRows()];
+ }
+ params.subUnitId = table.getSubunitId();
+ params.tableFilteredOutRows = tableManager.toJSON(unitId)[params.subUnitId]?.tableFilteredOutRows ?? [];
+ }
return true;
},
};
diff --git a/packages/sheets-table/src/commands/utils/__tests__/calculated-column.spec.ts b/packages/sheets-table/src/commands/utils/__tests__/calculated-column.spec.ts
new file mode 100644
index 0000000000..e137f29b63
--- /dev/null
+++ b/packages/sheets-table/src/commands/utils/__tests__/calculated-column.spec.ts
@@ -0,0 +1,69 @@
+/**
+ * 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 { BooleanNumber, FormulaType, Injector } from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { Table } from '../../../models/table';
+import { getCalculatedColumnFillMutation } from '../calculated-column';
+
+describe('getCalculatedColumnFillMutation', () => {
+ it('fills relative references and marks imported arrays using formal formula metadata', () => {
+ const injector = new Injector([[LexerTreeBuilder]]);
+ try {
+ const table = new Table('table', 'Orders', { startRow: 0, endRow: 9, startColumn: 4, endColumn: 6 }, ['Name', 'Amount', 'Array']);
+ table.getTableColumnByIndex(1)!.formula = 'A2*2';
+ table.getTableColumnByIndex(2)!.formula = '=$A2';
+ table.getTableColumnByIndex(2)!.formulaIsArray = true;
+ const mutation = getCalculatedColumnFillMutation(table, 'unit', 'sheet', 7, 8, () => injector.get(LexerTreeBuilder));
+ expect(mutation?.params).toMatchObject({
+ cellValue: {
+ 7: { 5: { f: '=A8*2', ft: null, v: null }, 6: { f: '=$A8', ref: 'G8', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE } },
+ 8: { 5: { f: '=A9*2' }, 6: { f: '=$A9', ref: 'G9', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE } },
+ },
+ });
+ const stopped = getCalculatedColumnFillMutation(table, 'unit', 'sheet', 7, 8, () => injector.get(LexerTreeBuilder), {
+ columnId: table.getTableColumnByIndex(1)!.id,
+ formula: '',
+ });
+ expect(stopped).toBeUndefined();
+ } finally {
+ injector.dispose();
+ }
+ });
+
+ it.each([
+ ['[@单价]*[@数量]', '=Orders[[#This Row],[单价]]*Orders[[#This Row],[数量]]'],
+ ['[@[单价]]*[@[数量]]', '=Orders[[#This Row],[单价]]*Orders[[#This Row],[数量]]'],
+ ['SUM([单价])+SUM([[#Data],[数量]])', '=SUM(Orders[单价])+SUM(Orders[[#Data],[数量]])'],
+ ['SUM([@[单价]:[数量]])+$A2', '=SUM(Orders[[#This Row],[单价]:[数量]])+$A8'],
+ ['Other[@单价]*[@数量]', '=Other[[#This Row],[单价]]*Orders[[#This Row],[数量]]'],
+ ['IF(A2="[@单价]",[@数量],"a""[数量]")', '=IF(A8="[@单价]",Orders[[#This Row],[数量]],"a""[数量]")'],
+ ["[@[Tax'] rate]]", "=Orders[[#This Row],[Tax'] rate]]"],
+ ["SUM('[other.xlsx]Sheet 1'!A2)+SUM([other]Other[单价])", "=SUM('[other.xlsx]Sheet 1'!A8)+SUM([other]Other[单价])"],
+ ])('fills structured references without changing literals or external qualifiers: %s', (formula, expected) => {
+ const injector = new Injector([[LexerTreeBuilder]]);
+ try {
+ const table = new Table('table', 'Orders', { startRow: 0, endRow: 9, startColumn: 0, endColumn: 2 }, ['单价', '数量', '金额']);
+ table.getTableColumnByIndex(2)!.formula = formula;
+ const mutation = getCalculatedColumnFillMutation(table, 'unit', 'sheet', 7, 7, () => injector.get(LexerTreeBuilder));
+ expect(mutation?.params).toMatchObject({ cellValue: { 7: { 2: { f: expected } } } });
+ expect(table.getTableColumnByIndex(2)!.formula).toBe(formula);
+ } finally {
+ injector.dispose();
+ }
+ });
+});
diff --git a/packages/sheets-table/src/commands/utils/calculated-column.ts b/packages/sheets-table/src/commands/utils/calculated-column.ts
new file mode 100644
index 0000000000..dbe8ff9a02
--- /dev/null
+++ b/packages/sheets-table/src/commands/utils/calculated-column.ts
@@ -0,0 +1,134 @@
+/**
+ * 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 { ICellData, IMutationInfo, IObjectMatrixPrimitiveType } from '@univerjs/core';
+import type { LexerTreeBuilder } from '@univerjs/engine-formula';
+import type { Table } from '../../models/table';
+import type { ITableCalculatedColumnConfig } from '../../types/type';
+import { BooleanNumber, FormulaType } from '@univerjs/core';
+import { serializeRange } from '@univerjs/engine-formula';
+import { SetRangeValuesMutation } from '@univerjs/sheets';
+
+export function getCalculatedColumnFillMutation(
+ table: Table,
+ unitId: string,
+ subUnitId: string,
+ startRow: number,
+ endRow: number,
+ getLexerTreeBuilder: () => LexerTreeBuilder,
+ config?: ITableCalculatedColumnConfig
+): IMutationInfo | undefined {
+ const tableInfo = table.getTableInfo?.();
+ if (!tableInfo) {
+ return;
+ }
+ const firstDataRow = tableInfo.range.startRow + (tableInfo.showHeader ? 1 : 0);
+ const cellValue: IObjectMatrixPrimitiveType<ICellData> = {};
+ let lexerTreeBuilder: LexerTreeBuilder | undefined;
+
+ tableInfo.columns.forEach((column, columnIndex) => {
+ if (config && column.id !== config.columnId) {
+ return;
+ }
+ const formula = (config?.formula ?? column.formula)?.trim();
+ const formulaIsArray = config?.formulaIsArray ?? column.formulaIsArray;
+ if (!formula) {
+ return;
+ }
+
+ const baseFormula = normalizeCalculatedColumnFormula(formula.startsWith('=') ? formula : `=${formula}`, tableInfo.name);
+ const sheetColumn = tableInfo.range.startColumn + columnIndex;
+ lexerTreeBuilder ??= getLexerTreeBuilder();
+ for (let row = startRow; row <= endRow; row++) {
+ cellValue[row] ??= {};
+ const cell: ICellData = {
+ f: lexerTreeBuilder.moveFormulaRefOffset(baseFormula, 0, row - firstDataRow),
+ si: null,
+ ref: null,
+ ft: formulaIsArray ? FormulaType.ARRAY : null,
+ fd: formulaIsArray ? BooleanNumber.FALSE : null,
+ v: null,
+ p: null,
+ t: null,
+ };
+ if (formulaIsArray) {
+ cell.ref = serializeRange({
+ startRow: row,
+ endRow: row,
+ startColumn: sheetColumn,
+ endColumn: sheetColumn,
+ });
+ }
+ cellValue[row][sheetColumn] = cell;
+ }
+ });
+
+ if (!Object.keys(cellValue).length) {
+ return;
+ }
+
+ return {
+ id: SetRangeValuesMutation.id,
+ params: { unitId, subUnitId, cellValue },
+ };
+}
+
+function normalizeCalculatedColumnFormula(formula: string, tableName: string): string {
+ let result = '';
+ for (let index = 0; index < formula.length; index++) {
+ const start = index;
+ const char = formula[index];
+ if (char === '"' || char === "'") {
+ while (++index < formula.length) {
+ if (formula[index] === char) {
+ if (formula[index + 1] !== char) break;
+ index++;
+ }
+ }
+ } else if (char === '[') {
+ let depth = 1;
+ while (++index < formula.length && depth > 0) {
+ if (formula[index] === "'") {
+ index++;
+ } else if (formula[index] === '[') {
+ depth++;
+ } else if (formula[index] === ']') {
+ depth--;
+ }
+ if (depth === 0) break;
+ }
+ if (depth === 0) {
+ const body = formula.slice(start + 1, index);
+ const previous = formula.slice(0, start).trimEnd().slice(-1);
+ const unqualified = !previous || /[=+\-*/^&(<>,;:{]/.test(previous);
+ // External workbook qualifiers are followed by a table/sheet name or '!'.
+ const next = formula.slice(index + 1).trimStart();
+ const qualifier = /^[^+\-*/^&=<>%),;}:\s]/.test(next);
+ if (!qualifier) {
+ const prefix = unqualified ? tableName : '';
+ // The formula engine consumes the explicit OOXML current-row form.
+ const columns = body.slice(1);
+ result += body.startsWith('@')
+ ? `${prefix}[[#This Row],${columns.startsWith('[') ? columns : `[${columns}]`}]`
+ : `${prefix}[${body}]`;
+ continue;
+ }
+ }
+ }
+ result += formula.slice(start, index + 1);
+ }
+ return result;
+}
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
index a049e38caf..573358b1fc 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
@@ -14,11 +14,15 @@
* limitations under the License.
*/
+import type { IActiveDirtyManagerService } from '@univerjs/engine-formula';
import { RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { SetSheetTableFilterMutation } from '../../commands/mutations/set-table-filter.mutation';
import { SheetTableFormulaController } from '../sheet-table-formula.controller';
+type DirtyConversion = Parameters<IActiveDirtyManagerService['register']>[1];
+
describe('SheetTableFormulaController', () => {
it('should sync super table metadata on add/range/name/delete events', () => {
const tableAdd$ = new Subject<any>();
@@ -49,7 +53,30 @@ describe('SheetTableFormulaController', () => {
const executeCommand = vi.fn();
const commandService = { executeCommand };
- const controller = new SheetTableFormulaController(tableManager as any, commandService as any);
+ const dirtyConversions = new Map<string, DirtyConversion>();
+ const activeDirtyManagerService = {
+ register: vi.fn((id: string, conversion: DirtyConversion) => dirtyConversions.set(id, conversion)),
+ remove: vi.fn((id: string) => dirtyConversions.delete(id)),
+ };
+
+ const controller = new SheetTableFormulaController(
+ tableManager as any,
+ commandService as any,
+ activeDirtyManagerService as any
+ );
+
+ const filterDirtyData = dirtyConversions.get(SetSheetTableFilterMutation.id)?.getDirtyData({
+ id: SetSheetTableFilterMutation.id,
+ params: { unitId: 'u1', tableId: 't1', column: 0, tableFilter: undefined },
+ } as any);
+ expect(filterDirtyData).toEqual({
+ dirtyRanges: [{
+ unitId: 'u1',
+ sheetId: 's1',
+ range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },
+ }],
+ clearDependencyTreeCache: { u1: { s1: '1' } },
+ });
tableAdd$.next({ unitId: 'u1', tableId: 't1' });
@@ -93,5 +120,6 @@ describe('SheetTableFormulaController', () => {
expect(executeCommand.mock.calls.every((call) => call[2]?.onlyLocal === true)).toBe(true);
controller.dispose();
+ expect(activeDirtyManagerService.remove).toHaveBeenCalledWith(SetSheetTableFilterMutation.id);
});
});
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
index d51f205878..0da48b86fe 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
@@ -38,6 +38,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import {
+ ActiveDirtyManagerService,
AstRootNodeFactory,
AstTreeBuilder,
CalculateFormulaService,
@@ -53,6 +54,7 @@ import {
generateExecuteAstNodeData,
getObjectValue,
HyperlinkEngineFormulaService,
+ IActiveDirtyManagerService,
ICalculateFormulaService,
IDefinedNamesService,
IFormulaCurrentConfigService,
@@ -250,6 +252,7 @@ function createWorkbookData(): IWorkbookData {
function createControllerTestBed() {
const dependencies: Dependency[] = [
[ICalculateFormulaService, { useClass: CalculateFormulaService }],
+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
[Lexer],
[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],
[IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }],
diff --git a/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
index 3ce7c539fe..37adbab2d3 100644
--- a/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DateSystem } from '@univerjs/core';
+import { DateSystem, toDisposable } from '@univerjs/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { TableFilterController } from '../table-filter.controller';
@@ -43,7 +43,7 @@ describe('TableFilterController', () => {
tableFilterChanged$,
tableInitStatus$,
getTable: vi.fn(() => mainTable),
- getTablesBySubunitId: vi.fn(() => [mainTable, extraTable]),
+ getTablesBySubunitId: vi.fn((_unitId, subUnitId) => subUnitId === 's1' ? [mainTable, extraTable] : []),
};
let rowFilteredHandler: any;
@@ -74,10 +74,21 @@ describe('TableFilterController', () => {
updateZebraCrossingCache: vi.fn(),
};
+ let formulaRowFiltered: ((unitId: string, subUnitId: string, row: number) => boolean) | undefined;
+ const sheetRowFilteredService = {
+ register: vi.fn((callback) => {
+ formulaRowFiltered = callback;
+ return toDisposable(() => {
+ formulaRowFiltered = undefined;
+ });
+ }),
+ };
+
const controller = new TableFilterController(
tableManager as any,
sheetInterceptorService as any,
univerInstanceService as any,
+ sheetRowFilteredService as any,
zebraCrossingCacheController as any
);
@@ -90,6 +101,7 @@ describe('TableFilterController', () => {
);
expect(zebraCrossingCacheController.updateZebraCrossingCache).toHaveBeenCalledWith('u1', 's1');
expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's1', row: 4 }, vi.fn(() => false))).toBe(true);
+ expect(formulaRowFiltered?.('u1', 's1', 4)).toBe(true);
expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's2', row: 4 }, vi.fn(() => false))).toBe(false);
expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's1', row: 9 }, vi.fn(() => false))).toBe(false);
diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
index 10997d35d8..67612d372f 100644
--- a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
@@ -15,18 +15,45 @@
*/
import type { IRemoveSuperTableMutationParam, ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';
+import type { ISetSheetTableParams } from '../commands/mutations/set-table-filter.mutation';
import type { Table } from '../models/table';
-import { Disposable, ICommandService, Inject } from '@univerjs/core';
-import { RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';
+import { Disposable, ICommandService, Inject, toDisposable } from '@univerjs/core';
+import { IActiveDirtyManagerService, RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';
+import { SetSheetTableFilterMutation } from '../commands/mutations/set-table-filter.mutation';
import { TableManager } from '../models/table-manager';
export class SheetTableFormulaController extends Disposable {
constructor(
@Inject(TableManager) private _tableManager: TableManager,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService
) {
super();
this._initRangeListener();
+ this._initFilterDirtyRange();
+ }
+
+ private _initFilterDirtyRange() {
+ this._activeDirtyManagerService.register(SetSheetTableFilterMutation.id, {
+ commandId: SetSheetTableFilterMutation.id,
+ getDirtyData: (command) => {
+ const params = command.params as ISetSheetTableParams;
+ const table = this._tableManager.getTableById(params.unitId, params.tableId);
+ if (!table) {
+ return {};
+ }
+
+ const { subUnitId, range } = table.getTableInfo();
+ return {
+ dirtyRanges: [{ unitId: params.unitId, sheetId: subUnitId, range }],
+ clearDependencyTreeCache: { [params.unitId]: { [subUnitId]: '1' } },
+ };
+ },
+ });
+
+ this.disposeWithMe(toDisposable(() => {
+ this._activeDirtyManagerService.remove(SetSheetTableFilterMutation.id);
+ }));
}
private _initRangeListener() {
diff --git a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
index 784d3fffe3..5cbe62338e 100644
--- a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
@@ -32,6 +32,7 @@ import {
LocaleService,
Rectangle,
} from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import {
getSheetCommandTarget,
InsertColCommand,
@@ -48,6 +49,7 @@ import {
import { AddSheetTableMutation } from '../commands/mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../commands/mutations/delete-sheet-table.mutation';
import { SetSheetTableMutation } from '../commands/mutations/set-sheet-table.mutation';
+import { getCalculatedColumnFillMutation } from '../commands/utils/calculated-column';
import { TableManager } from '../models/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../types/type';
import { convertCellDataToString, getColumnName } from '../util';
@@ -131,6 +133,18 @@ export class SheetTableRefRangeController extends Disposable {
},
});
+ const formulaMutation = getCalculatedColumnFillMutation(
+ table,
+ unitId,
+ subUnitId,
+ range.startRow,
+ range.endRow,
+ () => this._injector.get(LexerTreeBuilder)
+ );
+ if (formulaMutation) {
+ redos.push(formulaMutation);
+ }
+
undos.push({
id: SetSheetTableMutation.id,
params: {
diff --git a/packages/sheets-table/src/controllers/table-filter.controller.ts b/packages/sheets-table/src/controllers/table-filter.controller.ts
index ef233e507c..e9f2b13c3d 100644
--- a/packages/sheets-table/src/controllers/table-filter.controller.ts
+++ b/packages/sheets-table/src/controllers/table-filter.controller.ts
@@ -17,6 +17,7 @@
import type { Workbook } from '@univerjs/core';
import type { Subscription } from 'rxjs';
import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { ISheetRowFilteredService } from '@univerjs/engine-formula';
import { getSheetCommandTarget, INTERCEPTOR_POINT, SheetInterceptorService, ZebraCrossingCacheController } from '@univerjs/sheets';
import { filter, switchMap } from 'rxjs';
import { TableManager } from '../models/table-manager';
@@ -29,14 +30,22 @@ export class TableFilterController extends Disposable {
@Inject(TableManager) private _tableManager: TableManager,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(ISheetRowFilteredService) private readonly _sheetRowFilteredService: ISheetRowFilteredService,
@Inject(ZebraCrossingCacheController) private readonly _zebraCrossingCacheController: ZebraCrossingCacheController
) {
super();
this.registerFilterChangeEvent();
this.initTableHiddenRowIntercept();
+ this._registerFormulaRowFiltered();
this._initFilteredOutRows();
}
+ private _registerFormulaRowFiltered(): void {
+ this.disposeWithMe(this._sheetRowFilteredService.register((unitId, subUnitId, row) => {
+ return this._getTableFilteredOutRows(unitId, subUnitId).has(row);
+ }));
+ }
+
initTableHiddenRowIntercept() {
this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.ROW_FILTERED, {
// Priority must be higher than sheet filtering, because filtering has no next, and those below filtering will not trigger interceptor
@@ -106,7 +115,11 @@ export class TableFilterController extends Disposable {
}
private _getTableFilteredOutRows(unitId: string, subUnitId: string): Set<number> {
- return this._tableFilteredOutRows.get(this._getSheetKey(unitId, subUnitId)) ?? new Set();
+ const key = this._getSheetKey(unitId, subUnitId);
+ if (!this._tableFilteredOutRows.has(key)) {
+ this._refreshTableFilteredOutRows(unitId, subUnitId);
+ }
+ return this._tableFilteredOutRows.get(key) ?? new Set();
}
private _getSheetKey(unitId: string, subUnitId: string): string {
diff --git a/packages/sheets-table/src/facade/f-worksheet.ts b/packages/sheets-table/src/facade/f-worksheet.ts
index 925876eebb..d3bead4d14 100644
--- a/packages/sheets-table/src/facade/f-worksheet.ts
+++ b/packages/sheets-table/src/facade/f-worksheet.ts
@@ -20,12 +20,13 @@ import type {
IDeleteSheetTableParams,
ISetSheetTableCommandParams,
ISetSheetTableParams,
+ ITableFilterButtonConfig,
ITableFilterItem,
ITableInfoWithUnitId,
ITableOptions,
ITableRange,
} from '@univerjs/sheets-table';
-import { cellToRange, customNameCharacterCheck, LocaleService, Rectangle } from '@univerjs/core';
+import { cellToRange, customNameCharacterCheck, Rectangle } from '@univerjs/core';
import { RangeThemeStyle } from '@univerjs/sheets';
import {
AddSheetTableCommand,
@@ -34,6 +35,7 @@ import {
SetSheetTableCommand,
SetSheetTableFilterCommand,
SheetTableService,
+ TableManager,
} from '@univerjs/sheets-table';
import { FWorksheet } from '@univerjs/sheets/facade';
@@ -41,6 +43,23 @@ import { FWorksheet } from '@univerjs/sheets/facade';
* @ignore
*/
export interface IFWorksheetTableMixin {
+ /**
+ * Apply a formula to every data row of a table column, excluding header and footer.
+ * References are relative to the first data row. Empty string stops future auto-fill and preserves cells.
+ * @param tableId Table ID in this worksheet.
+ * @param columnId Stable column ID from getSubTableInfos().
+ * @param formula Formula to apply, or an empty string to stop automatic filling.
+ * @returns Whether the undoable update succeeded synchronously.
+ */
+ setTableColumnFormula(tableId: string, columnId: string, formula: string): boolean;
+ /**
+ * Update table filter button visibility without clearing filter criteria.
+ * Column overrides use stable column IDs from getSubTableInfos().
+ * @param tableId Table ID in this worksheet.
+ * @param config Partial table and column button visibility settings.
+ * @returns Whether the update succeeded synchronously.
+ */
+ setTableFilterButtons(tableId: string, config: ITableFilterButtonConfig): boolean;
/**
* Add a table to the worksheet
* @param {string} tableName The table name
@@ -354,13 +373,33 @@ export interface IFWorksheetTableMixin {
}
export class FWorksheetTableMixin extends FWorksheet implements IFWorksheetTableMixin {
+ override setTableColumnFormula(tableId: string, columnId: string, formula: string): boolean {
+ const unitId = this.getWorkbook().getUnitId();
+ const table = this._injector.get(TableManager).getTableById(unitId, tableId);
+ if (!table || table.getSubunitId() !== this.getSheetId()) {
+ return false;
+ }
+ return this._commandService.syncExecuteCommand(SetSheetTableCommand.id, {
+ unitId,
+ tableId,
+ calculatedColumn: { columnId, formula },
+ });
+ }
+
+ override setTableFilterButtons(tableId: string, config: ITableFilterButtonConfig): boolean {
+ const unitId = this.getWorkbook().getUnitId();
+ const table = this._injector.get(TableManager).getTableById(unitId, tableId);
+ if (!table || table.getSubunitId() !== this.getSheetId()) {
+ return false;
+ }
+ return this._commandService.syncExecuteCommand(SetSheetTableCommand.id, { unitId, tableId, filterButtons: config });
+ }
+
override addTable(tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<boolean> | boolean {
const subUnitId = this.getSheetId();
const workbook = this.getWorkbook();
const unitId = workbook.getUnitId();
- const localeService = this._injector.get(LocaleService);
-
const sheetNameSet = new Set<string>();
if (workbook) {
workbook.getSheets().forEach((sheet) => {
diff --git a/packages/sheets-table/src/index.ts b/packages/sheets-table/src/index.ts
index 824d16c780..f589c605ae 100644
--- a/packages/sheets-table/src/index.ts
+++ b/packages/sheets-table/src/index.ts
@@ -60,10 +60,12 @@ export {
TableStringCompareTypeEnum,
} from './types/enum';
export type {
+ ITableCalculatedColumnConfig,
ITableColorFilterItem,
ITableColumnJson,
ITableConditionFilterItem,
ITableData,
+ ITableFilterButtonConfig,
ITableFilterItem,
ITableInfo,
ITableInfoWithUnitId,
diff --git a/packages/sheets-table/src/models/__tests__/table-manager.spec.ts b/packages/sheets-table/src/models/__tests__/table-manager.spec.ts
index e81e4ae8e2..fa17c4f0bd 100644
--- a/packages/sheets-table/src/models/__tests__/table-manager.spec.ts
+++ b/packages/sheets-table/src/models/__tests__/table-manager.spec.ts
@@ -17,6 +17,7 @@
import type { IWorkbookData, UnitModel } from '@univerjs/core';
import { LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
+import { SheetsTableSortStateEnum, TableColumnDataTypeEnum, TableColumnFilterTypeEnum } from '../../types/enum';
import { TableManager } from '../table-manager';
describe('TableManager', () => {
@@ -40,12 +41,15 @@ describe('TableManager', () => {
'sheet-1': {
id: 'sheet-1',
name: 'Sheet1',
- rowCount: 2,
+ rowCount: 4,
columnCount: 1,
cellData: {
0: {
0: { v: 'Name' },
},
+ 1: { 0: { v: 'renamed' } },
+ 2: { 0: { v: 'renamed' } },
+ 3: { 0: { v: 'renamed' } },
},
},
},
@@ -66,22 +70,44 @@ describe('TableManager', () => {
range: {
startRow: 0,
startColumn: 0,
- endRow: 1,
+ endRow: 3,
endColumn: 0,
},
options: {
tableStyleId: 'ImportedTableStyle',
+ showFooter: true,
+ showAutoFilter: false,
},
- filters: {},
- columns: [],
+ filters: {
+ tableColumnFilterList: [{ filterType: TableColumnFilterTypeEnum.manual, values: ['original'] }],
+ tableSortInfo: { columnIndex: 0, sortState: SheetsTableSortStateEnum.Asc },
+ },
+ columns: [{
+ id: 'column-1',
+ displayName: 'Name',
+ dataType: TableColumnDataTypeEnum.String,
+ formula: '',
+ showFilterButton: false,
+ meta: {},
+ style: {},
+ }],
meta: {},
},
],
- tableFilteredOutRows: [],
+ tableFilteredOutRows: [2],
},
});
expect(events).toHaveLength(1);
expect(events[0].tableStyleId).toBe('ImportedTableStyle');
+ const serialized = manager.toJSON('unit-1')['sheet-1'];
+ expect(serialized.tableFilteredOutRows).toEqual([2]);
+ expect(serialized.tables[0].options.showFooter).toBe(true);
+ expect(serialized.tables[0].options.showAutoFilter).toBe(false);
+ expect(serialized.tables[0].columns[0].showFilterButton).toBe(false);
+ expect(serialized.tables[0].filters.tableSortInfo).toEqual({
+ columnIndex: 0,
+ sortState: SheetsTableSortStateEnum.Asc,
+ });
});
});
diff --git a/packages/sheets-table/src/models/__tests__/table-model.spec.ts b/packages/sheets-table/src/models/__tests__/table-model.spec.ts
index 3132c02945..5c83b6df8d 100644
--- a/packages/sheets-table/src/models/__tests__/table-model.spec.ts
+++ b/packages/sheets-table/src/models/__tests__/table-model.spec.ts
@@ -31,6 +31,84 @@ import { TableColumn } from '../table-column';
import { TableFilters } from '../table-filter';
describe('Table model', () => {
+ it('restores a visible footer from constructor options', () => {
+ const table = new Table(
+ 'table-1',
+ 'Sales',
+ { startRow: 0, endRow: 4, startColumn: 0, endColumn: 1 },
+ ['Region', 'Amount'],
+ { showFooter: true }
+ );
+
+ expect(table.isShowFooter()).toBe(true);
+ expect(table.getTableFilterRange()).toEqual({
+ startRow: 1,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 1,
+ });
+ expect(table.toJSON().options.showFooter).toBe(true);
+ });
+
+ it('preserves dormant totals row definitions while the footer is hidden', () => {
+ const table = new Table('placeholder', 'Placeholder', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, []);
+ table.fromJSON({
+ id: 'table-1',
+ name: 'StartTbl',
+ range: { startRow: 0, endRow: 4, startColumn: 0, endColumn: 0 },
+ options: {
+ showFooter: false,
+ },
+ filters: {},
+ columns: [{
+ id: 'column-time',
+ displayName: 'Time',
+ dataType: TableColumnDataTypeEnum.String,
+ formula: '+StartTbl[Time]+0.5/24',
+ formulaIsArray: true,
+ totalsRowFunction: 'custom',
+ totalsRowFormula: '+StartTbl[Time]+0.5/24',
+ meta: {},
+ style: {},
+ }],
+ meta: {},
+ });
+
+ const snapshot = table.toJSON();
+ const restored = new Table('placeholder', 'Placeholder', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, []);
+ restored.fromJSON(snapshot);
+
+ expect(restored.toJSON().options.showFooter).toBe(false);
+ expect(restored.toJSON().columns.find((column) => column.id === 'column-time')).toEqual(expect.objectContaining({
+ formulaIsArray: true,
+ totalsRowFunction: 'custom',
+ totalsRowFormula: '+StartTbl[Time]+0.5/24',
+ }));
+ });
+
+ it('preserves table and column filter-button visibility', () => {
+ const table = new Table('placeholder', 'Placeholder', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, []);
+ table.fromJSON({
+ id: 'table-1',
+ name: 'HiddenFilters',
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },
+ options: { showAutoFilter: false },
+ filters: {},
+ columns: [
+ { id: 'c1', displayName: 'Visible', dataType: TableColumnDataTypeEnum.String, formula: '', meta: {}, style: {} },
+ { id: 'c2', displayName: 'Hidden', dataType: TableColumnDataTypeEnum.String, formula: '', showFilterButton: false, meta: {}, style: {} },
+ ],
+ meta: {},
+ });
+
+ const snapshot = table.toJSON();
+ expect(table.isShowAutoFilter()).toBe(false);
+ expect(table.getTableInfo().showAutoFilter).toBe(false);
+ expect(snapshot.options.showAutoFilter).toBe(false);
+ expect(snapshot.columns[0].showFilterButton).toBe(true);
+ expect(snapshot.columns[1].showFilterButton).toBe(false);
+ });
+
it('builds a table from headers, tracks metadata, and serializes user changes', () => {
const table = new Table(
'table-1',
@@ -80,6 +158,7 @@ describe('Table model', () => {
options: {
showHeader: true,
showFooter: false,
+ showAutoFilter: true,
},
tableStyleId: 'theme-2',
});
@@ -163,6 +242,13 @@ describe('TableFilters', () => {
tableSortInfo: { columnIndex: 0, sortState: SheetsTableSortStateEnum.Asc },
});
+ filters.setColumnFilter(0, undefined);
+ filters.setColumnFilter(1, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['12', '20'],
+ });
+ expect([...filters.doFilter(sheet as never, range)]).toEqual([1, 3]);
+
filters.dispose();
expect(filters.toJSON().tableColumnFilterList).toEqual([]);
});
diff --git a/packages/sheets-table/src/models/table-column.ts b/packages/sheets-table/src/models/table-column.ts
index ed8eb9050f..cde4ebf328 100644
--- a/packages/sheets-table/src/models/table-column.ts
+++ b/packages/sheets-table/src/models/table-column.ts
@@ -23,6 +23,11 @@ export class TableColumn {
id: string;
displayName: string;
formula: string;
+ formulaIsArray?: boolean;
+ totalsRowLabel?: string;
+ totalsRowFunction?: string;
+ totalsRowFormula?: string;
+ showFilterButton: boolean;
meta: TableMetaType;
style: IStyleData;
constructor(id: string, name: string) {
@@ -30,6 +35,7 @@ export class TableColumn {
this.displayName = name;
this.dataType = TableColumnDataTypeEnum.String;
this.formula = '';
+ this.showFilterButton = true;
this.meta = {};
this.style = {};
}
@@ -52,6 +58,11 @@ export class TableColumn {
displayName: this.displayName,
dataType: this.dataType,
formula: this.formula,
+ formulaIsArray: this.formulaIsArray,
+ totalsRowLabel: this.totalsRowLabel,
+ totalsRowFunction: this.totalsRowFunction,
+ totalsRowFormula: this.totalsRowFormula,
+ showFilterButton: this.showFilterButton,
meta: this.meta,
style: this.style,
};
@@ -62,7 +73,16 @@ export class TableColumn {
this.displayName = json.displayName;
this.dataType = json.dataType;
this.formula = json.formula;
+ this.formulaIsArray = json.formulaIsArray;
+ this.totalsRowLabel = json.totalsRowLabel;
+ this.totalsRowFunction = json.totalsRowFunction;
+ this.totalsRowFormula = json.totalsRowFormula;
+ this.showFilterButton = json.showFilterButton ?? true;
this.meta = json.meta;
this.style = json.style;
}
+
+ isShowFilterButton() {
+ return this.showFilterButton;
+ }
}
diff --git a/packages/sheets-table/src/models/table-filter.ts b/packages/sheets-table/src/models/table-filter.ts
index edde9d8522..75a95b8866 100644
--- a/packages/sheets-table/src/models/table-filter.ts
+++ b/packages/sheets-table/src/models/table-filter.ts
@@ -26,7 +26,7 @@ import { getCellValueWithConditionType, getConditionExecuteFunc, isNumberDynamic
export class TableFilters {
private _tableColumnFilterList: (ITableFilterItem | undefined)[];
private _tableSortInfo?: { columnIndex: number; sortState: SheetsTableSortStateEnum };
- private _filterOutRows: Set<number>;
+ private _filterOutRows = new Set<number>();
constructor() {
this._tableColumnFilterList = [];
}
@@ -73,6 +73,10 @@ export class TableFilters {
return this._filterOutRows;
}
+ setFilterOutRows(rows: Iterable<number>) {
+ this._filterOutRows = new Set(rows);
+ }
+
doFilter(sheet: Worksheet, range: ITableRange, dateSystem = DateSystem.Date1900) {
const filterOutRows = new Set<number>();
const tableColumnFilterList = this._tableColumnFilterList;
@@ -136,11 +140,11 @@ export class TableFilters {
getExecuteFunc(sheet: Worksheet, range: ITableRange, columnIndex: number, filter: ITableFilterItem): (value: any) => boolean {
if (filter.filterType === TableColumnFilterTypeEnum.manual) {
const valuesSet = new Set(filter.values);
- return (value: string) => {
+ return (value: string | number) => {
if (value == null) {
return valuesSet.has(TABLE_FILTER_EMPTY_VALUE);
}
- return valuesSet.has(value);
+ return valuesSet.has(String(value));
};
} else if (filter.filterType === TableColumnFilterTypeEnum.condition) {
const isDynamic = isNumberDynamicFilter(filter.filterInfo.compareType);
@@ -183,5 +187,6 @@ export class TableFilters {
dispose() {
this._tableColumnFilterList = [];
+ this._filterOutRows = new Set();
}
}
diff --git a/packages/sheets-table/src/models/table-manager.ts b/packages/sheets-table/src/models/table-manager.ts
index 23d5b26a26..ffa33e53c3 100644
--- a/packages/sheets-table/src/models/table-manager.ts
+++ b/packages/sheets-table/src/models/table-manager.ts
@@ -172,7 +172,7 @@ export class TableManager extends Disposable {
}
const filterRanges: ITableRangeWithState[] = [];
unitMap.forEach((table) => {
- if (table.getSubunitId() === subUnitId && table.isShowHeader()) {
+ if (table.getSubunitId() === subUnitId && table.isShowHeader() && table.isShowAutoFilter()) {
filterRanges.push({
tableId: table.getId(),
range: table.getRange(),
@@ -367,9 +367,29 @@ export class TableManager extends Disposable {
setTableByConfig(unitId: string, tableId: string, config: ITableSetConfig) {
const unitMap = this._tableMap.get(unitId);
const table = unitMap?.get(tableId);
- if (!table) return;
+ if (!table) {
+ return;
+ }
const subUnitId = table.getSubunitId();
- const { name, updateRange, rowColOperation, theme, sortInfo, options } = config;
+ const { name, updateRange, rowColOperation, theme, sortInfo, options, filterButtons } = config;
+ if (config.calculatedColumn) {
+ const column = table.getColumn(config.calculatedColumn.columnId);
+ if (column) {
+ column.formula = config.calculatedColumn.formula;
+ column.formulaIsArray = config.calculatedColumn.formulaIsArray;
+ }
+ }
+ if (filterButtons) {
+ if (filterButtons.showAutoFilter !== undefined) {
+ table.setShowAutoFilter(filterButtons.showAutoFilter);
+ }
+ for (const [columnId, visible] of Object.entries(filterButtons.columns ?? {})) {
+ const column = table.getColumn(columnId);
+ if (column) {
+ column.showFilterButton = visible;
+ }
+ }
+ }
if (name) {
const oldTableName = table.getDisplayName();
table.setDisplayName(name);
@@ -459,6 +479,7 @@ export class TableManager extends Disposable {
if (!tables) {
return;
}
+ const cachedFilteredOutRows = data[subUnitId].tableFilteredOutRows;
tables.forEach((table) => {
const header = this.getColumnHeader(unitId, subUnitId, table.range);
const tableInstance = new Table(table.id, table.name, table.range, header, table.options);
@@ -469,7 +490,14 @@ export class TableManager extends Disposable {
if (table.filters) {
const tableFilter = tableInstance.getTableFilters();
tableFilter.fromJSON(table.filters);
- tableFilter.doFilter(sheet, tableInstance.getTableFilterRange(), target.workbook.getDateSystem());
+ if (Array.isArray(cachedFilteredOutRows)) {
+ const { startRow, endRow } = tableInstance.getTableFilterRange();
+ tableFilter.setFilterOutRows(
+ cachedFilteredOutRows.filter((row) => row >= startRow && row <= endRow)
+ );
+ } else {
+ tableFilter.doFilter(sheet, tableInstance.getTableFilterRange(), target.workbook.getDateSystem());
+ }
}
tableInstance.setSubunitId(subUnitId);
unitMap.set(table.id, tableInstance);
diff --git a/packages/sheets-table/src/models/table.ts b/packages/sheets-table/src/models/table.ts
index e45322d080..ed9696a43a 100644
--- a/packages/sheets-table/src/models/table.ts
+++ b/packages/sheets-table/src/models/table.ts
@@ -29,6 +29,7 @@ export class Table {
private _tableStyleId?: string;
private _showHeader: boolean;
private _showFooter: boolean;
+ private _showAutoFilter: boolean;
private _range: ITableRange;
private _columns: Map<string, TableColumn> = new Map();
private _columnOrder: string[] = [];
@@ -48,8 +49,8 @@ export class Table {
_init(header: string[], options: ITableOptions) {
this._tableStyleId = options?.tableStyleId;
this._showHeader = options?.showHeader ?? true;
- // Summarization is not supported yet. Footer is not displayed yet.
- this._showFooter = false;
+ this._showFooter = options?.showFooter ?? false;
+ this._showAutoFilter = options?.showAutoFilter ?? true;
// init table columns
const range = this.getRange();
const startColumn = range.startColumn;
@@ -216,6 +217,14 @@ export class Table {
return this._showFooter ?? false;
}
+ isShowAutoFilter() {
+ return this._showAutoFilter ?? true;
+ }
+
+ setShowAutoFilter(showAutoFilter: boolean) {
+ this._showAutoFilter = showAutoFilter;
+ }
+
getTableInfo(): ITableInfo {
return {
id: this._id,
@@ -224,6 +233,7 @@ export class Table {
range: this.getRangeInfo(),
meta: this.tableMeta,
showHeader: this._showHeader,
+ showAutoFilter: this._showAutoFilter,
columns: this._columnOrder.map((columnId) => this._columns.get(columnId)!.toJSON()),
};
}
@@ -235,6 +245,7 @@ export class Table {
options: {
showHeader: this._showHeader,
showFooter: this._showFooter,
+ showAutoFilter: this._showAutoFilter,
},
tableStyleId: this._tableStyleId,
};
@@ -256,6 +267,7 @@ export class Table {
options: {
showHeader: this._showHeader,
showFooter: this._showFooter,
+ showAutoFilter: this._showAutoFilter,
tableStyleId: this._tableStyleId,
},
// TODO: support filter
@@ -273,6 +285,9 @@ export class Table {
this._tableStyleId = json.options.tableStyleId || '';
this._showHeader = json.options.showHeader ?? true;
this._showFooter = json.options.showFooter ?? true;
+ this._showAutoFilter = json.options.showAutoFilter ?? true;
+ this._columns.clear();
+ this._columnOrder = [];
const columns = json.columns;
columns.forEach((column) => {
const tableColumn = new TableColumn(column.id, column.displayName);
@@ -290,6 +305,7 @@ export class Table {
this._tableStyleId = '';
this._showHeader = true;
this._showFooter = true;
+ this._showAutoFilter = true;
// @ts-ignore
delete this._range;
this._columns.clear();
diff --git a/packages/sheets-table/src/types/type.ts b/packages/sheets-table/src/types/type.ts
index 1bb92f8c68..225b0e522c 100644
--- a/packages/sheets-table/src/types/type.ts
+++ b/packages/sheets-table/src/types/type.ts
@@ -15,7 +15,16 @@
*/
import type { IRange, IStyleData, Nullable } from '@univerjs/core';
-import type { SheetsTableButtonStateEnum, SheetsTableSortStateEnum, TableColumnDataTypeEnum, TableColumnFilterTypeEnum, TableConditionTypeEnum, TableDateCompareTypeEnum, TableNumberCompareTypeEnum, TableStringCompareTypeEnum } from './enum';
+import type {
+ SheetsTableButtonStateEnum,
+ SheetsTableSortStateEnum,
+ TableColumnDataTypeEnum,
+ TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
+ TableDateCompareTypeEnum,
+ TableNumberCompareTypeEnum,
+ TableStringCompareTypeEnum,
+} from './enum';
export interface ITableRange {
startRow: number;
@@ -35,6 +44,11 @@ export interface ITableOptions {
* @todo not support yet
*/
showFooter?: boolean;
+ /**
+ * Whether the table has an AutoFilter control.
+ * @default true
+ */
+ showAutoFilter?: boolean;
/**
* The table style id. If the property is empty, the default style will be used.
* @default: table-default-0 ~ table-default-5
@@ -146,7 +160,24 @@ export interface ITableRangeRowColOperation {
columnsJson?: ITableColumnJson[];
}
+/** Changes button visibility without clearing existing filter criteria. */
+export interface ITableFilterButtonConfig {
+ showAutoFilter?: boolean;
+ /** Partial update keyed by stable table column ID, not worksheet column index. */
+ columns?: Record<string, boolean>;
+}
+
+/** Formula is anchored at the first data row; an empty formula stops automatic filling. */
+export interface ITableCalculatedColumnConfig {
+ columnId: string;
+ formula: string;
+ /** Preserve imported array semantics when omitted. */
+ formulaIsArray?: boolean;
+}
+
export interface ITableSetConfig {
+ calculatedColumn?: ITableCalculatedColumnConfig;
+ filterButtons?: ITableFilterButtonConfig;
name?: string;
updateRange?: ITableRangeUpdate;
rowColOperation?: ITableRangeRowColOperation;
@@ -199,6 +230,15 @@ export interface ITableColumnJson {
id: string;
displayName: string;
formula: string;
+ formulaIsArray?: boolean;
+ totalsRowLabel?: string;
+ totalsRowFunction?: string;
+ totalsRowFormula?: string;
+ /**
+ * Whether to show the filter button for this table column.
+ * @default true
+ */
+ showFilterButton?: boolean;
meta: TableMetaType;
style: IStyleData;
}
@@ -221,6 +261,7 @@ export interface ITableInfo {
meta: TableMetaType;
columns: ITableColumnJson[];
showHeader: boolean;
+ showAutoFilter: boolean;
}
export interface ITableInfoWithUnitId extends ITableInfo {
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts
index 1766fce9f1..da6d326e8c 100644
--- a/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts
@@ -119,11 +119,13 @@ describe('FRangeSheetsThreadCommentMixin', () => {
await expect(range.addCommentAsync('Agent review', {
id: 'agent-comment',
personId: 'agent-user',
+ authorName: 'Imported author',
})).resolves.toBe(true);
expect(commandService.executeCommand).toHaveBeenCalledWith(AddCommentCommand.id, expect.objectContaining({
comment: expect.objectContaining({
id: 'agent-comment',
personId: 'agent-user',
+ authorName: 'Imported author',
text: expect.objectContaining({ dataStream: 'Agent review\r\n' }),
}),
}));
diff --git a/packages/sheets-thread-comment/src/facade/f-range.ts b/packages/sheets-thread-comment/src/facade/f-range.ts
index 10a5652f24..1f90ee83d2 100644
--- a/packages/sheets-thread-comment/src/facade/f-range.ts
+++ b/packages/sheets-thread-comment/src/facade/f-range.ts
@@ -22,7 +22,7 @@ import { FTheadCommentBuilder, FThreadComment } from './f-thread-comment';
export type ISheetCellCommentCreateOptions = Pick<
ThreadComment.ICreateThreadCommentOptions,
- 'attachments' | 'dateTime' | 'id' | 'personId' | 'threadId'
+ 'attachments' | 'authorName' | 'dateTime' | 'id' | 'personId' | 'threadId'
>;
interface IRangeCommentDependencies {
@@ -210,6 +210,7 @@ export class FRangeSheetsThreadCommentMixin extends FRange implements IFRangeShe
id: firstNonEmpty(options.id, commentData?.id),
ref: refStr,
personId: firstNonEmpty(options.personId, commentData?.personId, currentUser.userID),
+ authorName: options.authorName ?? commentData?.authorName,
parentId: currentComment?.id,
unitId,
subUnitId: sheetId,
diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
index 8fb8ba9211..d35444a76a 100644
--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
@@ -589,6 +589,8 @@ export class SheetClipboardController extends RxDisposable {
[range.rows[0]]: {
[range.cols[0]]: {
f: text,
+ ft: null,
+ fd: null,
v: null,
p: null,
},
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
index 26f65a9eb2..463c3b93ae 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
@@ -15,9 +15,46 @@
*/
import type { ICellData } from '@univerjs/core';
-import { CellValueType, Styles, Tools } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CellValueType,
+ FormulaType,
+ LocaleService,
+ LocaleType,
+ Styles,
+ Tools,
+} from '@univerjs/core';
+import { FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
import { describe, expect, it } from 'vitest';
-import { getComparableCellData } from '../editing.render-controller';
+import { getCellDataByInput, getComparableCellData } from '../editing.render-controller';
+import { createTestBed } from './create-test-bed';
+
+describe('imported formula metadata when editing', () => {
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])('clears copied metadata on edits and keeps unchanged formulas (fd=%s)', (fd) => {
+ const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);
+ try {
+ const localeService = testBed.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ const previous: ICellData = { f: '=SUM(A1:A3)', ft: FormulaType.ARRAY, fd, v: 6 };
+ const parseInput = (input: string, cell: ICellData) => getCellDataByInput(
+ cell,
+ { id: 'editor', body: { dataStream: `${input}\r\n` }, documentStyle: {} },
+ testBed.get(LexerTreeBuilder),
+ localeService,
+ testBed.get(IFunctionService),
+ testBed.sheet.getStyles()
+ );
+ for (const input of ['=2+2', 'plain text', '']) {
+ expect(parseInput(input, { ...previous })).toMatchObject({ ft: null, fd: null });
+ }
+ const unchanged = { ...previous };
+ expect(parseInput(previous.f!, unchanged)).toBeNull();
+ expect(unchanged).toMatchObject({ f: previous.f, ft: previous.ft, fd });
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+});
describe('cell editor commit comparison', () => {
const unchanged: Array<{ name: string; previous: ICellData; incoming: ICellData }> = [
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index 6f1e862a99..14c89da0ef 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -1041,6 +1041,7 @@ export function getCellDataByInput(
return null;
}
const { body } = snapshot;
+ const previousFormula = cellData.f;
cellData.t = undefined;
const data = body.dataStream;
@@ -1126,6 +1127,12 @@ export function getCellDataByInput(
}
}
+ // Editor input starts from a copy of the old cell, including imported metadata.
+ if (cellData.f !== previousFormula && (cellData.ft !== undefined || cellData.fd !== undefined)) {
+ cellData.ft = null;
+ cellData.fd = null;
+ }
+
return cellData;
}
diff --git a/packages/sheets-ui/src/menu/sheet.menu.ts b/packages/sheets-ui/src/menu/sheet.menu.ts
index 5587cde003..bb71fd2733 100644
--- a/packages/sheets-ui/src/menu/sheet.menu.ts
+++ b/packages/sheets-ui/src/menu/sheet.menu.ts
@@ -156,7 +156,7 @@ export function UnHideSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
const commandService = accessor.get(ICommandService);
const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
- const hiddenList = workbook.getHiddenWorksheets().map((s) => ({
+ const hiddenList = workbook.getHiddenWorksheets(false).map((s) => ({
label: workbook.getSheetBySheetId(s)?.getName() || '',
value: s,
}));
@@ -166,7 +166,7 @@ export function UnHideSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
if (c.id !== SetWorksheetHideCommand.id && c.id !== SetWorksheetShowCommand.id) {
return;
}
- const newList = workbook.getHiddenWorksheets();
+ const newList = workbook.getHiddenWorksheets(false);
const isEmpty = newList.length === 0;
subscriber.next(isEmpty);
});
@@ -189,7 +189,7 @@ export function UnHideSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
if (c.id !== SetWorksheetHideCommand.id && c.id !== SetWorksheetShowCommand.id) {
return;
}
- const newList = workbook.getHiddenWorksheets().map((s) => ({
+ const newList = workbook.getHiddenWorksheets(false).map((s) => ({
label: workbook.getSheetBySheetId(s)?.getName() || '',
value: s,
}));
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
index 4c5e715477..e017522473 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
@@ -17,7 +17,9 @@
import type { ICellData, Injector, IRange, IStyleData, Nullable, Univer, Workbook } from '@univerjs/core';
import type { IClipboardItem } from './mock-clipboard';
import {
+ BooleanNumber,
CustomCommandExecutionError,
+ FormulaType,
ICommandService,
IPermissionService,
IUndoRedoService,
@@ -47,7 +49,9 @@ import {
WorkbookEditablePermission,
} from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { SheetPermissionInterceptorClipboardController } from '../../../controllers/permission/sheet-permission-interceptor-clipboard.controller';
+import {
+ SheetPermissionInterceptorClipboardController,
+} from '../../../controllers/permission/sheet-permission-interceptor-clipboard.controller';
import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../clipboard.service';
import { COPY_TYPE } from '../type';
import { clipboardTestBed } from './clipboard-test-bed';
@@ -175,6 +179,36 @@ describe('Test clipboard', () => {
univer?.dispose();
});
+ it('clears formula metadata on plain-text paste and restores it on undo', async () => {
+ const previous = { f: '=A1', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE };
+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 0: { 0: previous } },
+ });
+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ primary: null,
+ style: null,
+ }]);
+ expect(await sheetClipboardService.paste({
+ presentationStyle: 'unspecified',
+ types: ['text/plain'],
+ getType: async () => new Blob(['=SUM(B1:B2)'], { type: 'text/plain' }),
+ })).toBe(true);
+ const assertReplaced = () => {
+ const cell = getValues(0, 0, 0, 0)?.[0][0];
+ expect(cell?.f).toBe('=SUM(B1:B2)');
+ expect(cell?.ft).toBeUndefined();
+ expect(cell?.fd).toBeUndefined();
+ };
+ assertReplaced();
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getValues(0, 0, 0, 0)?.[0][0]).toMatchObject(previous);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ assertReplaced();
+ });
+
it('keeps the original selection while clipboard data is read asynchronously', async () => {
const clipboardService = get(ISheetClipboardService);
const selections = get(SheetsSelectionsService);
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts
index 23bd07193e..daa2d19678 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts
@@ -30,6 +30,8 @@ describe('cloneCellDataWithSpanInfo', () => {
v: '1',
t: 1,
f: '=A1',
+ ft: 2,
+ fd: 0,
ref: 'A1',
xf: '=SUM()',
si: 'sid',
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 90182a7c34..294d916601 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -15,6 +15,7 @@
*/
import type {
+ ICellData,
ICellDataWithSpanAndDisplay,
IDisposable,
IMutationInfo,
@@ -162,6 +163,8 @@ interface IFormulaClipboardPayload {
row: number;
column: number;
f: string;
+ ft?: ICellData['ft'];
+ fd?: ICellData['fd'];
}>;
}
@@ -676,6 +679,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
row,
column,
f: formula,
+ ft: copyContent.matrixFragment.getValue(row, column)?.ft,
+ fd: copyContent.matrixFragment.getValue(row, column)?.fd,
});
}
}
@@ -845,6 +850,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
...getEmptyCell(),
...cellMatrix.getValue(formula.row, formula.column),
f: formula.f,
+ ft: formula.ft,
+ fd: formula.fd,
});
}
});
diff --git a/packages/sheets-ui/src/services/clipboard/clone.ts b/packages/sheets-ui/src/services/clipboard/clone.ts
index 5f309de0f6..586b7caa9b 100644
--- a/packages/sheets-ui/src/services/clipboard/clone.ts
+++ b/packages/sheets-ui/src/services/clipboard/clone.ts
@@ -16,7 +16,7 @@
import type { Nullable } from '@univerjs/core';
import type { ICellDataWithSpanInfo } from './type';
-import { cloneValue } from '@univerjs/core';
+import { cloneCellData } from '@univerjs/core';
/**
* Fast clone for ICellDataWithSpanInfo. Optimized for the known structure.
@@ -29,56 +29,7 @@ export function cloneCellDataWithSpanInfo(cell: Nullable<ICellDataWithSpanInfo>)
return cell;
}
- const result: ICellDataWithSpanInfo = {};
-
- // p - IDocumentData (complex object, needs deep clone)
- if (cell.p !== undefined) {
- result.p = cell.p === null ? null : cloneValue(cell.p);
- }
-
- // s - style id (string) or IStyleData (object)
- if (cell.s !== undefined) {
- if (cell.s === null || typeof cell.s === 'string') {
- result.s = cell.s;
- } else {
- result.s = cloneValue(cell.s);
- }
- }
-
- // v - primitive value (string | number | boolean)
- if (cell.v !== undefined) {
- result.v = cell.v;
- }
-
- // t - CellValueType (number enum)
- if (cell.t !== undefined) {
- result.t = cell.t;
- }
-
- // f - formula string
- if (cell.f !== undefined) {
- result.f = cell.f;
- }
-
- // ref - formula array reference
- if (cell.ref !== undefined) {
- result.ref = cell.ref;
- }
-
- // xf - Excel formula prefix
- if (cell.xf !== undefined) {
- result.xf = cell.xf;
- }
-
- // si - formula id
- if (cell.si !== undefined) {
- result.si = cell.si;
- }
-
- // custom - user stored custom fields
- if (cell.custom !== undefined) {
- result.custom = cell.custom === null ? null : cloneValue(cell.custom);
- }
+ const result: ICellDataWithSpanInfo = cloneCellData(cell)!;
// rowSpan - span properties (primitives)
if (cell.rowSpan !== undefined) {
diff --git a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
index a002adb501..758a529d50 100644
--- a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
@@ -343,7 +343,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
dark:!univer-bg-gray-800
"
>
- {workbook.getHiddenWorksheets().map((sheetId) => (
+ {workbook.getHiddenWorksheets(false).map((sheetId) => (
<button
key={sheetId}
type="button"
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
index d22c452093..9b2f1d06a1 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
@@ -21,7 +21,7 @@ import type {
ISetWorksheetShowCommandParams,
} from '@univerjs/sheets';
import type { ReactNode } from 'react';
-import { BooleanNumber, DisposableCollection, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, DisposableCollection, ICommandService, IUniverInstanceService, UniverInstanceType, WorksheetHiddenState } from '@univerjs/core';
import { clsx, DropdownMenu } from '@univerjs/design';
import { CheckMarkIcon, ConvertIcon, EyelashIcon } from '@univerjs/icons';
import {
@@ -82,15 +82,15 @@ export function SheetBarMenu() {
const sheets = workbook.getSheets();
const activeSheet = workbook.getActiveSheet();
- const worksheetMenuItems = sheets.map((sheet, index) => {
- return {
+ const worksheetMenuItems = sheets
+ .filter((sheet) => sheet.getHiddenState() !== WorksheetHiddenState.VERY_HIDDEN)
+ .map((sheet, index) => ({
label: sheet.getName(),
index: `${index}`,
sheetId: sheet.getSheetId(),
hidden: sheet.isSheetHidden() === BooleanNumber.TRUE,
selected: activeSheet === sheet,
- };
- });
+ }));
setMenu(worksheetMenuItems);
}, [workbook, worksheetProtectionRuleModel]);
diff --git a/packages/sheets/src/basics/__tests__/utils.spec.ts b/packages/sheets/src/basics/__tests__/utils.spec.ts
index caa43dccf0..9ca40c18f0 100644
--- a/packages/sheets/src/basics/__tests__/utils.spec.ts
+++ b/packages/sheets/src/basics/__tests__/utils.spec.ts
@@ -19,6 +19,7 @@ import { cellToRange, IUniverInstanceService } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import {
createUniqueKey,
+ deserializeListOptions,
discreteRangeToRange,
findFirstNonEmptyCell,
generateNullCell,
@@ -38,6 +39,11 @@ function createAccessor(getter: (token: unknown) => unknown): IAccessor {
}
describe('Test utils', () => {
+ it('trims legacy comma-delimited list options like Excel', () => {
+ expect(deserializeListOptions('Asc, Desc , Pending')).toEqual(['Asc', 'Desc', 'Pending']);
+ expect(deserializeListOptions('[" keep ","spaces"]')).toEqual([' keep ', 'spaces']);
+ });
+
it('Test generateNullCell', () => {
const range: IRange[] = [cellToRange(0, 0), cellToRange(1, 1)];
const result = generateNullCell(range);
diff --git a/packages/sheets/src/basics/cell-value.ts b/packages/sheets/src/basics/cell-value.ts
index f8436d1ff5..71706810f2 100644
--- a/packages/sheets/src/basics/cell-value.ts
+++ b/packages/sheets/src/basics/cell-value.ts
@@ -98,6 +98,13 @@ export function setNull(value: Nullable<ICellData>) {
value.f = null;
}
+ if (value.ft === undefined) {
+ value.ft = null;
+ }
+ if (value.fd === undefined) {
+ value.fd = null;
+ }
+
if (value.si === undefined) {
value.si = null;
}
diff --git a/packages/sheets/src/basics/utils.ts b/packages/sheets/src/basics/utils.ts
index d9b8971255..23d269abb8 100644
--- a/packages/sheets/src/basics/utils.ts
+++ b/packages/sheets/src/basics/utils.ts
@@ -255,5 +255,5 @@ export function deserializeListOptions(optionsStr: string) {
// Fallback for data saved by older versions.
}
- return optionsStr.split(',').filter(Boolean);
+ return optionsStr.split(',').map((option) => option.trim()).filter(Boolean);
}
diff --git a/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
index b5b96c464d..d07bef2e3d 100644
--- a/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
@@ -17,7 +17,15 @@
import type { IAccessor, IRange } from '@univerjs/core';
import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
import type { IWorksheetProtectionRule } from '../../../services/permission/type';
-import { BooleanNumber, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import {
+ BooleanNumber,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ Styles,
+ Worksheet,
+ WorksheetHiddenState,
+} from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
import { describe, expect, it } from 'vitest';
import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
@@ -101,17 +109,13 @@ function createWorksheetRule(permissionId = 'permission-sheet-1'): IWorksheetPro
}
function createWorkbookTarget() {
- const config = { hidden: BooleanNumber.TRUE, rightToLeft: BooleanNumber.FALSE };
- const worksheet = {
+ const worksheet = new Worksheet('unit-1', {
+ id: 'sheet-1',
rowCount: 100,
columnCount: 20,
- config,
- getSheetId: () => 'sheet-1',
- getConfig: () => config,
- isSheetHidden: () => config.hidden,
- getRowCount() { return this.rowCount; },
- getColumnCount() { return this.columnCount; },
- };
+ hidden: WorksheetHiddenState.HIDDEN,
+ rightToLeft: BooleanNumber.FALSE,
+ }, new Styles());
const workbook = {
getUnitId: () => 'unit-1',
getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
@@ -515,7 +519,7 @@ describe('worksheet row, column, rtl and show commands', () => {
redoMutations: [{ id: SetWorksheetHideMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', hidden: BooleanNumber.FALSE } }],
});
- worksheet.config.hidden = BooleanNumber.FALSE;
+ worksheet.getConfig().hidden = WorksheetHiddenState.VISIBLE;
expect(SetWorksheetShowCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
index d066854faa..a1664d2107 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
@@ -14,12 +14,22 @@
* limitations under the License.
*/
-import type { ICellData, IDocumentData, Injector, IStyleData, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';
+import type {
+ ICellData,
+ IDocumentData,
+ Injector,
+ IStyleData,
+ IWorkbookData,
+ Nullable,
+ Univer,
+ Workbook,
+} from '@univerjs/core';
import type { ISetRangeValuesCommandParams } from '../set-range-values.command';
import {
BooleanNumber,
CellValueType,
DEFAULT_TEXT_FORMAT_EXCEL,
+ FormulaType,
ICommandService,
IUniverInstanceService,
LocaleType,
@@ -280,6 +290,36 @@ describe('Test set range values commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
+ it('preserves array metadata on value updates and restores it after formula replacement undo', async () => {
+ const array = { f: '=SUM(B1:B3)', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE };
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, { value: array })).toBeTruthy();
+ expect(getValue()).toMatchObject(array);
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, { value: { v: 6 } })).toBeTruthy();
+ expect(getValue()).toMatchObject(array);
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, { value: { f: '=1+1' } })).toBeTruthy();
+ expect(getValue()?.ft).toBeUndefined();
+ expect(getValue()?.fd).toBeUndefined();
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toMatchObject(array);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()?.ft).toBeUndefined();
+ expect(getValue()?.fd).toBeUndefined();
+ });
+
+ it.each([null, ''])('clears copied formula metadata when f is %s and restores it on undo', async (f) => {
+ const array = { f: '=SUM(B1:B3)', ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE };
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, { value: array })).toBeTruthy();
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, { value: { ...array, f, v: 7 } })).toBeTruthy();
+ expect(getValue()?.ft).toBeUndefined();
+ expect(getValue()?.fd).toBeUndefined();
+ expect(getValue()?.v).toBe(7);
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toMatchObject(array);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()?.ft).toBeUndefined();
+ expect(getValue()?.fd).toBeUndefined();
+ });
+
it('keeps complex cell data independent from command parameters across undo and redo', async () => {
const richText: IDocumentData = {
id: 'rich-text',
diff --git a/packages/sheets/src/commands/commands/__tests__/set-worksheet-hide.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-worksheet-hide.command.spec.ts
index 93458416bf..bba94a82a1 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-worksheet-hide.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-worksheet-hide.command.spec.ts
@@ -15,7 +15,7 @@
*/
import type { Injector, Univer, Workbook } from '@univerjs/core';
-import { BooleanNumber, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType, WorksheetHiddenState } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { InsertSheetMutation } from '../../mutations/insert-sheet.mutation';
import { SetWorksheetHideMutation } from '../../mutations/set-worksheet-hide.mutation';
@@ -79,6 +79,19 @@ describe('Test set worksheet hide commands', () => {
// redo
expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
expect(targetActiveSheet?.getConfig().hidden).toBe(BooleanNumber.TRUE);
+
+ expect(await commandService.executeCommand(SetWorksheetHideCommand.id, {
+ subUnitId: targetSheetId,
+ hidden: WorksheetHiddenState.VERY_HIDDEN,
+ })).toBeTruthy();
+ expect(targetActiveSheet?.getHiddenState()).toBe(WorksheetHiddenState.VERY_HIDDEN);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(targetActiveSheet?.getHiddenState()).toBe(WorksheetHiddenState.HIDDEN);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(targetActiveSheet?.getConfig().hidden).toBe(2);
+ expect(targetActiveSheet?.isSheetHidden()).toBe(BooleanNumber.TRUE);
+ expect(workbook.getHiddenWorksheets(false)).not.toContain(targetSheetId);
});
});
});
diff --git a/packages/sheets/src/commands/commands/set-range-values.command.ts b/packages/sheets/src/commands/commands/set-range-values.command.ts
index 22f73ab1ee..13cd389db2 100644
--- a/packages/sheets/src/commands/commands/set-range-values.command.ts
+++ b/packages/sheets/src/commands/commands/set-range-values.command.ts
@@ -103,6 +103,13 @@ export const SetRangeValuesCommand: ICommand = {
subUnitId,
cellValue: Tools.deepClone(realCellValue ?? cellValue.getMatrix()),
};
+ // User formula replacement starts fresh; internal reference mutations retain their type.
+ new ObjectMatrix(setRangeValuesMutationRedoParams.cellValue).forValue((row, col, cell) => {
+ if (cell?.f !== undefined && cell.f !== worksheet.getCell(row, col)?.f) {
+ cell.ft ??= null;
+ cell.fd ??= null;
+ }
+ });
const setRangeValuesMutationUndoParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationRedoParams);
const cellHeights = mapObjectMatrix(setRangeValuesMutationRedoParams.cellValue, (row, col) => worksheet.getCellHeight(row, col) || undefined);
diff --git a/packages/sheets/src/commands/commands/set-worksheet-hide.command.ts b/packages/sheets/src/commands/commands/set-worksheet-hide.command.ts
index 331881f139..f1b6b22578 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-hide.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-hide.command.ts
@@ -25,12 +25,16 @@ import {
IUndoRedoService,
IUniverInstanceService,
LocaleService,
+ WorksheetHiddenState,
} from '@univerjs/core';
import { SetWorksheetHideMutation, SetWorksheetHideMutationFactory } from '../mutations/set-worksheet-hide.mutation';
import { getSheetCommandTarget } from './utils/target-util';
export interface ISetWorksheetHiddenCommandParams {
+ unitId?: string;
subUnitId?: string;
+ /** Defaults to ordinary hiding; VERY_HIDDEN is available to API callers. */
+ hidden?: WorksheetHiddenState;
}
export const SetWorksheetHideCommand: ICommand = {
@@ -44,23 +48,34 @@ export const SetWorksheetHideCommand: ICommand = {
const localeService = accessor.get(LocaleService);
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { workbook, worksheet, unitId, subUnitId } = target;
- const hidden = worksheet.getConfig().hidden;
- if (hidden === BooleanNumber.TRUE) return false;
+ const hidden = params?.hidden ?? WorksheetHiddenState.HIDDEN;
+ const currentHiddenState = worksheet.getHiddenState();
+ if (hidden !== WorksheetHiddenState.HIDDEN && hidden !== WorksheetHiddenState.VERY_HIDDEN) {
+ return false;
+ }
+ if (currentHiddenState === hidden) {
+ return false;
+ }
+ if (params?.hidden === undefined && currentHiddenState !== WorksheetHiddenState.VISIBLE) {
+ return false;
+ }
const redoMutationParams: ISetWorksheetHideMutationParams = {
unitId,
subUnitId,
- hidden: BooleanNumber.TRUE,
+ hidden,
};
const undoMutationParams = SetWorksheetHideMutationFactory(accessor, redoMutationParams);
const worksheets = workbook.getSheets();
const visibleWorksheets = worksheets.filter((sheet) => sheet.getConfig().hidden === BooleanNumber.FALSE);
- if (visibleWorksheets.length === 1) {
+ if (currentHiddenState === WorksheetHiddenState.VISIBLE && visibleWorksheets.length === 1) {
errorService.emit(localeService.t<LocaleKey>('sheets.info.hideSheet'));
return false;
}
diff --git a/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
index 24736c939b..b0751d56c9 100644
--- a/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
+++ b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IWorkbookData } from '@univerjs/core';
-import { BooleanNumber, LocaleType } from '@univerjs/core';
+import { BooleanNumber, LocaleType, WorksheetHiddenState } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
SetGridlinesColorMutation,
@@ -118,7 +118,7 @@ describe('worksheet meta mutations', () => {
hidden: BooleanNumber.FALSE,
})
).toEqual({
- hidden: BooleanNumber.TRUE,
+ hidden: WorksheetHiddenState.HIDDEN,
unitId: 'unit-1',
subUnitId: 'sheet-1',
});
@@ -131,6 +131,13 @@ describe('worksheet meta mutations', () => {
})
).toBe(true);
expect(worksheet.getConfig().hidden).toBe(BooleanNumber.FALSE);
+ expect(worksheet.getHiddenState()).toBe(WorksheetHiddenState.VISIBLE);
+ expect(SetWorksheetHideMutation.handler(testBed, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ hidden: 3,
+ } as never)).toBe(false);
+ expect(worksheet.getHiddenState()).toBe(WorksheetHiddenState.VISIBLE);
expect(SetWorksheetHideMutation.handler(testBed, { unitId: 'missing', subUnitId: 'sheet-1', hidden: BooleanNumber.FALSE })).toBe(false);
expect(SetWorksheetHideMutation.handler(testBed, { unitId: 'unit-1', subUnitId: 'missing', hidden: BooleanNumber.FALSE })).toBe(false);
expect(() => SetWorksheetHideMutationFactory(testBed, { unitId: 'missing', subUnitId: 'sheet-1', hidden: BooleanNumber.FALSE }))
diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
index 7497c2b0f4..b34dda0b50 100644
--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -25,7 +25,14 @@ import type {
Styles,
Workbook,
} from '@univerjs/core';
-import { CommandType, IUniverInstanceService, ObjectMatrix, Tools, UniverInstanceType } from '@univerjs/core';
+import {
+ CommandType,
+ isFormulaId,
+ IUniverInstanceService,
+ ObjectMatrix,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
import { handleStyle, transformStyle } from '../../basics/cell-style';
import { getCellType } from '../../basics/cell-type';
import { getCellValue, setNull } from '../../basics/cell-value';
@@ -142,7 +149,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
},
};
-const overwriteCellPropertiesSet = new Set(['f', 'p', 'si', 'custom', 'ref', 'xf']);
+const overwriteCellPropertiesSet = new Set(['f', 'p', 'si', 'custom', 'ref', 'xf', 'ft', 'fd']);
function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles, isOverrideStyle = false) {
const type = getCellType(styles, newValue, oldValue);
Object.keys(newValue).forEach((key) => {
@@ -163,6 +170,12 @@ function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles,
}
});
+ // Shared formula followers have no f, but still carry formula metadata.
+ if ((newValue.f === null || newValue.f === '') && !isFormulaId(newValue.si)) {
+ delete oldValue.ft;
+ delete oldValue.fd;
+ }
+
if (oldValue.v !== undefined) {
oldValue.t = type;
oldValue.v = getCellValue(type, oldValue);
diff --git a/packages/sheets/src/commands/mutations/set-worksheet-hide.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-hide.mutation.ts
index a7b97520bd..8b8a7804f8 100644
--- a/packages/sheets/src/commands/mutations/set-worksheet-hide.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-worksheet-hide.mutation.ts
@@ -15,11 +15,11 @@
*/
import type { BooleanNumber, IAccessor, IMutation, Workbook } from '@univerjs/core';
-import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType, WorksheetHiddenState } from '@univerjs/core';
import { getSheetMutationTarget } from '../commands/utils/target-util';
export interface ISetWorksheetHideMutationParams {
- hidden: BooleanNumber;
+ hidden: WorksheetHiddenState | BooleanNumber;
unitId: string;
subUnitId: string;
}
@@ -35,7 +35,7 @@ export const SetWorksheetHideMutationFactory = (
const { worksheet } = target;
return {
- hidden: worksheet.isSheetHidden(),
+ hidden: worksheet.getHiddenState(),
unitId: params.unitId,
subUnitId: worksheet.getSheetId(),
};
@@ -57,7 +57,12 @@ export const SetWorksheetHideMutation: IMutation<ISetWorksheetHideMutationParams
return false;
}
- worksheet.getConfig().hidden = params.hidden;
+ if (params.hidden !== WorksheetHiddenState.VISIBLE
+ && params.hidden !== WorksheetHiddenState.HIDDEN
+ && params.hidden !== WorksheetHiddenState.VERY_HIDDEN) {
+ return false;
+ }
+ worksheet.setHiddenState(params.hidden);
return true;
},
diff --git a/packages/sheets/src/controllers/__tests__/auto-fill.controller.spec.ts b/packages/sheets/src/controllers/__tests__/auto-fill.controller.spec.ts
index 90b29b8ae6..bbd67fbc71 100644
--- a/packages/sheets/src/controllers/__tests__/auto-fill.controller.spec.ts
+++ b/packages/sheets/src/controllers/__tests__/auto-fill.controller.spec.ts
@@ -16,22 +16,31 @@
import type { ICellData, IStyleData, IWorkbookData, Univer, Workbook } from '@univerjs/core';
import {
+ BooleanNumber,
BorderStyleTypes,
+ FormulaType,
ICommandService,
IUniverInstanceService,
LocaleType,
RANGE_TYPE,
+ RedoCommand,
Tools,
+ UndoCommand,
UniverInstanceType,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { AutoFillCommand, SheetCopyDownCommand, SheetCopyRightCommand } from '../../commands/commands/auto-fill.command';
+import {
+ AutoFillCommand,
+ SheetCopyDownCommand,
+ SheetCopyRightCommand,
+} from '../../commands/commands/auto-fill.command';
import { AddWorksheetMergeMutation } from '../../commands/mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation } from '../../commands/mutations/remove-worksheet-merge.mutation';
import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';
import { SetSelectionsOperation } from '../../commands/operations/selection.operation';
import { createTestBase } from '../../services/__tests__/util';
import { AutoFillService, IAutoFillService } from '../../services/auto-fill/auto-fill.service';
+import { AUTO_FILL_APPLY_TYPE } from '../../services/auto-fill/type';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { AutoFillController } from '../auto-fill.controller';
@@ -149,6 +158,31 @@ describe('AutoFillController copy-fill shortcuts', () => {
expect(getCellStyle(1, 0)).toEqual(SOURCE_STYLE);
});
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])(
+ 'preserves target array metadata when filling only formatting (%s)',
+ async (fd) => {
+ const formula = { f: '=A1', ft: FormulaType.ARRAY, fd, v: 123 };
+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 1: { 0: formula } },
+ });
+ expect(await commandService.executeCommand(AutoFillCommand.id, {
+ sourceRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ targetRange: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },
+ applyType: AUTO_FILL_APPLY_TYPE.ONLY_FORMAT,
+ })).toBe(true);
+ expect(getCell(1, 0)).toMatchObject(formula);
+ expect(getCellStyle(1, 0)).toEqual(SOURCE_STYLE);
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getCell(1, 0)).toMatchObject(formula);
+ expect(getCellStyle(1, 0)).toEqual(TARGET_STYLE);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getCell(1, 0)).toMatchObject(formula);
+ expect(getCellStyle(1, 0)).toEqual(SOURCE_STYLE);
+ }
+ );
+
it('copies values and styles right with the copy-right shortcut command', async () => {
selectRange(2, 4);
diff --git a/packages/sheets/src/controllers/__tests__/calculate-result-apply.controller.spec.ts b/packages/sheets/src/controllers/__tests__/calculate-result-apply.controller.spec.ts
index 305c954ae4..292e2a7dad 100644
--- a/packages/sheets/src/controllers/__tests__/calculate-result-apply.controller.spec.ts
+++ b/packages/sheets/src/controllers/__tests__/calculate-result-apply.controller.spec.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { ICommandService } from '@univerjs/core';
-import { SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { BooleanNumber, CellValueType, FormulaType, ICommandService } from '@univerjs/core';
+import { ErrorType, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
import { describe, expect, it } from 'vitest';
import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';
import { CalculateResultApplyController } from '../calculate-result-apply.controller';
@@ -44,4 +44,93 @@ describe('CalculateResultApplyController', () => {
expect(testBed.sheet.getSheetBySheetId(testBed.sheetId)?.getCellMatrix().getValue(0, 0)?.v).toBe(2760);
testBed.univer.dispose();
});
+
+ it.each([ErrorType.REF, ErrorType.NAME, ErrorType.DIV_BY_ZERO])('applies calculated %s errors to fixed and dynamic arrays', async (error) => {
+ const testBed = createFunctionTestBed();
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
+ testBed.get(CalculateResultApplyController);
+ const sheet = testBed.sheet.getSheetBySheetId(testBed.sheetId)!;
+ sheet.getCellMatrix().setValue(0, 0, {
+ f: '=VSTACK("Project")',
+ ref: 'A1:A2',
+ v: 'Project',
+ t: CellValueType.STRING,
+ ft: FormulaType.ARRAY,
+ fd: BooleanNumber.FALSE,
+ });
+ sheet.getCellMatrix().setValue(0, 1, {
+ ft: FormulaType.ARRAY,
+ fd: BooleanNumber.TRUE,
+ f: '=VSTACK("Project")',
+ v: 'Project',
+ t: CellValueType.STRING,
+ });
+
+ sheet.getCellMatrix().setValue(1, 0, { v: 100, ref: 'A1:A2' });
+
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {
+ [testBed.unitId]: {
+ [testBed.sheetId]: {
+ 0: {
+ 0: { v: error, t: CellValueType.STRING },
+ 1: { v: error, t: CellValueType.STRING },
+ },
+ 1: { 0: { v: error, t: CellValueType.STRING } },
+ },
+ },
+ },
+ unitOtherData: {},
+ });
+
+ expect(sheet.getCellMatrix().getValue(0, 0)?.v).toBe(error);
+ expect(sheet.getCellMatrix().getValue(0, 1)?.v).toBe(error);
+ expect(sheet.getCellMatrix().getValue(1, 0)?.v).toBe(error);
+ expect(sheet.getCellMatrix().getValue(0, 0)).toMatchObject({ ft: FormulaType.ARRAY, fd: BooleanNumber.FALSE });
+ testBed.univer.dispose();
+ });
+
+ it('applies explicit clearing results to array anchors and followers', async () => {
+ const testBed = createFunctionTestBed();
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
+ testBed.get(CalculateResultApplyController);
+ const sheet = testBed.sheet.getSheetBySheetId(testBed.sheetId)!;
+ sheet.getCellMatrix().setValue(0, 0, {
+ f: '=A2:B2',
+ ref: 'A1:B1',
+ ft: FormulaType.ARRAY,
+ fd: BooleanNumber.FALSE,
+ });
+ sheet.getCellMatrix().setValue(0, 1, {
+ ref: 'A1:B1',
+ s: { bl: 1 },
+ });
+ sheet.getCellMatrix().setValue(0, 2, {
+ f: '=C2',
+ });
+
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {
+ [testBed.unitId]: {
+ [testBed.sheetId]: {
+ 0: {
+ 0: null,
+ 1: null,
+ 2: null,
+ },
+ },
+ },
+ },
+ unitOtherData: {},
+ });
+
+ expect(sheet.getCellMatrix().getValue(0, 0)).toBeUndefined();
+ expect(sheet.getCellMatrix().getValue(0, 1)).toBeUndefined();
+ expect(sheet.getCellMatrix().getValue(0, 2)).toBeUndefined();
+ testBed.univer.dispose();
+ });
});
diff --git a/packages/sheets/src/controllers/auto-fill.controller.ts b/packages/sheets/src/controllers/auto-fill.controller.ts
index 683c4d32fb..15f11128f5 100644
--- a/packages/sheets/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets/src/controllers/auto-fill.controller.ts
@@ -15,9 +15,18 @@
*/
import type { ICellData, IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';
-import type { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../basics';
+import type {
+ IAddWorksheetMergeMutationParams,
+ IRemoveWorksheetMergeMutationParams,
+} from '../basics/interfaces/mutation-interface';
import type { ISetRangeValuesMutationParams } from '../commands/mutations/set-range-values.mutation';
-import type { AUTO_FILL_APPLY_FUNCTIONS, IAutoFillCopyDataInType, IAutoFillCopyDataPiece, IAutoFillLocation, IAutoFillRuleConfirmedData } from '../services/auto-fill/type';
+import type {
+ AUTO_FILL_APPLY_FUNCTIONS,
+ IAutoFillCopyDataInType,
+ IAutoFillCopyDataPiece,
+ IAutoFillLocation,
+ IAutoFillRuleConfirmedData,
+} from '../services/auto-fill/type';
import {
Direction,
Disposable,
@@ -30,9 +39,18 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { discreteRangeToRange } from '../basics/utils';
-import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';
-import { RemoveMergeUndoMutationFactory, RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';
-import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../commands/mutations/set-range-values.mutation';
+import {
+ AddMergeUndoMutationFactory,
+ AddWorksheetMergeMutation,
+} from '../commands/mutations/add-worksheet-merge.mutation';
+import {
+ RemoveMergeUndoMutationFactory,
+ RemoveWorksheetMergeMutation,
+} from '../commands/mutations/remove-worksheet-merge.mutation';
+import {
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+} from '../commands/mutations/set-range-values.mutation';
import { IAutoFillService } from '../services/auto-fill/auto-fill.service';
import AutoFillRules from '../services/auto-fill/rules';
import AutoFillTools from '../services/auto-fill/tools';
@@ -473,6 +491,8 @@ export class AutoFillController extends Disposable {
if (cellData) {
const old = this._beforeApplyData[rowIndex][colIndex] || {};
cellData.f = old.f;
+ cellData.ft = old.ft;
+ cellData.fd = old.fd;
cellData.si = old.si;
cellData.t = old.t;
cellData.v = old.v;
diff --git a/packages/sheets/src/controllers/calculate-result-apply.controller.ts b/packages/sheets/src/controllers/calculate-result-apply.controller.ts
index 73f586bb0f..f8fc7ae464 100644
--- a/packages/sheets/src/controllers/calculate-result-apply.controller.ts
+++ b/packages/sheets/src/controllers/calculate-result-apply.controller.ts
@@ -106,7 +106,7 @@ export class CalculateResultApplyController extends Disposable {
* @param unitId
* @param sheetId
* @param cellData
- * @returns
+ * @returns Calculated cell data merged with number formats.
*/
private _getMergedCellData(unitId: string, sheetId: string, cellData: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {
const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
diff --git a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
index 6e17826608..c86e7ff8f3 100644
--- a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
@@ -25,6 +25,7 @@ import {
RANGE_TYPE,
TestConfirmService,
UniverInstanceType,
+ WorksheetHiddenState,
} from '@univerjs/core';
import {
AddWorksheetMergeCommand,
@@ -699,6 +700,23 @@ describe('Test FWorksheet', () => {
expect(activeSheet.getActiveCell()?.getA1Notation()).toBe('C3');
expect(() => activeSheet.hideSheet()).toThrow('Cannot hide the only visible sheet');
+ expect(() => activeSheet.setHiddenState(WorksheetHiddenState.VERY_HIDDEN)).toThrow('Cannot hide the only visible sheet');
+ expect(activeSheet.isSheetHidden()).toBe(false);
+
+ const workbookModel = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ workbookModel.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Second' });
+ expect(univerAPI.Enum.WorksheetHiddenState.VERY_HIDDEN).toBe(2);
+ activeSheet.setHiddenState(univerAPI.Enum.WorksheetHiddenState.VERY_HIDDEN);
+ expect(activeSheet.isSheetHidden()).toBe(true);
+ expect(activeSheet.getHiddenState()).toBe(WorksheetHiddenState.VERY_HIDDEN);
+ expect(workbookModel.getSheetBySheetId(activeSheet.getSheetId())!.getSnapshot()).toMatchObject({ hidden: 2 });
+ activeSheet.hideSheet();
+ expect(activeSheet.getHiddenState()).toBe(WorksheetHiddenState.VERY_HIDDEN);
+ activeSheet.showSheet();
+ expect(activeSheet.getHiddenState()).toBe(WorksheetHiddenState.VISIBLE);
+ activeSheet.setHiddenState(WorksheetHiddenState.HIDDEN);
+ expect(activeSheet.getHiddenState()).toBe(WorksheetHiddenState.HIDDEN);
+ activeSheet.setHiddenState(WorksheetHiddenState.VISIBLE);
expect(activeSheet.isSheetHidden()).toBe(false);
activeSheet.setName('Renamed');
diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.ts
index 3d12f4f5ce..b5e7f92987 100644
--- a/packages/sheets/src/facade/f-worksheet.ts
+++ b/packages/sheets/src/facade/f-worksheet.ts
@@ -50,6 +50,7 @@ import {
Injector,
ObjectMatrix,
RANGE_TYPE,
+ WorksheetHiddenState,
WrapStrategy,
} from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
@@ -2224,20 +2225,8 @@ export class FWorksheet extends FBaseInitialable {
* ```
*/
hideSheet(): FWorksheet {
- const commandService = this._injector.get(ICommandService);
- const workbook = this._workbook;
- const sheets = workbook.getSheets();
- const visibleSheets = sheets.filter((sheet) => sheet.isSheetHidden() !== BooleanNumber.TRUE);
- if (visibleSheets.length <= 1) {
- throw new Error('Cannot hide the only visible sheet');
- }
-
- commandService.syncExecuteCommand(SetWorksheetHideCommand.id, {
- unitId: this._workbook.getUnitId(),
- subUnitId: this._worksheet.getSheetId(),
- });
-
- return this;
+ // Preserve a very-hidden state when hideSheet() is called without an explicit state.
+ return this.isSheetHidden() ? this : this.setHiddenState(WorksheetHiddenState.HIDDEN);
}
/**
@@ -2261,7 +2250,7 @@ export class FWorksheet extends FBaseInitialable {
}
/**
- * Returns true if the sheet is currently hidden.
+ * Returns true for both HIDDEN and VERY_HIDDEN sheets.
* @returns {boolean} True if the sheet is hidden; otherwise, false.
* @example
* ```ts
@@ -2275,6 +2264,45 @@ export class FWorksheet extends FBaseInitialable {
return Boolean(this._worksheet.isSheetHidden() === BooleanNumber.TRUE);
}
+ /**
+ * Returns 0 (visible), 1 (hidden), or 2 (very hidden).
+ * @example fWorksheet.getHiddenState() === univerAPI.Enum.WorksheetHiddenState.VERY_HIDDEN
+ */
+ getHiddenState(): WorksheetHiddenState {
+ return this._worksheet.getHiddenState();
+ }
+
+ /**
+ * Changes the persisted hiding state through an undoable command.
+ * VERY_HIDDEN removes the sheet from Unhide UI; showSheet() can reveal it through the API.
+ * The last visible sheet cannot be hidden. Existing isSheetHidden() stays a boolean predicate.
+ * @example fWorksheet.setHiddenState(univerAPI.Enum.WorksheetHiddenState.VERY_HIDDEN)
+ */
+ setHiddenState(hidden: WorksheetHiddenState): FWorksheet {
+ if (hidden === WorksheetHiddenState.VISIBLE) {
+ return this.showSheet();
+ }
+ if (hidden !== WorksheetHiddenState.HIDDEN && hidden !== WorksheetHiddenState.VERY_HIDDEN) {
+ throw new RangeError(`Unsupported worksheet hidden state: ${String(hidden)}`);
+ }
+ if (this._worksheet.getHiddenState() === hidden) {
+ return this;
+ }
+ if (this._worksheet.getHiddenState() === WorksheetHiddenState.VISIBLE) {
+ const visibleSheets = this._workbook.getSheets().filter((sheet) => !sheet.isSheetHidden());
+ if (visibleSheets.length <= 1) {
+ throw new Error('Cannot hide the only visible sheet');
+ }
+ }
+
+ this._injector.get(ICommandService).syncExecuteCommand(SetWorksheetHideCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ hidden,
+ });
+ return this;
+ }
+
/**
* Sets the sheet name.
* @param {string} name - The new name for the sheet.
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
index 9555c3b42e..9dfd741347 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
@@ -136,6 +136,7 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
const localeService = useDependency(LocaleService);
const regionService = useDependency(RegionService);
const userManagerService = useDependency(UserManagerService);
+ useObservable(userManagerService.userChange$);
const user = userManagerService.getUser(item.personId);
const currentUser = useObservable(userManagerService.currentUser$);
const isCommentBySelf = currentUser?.userID === item.personId;
@@ -195,11 +196,11 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
backgroundImage: `url(${user?.avatar || avatarFallback})`,
}}
/>
- {user
+ {user || item.authorName
? (
<div className="univer-mb-1 univer-flex univer-h-6 univer-items-center univer-justify-between">
<div className="univer-text-sm univer-font-medium univer-leading-5">
- {user?.name || ' '}
+ {user?.name || item.authorName || ' '}
</div>
<div>
{(isMock || resolved)
diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
index f92ecf7ad1..ce8eac5765 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
@@ -362,6 +362,7 @@ function createComment(overrides: Partial<IThreadComment>): IThreadComment {
ref: overrides.ref ?? 'A1',
dT: overrides.dT ?? '2026-06-17T00:00:00.000Z',
personId: overrides.personId ?? 'owner',
+ authorName: overrides.authorName,
text: overrides.text ?? transformTextNodes2Document([{ type: 'text', content: id }]),
unitId: overrides.unitId ?? UNIT_ID,
subUnitId: overrides.subUnitId ?? SHEET_ID,
@@ -682,6 +683,7 @@ describe('ThreadCommentTree', () => {
addRootComment(testBed.threadCommentModel, createComment({
id: 'removed-author-thread',
personId: 'removed-user',
+ authorName: 'Imported author',
text: transformTextNodes2Document([{ type: 'text', content: 'kept after user removal' }]),
}));
@@ -690,6 +692,13 @@ describe('ThreadCommentTree', () => {
container = rendered.container;
expect(container.textContent).toContain('kept after user removal');
+ expect(container.textContent).toContain('Imported author');
+ const users = testBed.injector.get(UserManagerService);
+ act(() => users.addUser({ userID: 'removed-user', name: 'Resolved author' }));
+ expect(container.textContent).toContain('Resolved author');
+ expect(container.textContent).not.toContain('Imported author');
+ act(() => users.delete('removed-user'));
+ expect(container.textContent).toContain('Imported author');
});
it('adds a reply through the tree editor and stores it under the root thread', async () => {
diff --git a/packages/thread-comment/src/common/tc-resource.ts b/packages/thread-comment/src/common/tc-resource.ts
index cb4e082cd7..3207b50ec9 100644
--- a/packages/thread-comment/src/common/tc-resource.ts
+++ b/packages/thread-comment/src/common/tc-resource.ts
@@ -35,7 +35,8 @@ function isSnapshotComment(value: unknown, allowChildren = true): value is IThre
&& comment.id.length > 0
&& typeof comment.threadId === 'string'
&& comment.threadId.length > 0
- && typeof comment.ref === 'string'
+ && (typeof comment.ref === 'string' || (!allowChildren && comment.ref === undefined))
+ && (comment.authorName === undefined || typeof comment.authorName === 'string')
&& (comment.text === undefined || isThreadCommentDocumentBody(comment.text))
&& (comment.attachments === undefined || isStringArray(comment.attachments))
&& (comment.mentions === undefined || isStringArray(comment.mentions))
diff --git a/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
index 6bc4f25d67..372d909f0f 100644
--- a/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
+++ b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
@@ -238,6 +238,33 @@ describe('ThreadCommentModel', () => {
});
});
+ it('preserves imported root and reply author names across refreshes only for the same author', async () => {
+ lifecycleService.stage = LifecycleStages.Rendered;
+ const root = { ...createComment({ id: 'imported-root' }), authorName: 'Ada' };
+ const reply = { ...createComment({ id: 'imported-reply', parentId: root.id }), authorName: 'Lin' };
+ threadCommentModel.addComment('unit-1', 'sheet-1', { ...root, children: [reply] });
+ let personId = root.personId;
+ dataSourceService.dataSource = {
+ addComment: async (comment) => comment,
+ updateComment: async () => true,
+ resolveComment: async () => true,
+ deleteComment: async () => true,
+ listComments: async () => [{ ...root, personId, authorName: undefined, children: [{ ...reply, personId, authorName: undefined }] }],
+ saveCommentToSnapshot: (comment) => comment,
+ };
+ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', [root.threadId]);
+ let thread = threadCommentModel.getThread('unit-1', 'sheet-1', root.threadId)!;
+ expect(thread.root.authorName).toBe('Ada');
+ expect(thread.children[0].authorName).toBe('Lin');
+ const snapshot = JSON.parse(JSON.stringify({ sheet: [{ ...thread.root, children: thread.children }] }));
+ expect(snapshot.sheet[0].children[0].authorName).toBe('Lin');
+ personId = 'another-user';
+ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', [root.threadId]);
+ thread = threadCommentModel.getThread('unit-1', 'sheet-1', root.threadId)!;
+ expect(thread.root.authorName).toBeUndefined();
+ expect(thread.children[0].authorName).toBeUndefined();
+ });
+
it('keeps the newest sync result when overlapping requests finish out of order', async () => {
lifecycleService.stage = LifecycleStages.Rendered;
const root = createComment({ id: 'racing-root', text: createBody('initial') });
diff --git a/packages/thread-comment/src/models/thread-comment.model.ts b/packages/thread-comment/src/models/thread-comment.model.ts
index 5ad0d06d70..4906b296e0 100644
--- a/packages/thread-comment/src/models/thread-comment.model.ts
+++ b/packages/thread-comment/src/models/thread-comment.model.ts
@@ -17,7 +17,14 @@
import type { Nullable } from '@univerjs/core';
import type { IUpdateCommentPayload, IUpdateCommentRefPayload } from '../commands/mutations/comment.mutation';
import type { IBaseComment, IThreadComment } from '../types/interfaces/i-thread-comment';
-import { Disposable, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, UniverInstanceType } from '@univerjs/core';
+import {
+ Disposable,
+ Inject,
+ IUniverInstanceService,
+ LifecycleService,
+ LifecycleStages,
+ UniverInstanceType,
+} from '@univerjs/core';
import { Subject } from 'rxjs';
import { IThreadCommentDataSourceService } from '../services/tc-datasource.service';
import { deserializeThreadCommentAnchor, ThreadCommentAnchorKind } from '../types/comment-anchor';
@@ -207,6 +214,7 @@ export class ThreadCommentModel extends Disposable {
});
const newComment = {
...rest,
+ authorName: rest.authorName ?? (rest.personId === currentComment.personId ? currentComment.authorName : undefined),
ref: currentComment.ref,
};
commentMap.set(comment.id, newComment);
@@ -224,6 +232,7 @@ export class ThreadCommentModel extends Disposable {
safeChildren.forEach((child) => {
commentMap.set(child.id, {
...child,
+ authorName: child.authorName ?? (child.personId === commentMap.get(child.id)?.personId ? commentMap.get(child.id)?.authorName : undefined),
parentId: comment.id,
ref: '',
});
diff --git a/packages/thread-comment/src/services/tc-datasource.service.ts b/packages/thread-comment/src/services/tc-datasource.service.ts
index 95411b425a..54f8285250 100644
--- a/packages/thread-comment/src/services/tc-datasource.service.ts
+++ b/packages/thread-comment/src/services/tc-datasource.service.ts
@@ -22,7 +22,8 @@ export type ThreadCommentJSON = {
id: string;
threadId: string;
ref: string;
-} & Partial<Omit<IThreadComment, 'id' | 'threadId' | 'ref'>>;
+ children?: Array<Omit<ThreadCommentJSON, 'ref'> & { ref?: string }>;
+} & Partial<Omit<IThreadComment, 'id' | 'threadId' | 'ref' | 'children'>>;
type Success = boolean;
diff --git a/packages/thread-comment/src/services/thread-comment-api.service.ts b/packages/thread-comment/src/services/thread-comment-api.service.ts
index fc35bebe23..e22e8b4dc7 100644
--- a/packages/thread-comment/src/services/thread-comment-api.service.ts
+++ b/packages/thread-comment/src/services/thread-comment-api.service.ts
@@ -46,6 +46,8 @@ export interface ICreateThreadCommentOptions {
threadId?: string;
/** Author user ID. Defaults to the current user managed by `UserManagerService`. */
personId?: string;
+ /** Display-only author name used when the user profile is unavailable. */
+ authorName?: string;
/** Creation time. Defaults to the current time. */
dateTime?: Date;
}
@@ -65,6 +67,8 @@ export interface IReplyThreadCommentOptions {
id?: string;
/** Author user ID. Defaults to the current user managed by `UserManagerService`. */
personId?: string;
+ /** Display-only author name used when the user profile is unavailable. */
+ authorName?: string;
/** Creation time. Defaults to the current time. */
dateTime?: Date;
}
@@ -213,6 +217,7 @@ export class ThreadCommentFacadeService {
text: normalizeThreadCommentContent(options.content),
attachments: options.attachments ?? [],
dT: getDT(options.dateTime),
+ authorName: options.authorName,
personId,
},
});
@@ -237,6 +242,7 @@ export class ThreadCommentFacadeService {
text: normalizeThreadCommentContent(options.content),
attachments: options.attachments ?? [],
dT: getDT(options.dateTime),
+ authorName: options.authorName,
personId: options.personId ?? this._userManagerService.getCurrentUser().userID,
},
});
diff --git a/packages/thread-comment/src/types/interfaces/i-thread-comment.ts b/packages/thread-comment/src/types/interfaces/i-thread-comment.ts
index 2315a3bd41..e10f1d5f95 100644
--- a/packages/thread-comment/src/types/interfaces/i-thread-comment.ts
+++ b/packages/thread-comment/src/types/interfaces/i-thread-comment.ts
@@ -28,6 +28,8 @@ export interface IBaseComment {
dT: string;
updateT?: string;
personId: string;
+ /** Display-only fallback when the author profile cannot be resolved. Never used for permissions. */
+ authorName?: string;
text: IDocumentBody;
attachments?: string[];
updated?: boolean;