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.

refactor(core): share record values and layout units (#7917)

白熱7f22875793f0
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 7e062505a8..298c2898e0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -167,6 +167,8 @@ export { RBush, RTree } from './shared/r-tree';
export type { BBox, IRTreeItem } from './shared/r-tree';
export { generateRandomId } from './shared/random-id';
export { getIntersectRange } from './shared/range';
+export { getRecordValueKey } from './shared/record-value';
+export type { RecordSelection, RecordValue } from './shared/record-value';
export {
afterTime,
bufferDebounceTime,
@@ -176,6 +178,7 @@ export {
} from './shared/rxjs';
export { awaitTime, delayAnimationFrame } from './shared/timer';
export { isNodeEnv } from './shared/tools';
+export { cssPxToEmu, EMU_PER_CSS_PX, emuToCssPx } from './shared/units';
export * from './sheets';
export type { IWorkbookCalculationSettings } from './sheets/calculation-settings';
export { MAX_ITERATION_COUNT, normalizeWorkbookCalculationSettings } from './sheets/calculation-settings';
@@ -190,8 +193,10 @@ export { DataValidationRenderMode } from './types/enum/data-validation-render-mo
export { DataValidationStatus } from './types/enum/data-validation-status';
export { DataValidationType } from './types/enum/data-validation-type';
export { FilterSelectionMode, RecordValueType } from './types/enum/record-filter';
+
export * from './types/interfaces';
export type { ICellCustomRender, ICellRenderContext } from './types/interfaces/i-cell-custom-render';
+
export type {
IDataValidationRule,
IDataValidationRuleBase,
@@ -199,6 +204,5 @@ export type {
IDataValidationRuleOptions,
ISheetDataValidationRule,
} from './types/interfaces/i-data-validation';
-
export { Univer } from './univer';
export type { IUniverConfig } from './univer';
diff --git a/packages/core/src/shared/__tests__/record-value.spec.ts b/packages/core/src/shared/__tests__/record-value.spec.ts
new file mode 100644
index 0000000000..dff3300b36
--- /dev/null
+++ b/packages/core/src/shared/__tests__/record-value.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 type { RecordValue } from '../record-value';
+import { RecordValueType } from '../../types/enum/record-filter';
+import { getRecordValueKey } from '../record-value';
+
+describe('record value identity', () => {
+ it('keeps typed identities distinct even when captions look the same', () => {
+ const members: RecordValue[] = [
+ { type: RecordValueType.Blank },
+ { type: RecordValueType.String, value: '' },
+ { type: RecordValueType.String, value: '(Blank)' },
+ { type: RecordValueType.String, value: '1' },
+ { type: RecordValueType.Number, value: 1 },
+ { type: RecordValueType.Date, value: 1 },
+ { type: RecordValueType.String, value: 'true' },
+ { type: RecordValueType.Boolean, value: true },
+ { type: RecordValueType.String, value: '#N/A' },
+ { type: RecordValueType.Error, value: '#N/A' },
+ ];
+
+ expect(new Set(members.map(getRecordValueKey)).size).toBe(members.length);
+ });
+
+ it('keeps wire keys stable across JSON round trips and normalizes negative zero', () => {
+ const value: RecordValue = { type: RecordValueType.String, value: 'north\u0000:string:南' };
+ expect(getRecordValueKey(value)).toBe(JSON.stringify(['string', value.value]));
+ expect(getRecordValueKey(JSON.parse(JSON.stringify(value)))).toBe(getRecordValueKey(value));
+ expect(getRecordValueKey({ type: RecordValueType.Number, value: -0 }))
+ .toBe(getRecordValueKey({ type: RecordValueType.Number, value: 0 }));
+ });
+
+ it('rejects malformed identities before they enter filter key sets', () => {
+ for (const value of [null, [], {}, { type: 'unknown' }, { type: 'blank', value: undefined }, { type: 'string', value: 1 }, { type: 'boolean', value: 1 }]) {
+ expect(() => getRecordValueKey(value as never)).toThrow(TypeError);
+ }
+ for (const type of [RecordValueType.Number, RecordValueType.Date] as const) {
+ for (const value of [Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY]) {
+ expect(() => getRecordValueKey({ type, value })).toThrow(RangeError);
+ }
+ }
+ });
+});
diff --git a/packages/core/src/shared/__tests__/units.spec.ts b/packages/core/src/shared/__tests__/units.spec.ts
new file mode 100644
index 0000000000..54ff120aa3
--- /dev/null
+++ b/packages/core/src/shared/__tests__/units.spec.ts
@@ -0,0 +1,32 @@
+/**
+ * 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 { cssPxToEmu, emuToCssPx } from '../units';
+
+describe('EMU and CSS pixel conversion', () => {
+ it('round trips a CSS inch through Office layout units', () => {
+ expect(cssPxToEmu(96)).toBe(914400);
+ expect(emuToCssPx(914400)).toBe(96);
+ });
+
+ it('quantizes fractional dimensions to the nearest integer EMU', () => {
+ expect(cssPxToEmu(0.1)).toBe(953);
+ for (const pixels of [-20.5, 0, 0.1, 28.33, 200000 / 9525]) {
+ expect(Math.abs(emuToCssPx(cssPxToEmu(pixels)) - pixels)).toBeLessThanOrEqual(0.5 / 9525 + Number.EPSILON * Math.abs(pixels));
+ }
+ });
+});
diff --git a/packages/core/src/shared/numfmt/__tests__/date-system.spec.ts b/packages/core/src/shared/numfmt/__tests__/date-system.spec.ts
deleted file mode 100644
index b815f038d7..0000000000
--- a/packages/core/src/shared/numfmt/__tests__/date-system.spec.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * 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 { DateSystem } from '../../../types/enum/date-system';
-import { excelDateSerial, excelDateTimePartsToSerial, excelDateTimeSerial, excelSerialToDate, excelSerialToDateTime, excelSerialToDateTimeParts } from '../serial-date';
-
-describe('Excel date systems', () => {
- it('preserves the Excel 1900 compatibility dates', () => {
- expect(excelSerialToDateTimeParts(0, { dateSystem: DateSystem.Date1900 })).toEqual({
- year: 1900,
- month: 1,
- day: 0,
- hours: 0,
- minutes: 0,
- seconds: 0,
- fractionalSecond: 0,
- });
- expect(excelSerialToDateTimeParts(60, { dateSystem: DateSystem.Date1900 })).toEqual({
- year: 1900,
- month: 2,
- day: 29,
- hours: 0,
- minutes: 0,
- seconds: 0,
- fractionalSecond: 0,
- });
- });
-
- it('uses 1904-01-01 as serial zero in the Excel 1904 system', () => {
- const parts = {
- year: 1904,
- month: 1,
- day: 1,
- hours: 0,
- minutes: 0,
- seconds: 0,
- fractionalSecond: 0,
- };
-
- expect(excelSerialToDateTimeParts(0, { dateSystem: DateSystem.Date1904 })).toEqual(parts);
- expect(excelDateTimePartsToSerial(parts, { dateSystem: DateSystem.Date1904 })).toBe(0);
- });
-
- it('preserves fractional seconds without using a native Date', () => {
- const parts = excelSerialToDateTimeParts(0.5242683912037037, { dateSystem: DateSystem.Date1900 });
-
- expect(parts).toMatchObject({
- year: 1900,
- month: 1,
- day: 0,
- hours: 12,
- minutes: 34,
- seconds: 56,
- });
- expect(parts?.fractionalSecond).toBeCloseTo(0.789, 9);
- });
-
- it('rejects invalid calendar inputs', () => {
- expect(excelSerialToDateTimeParts(-1, { dateSystem: DateSystem.Date1900 })).toBeNull();
- expect(excelSerialToDateTimeParts(Number.POSITIVE_INFINITY, { dateSystem: DateSystem.Date1900 })).toBeNull();
- expect(excelDateTimePartsToSerial({
- year: 1900,
- month: 2,
- day: 29,
- hours: 0,
- minutes: 0,
- seconds: 0,
- fractionalSecond: 0,
- }, { dateSystem: DateSystem.Date1904 })).toBeNull();
- });
-
- it('converts serials to UTC native Dates and normalizes pseudo-dates', () => {
- expect(excelSerialToDate(0, DateSystem.Date1900).getTime()).toBe(Date.UTC(1899, 11, 31));
- expect(excelSerialToDate(60, DateSystem.Date1900).getTime()).toBe(Date.UTC(1900, 1, 28));
- expect(excelSerialToDate(0, DateSystem.Date1904).getTime()).toBe(Date.UTC(1904, 0, 1));
- expect(excelSerialToDateTime(0.5, DateSystem.Date1904).getTime()).toBe(Date.UTC(1904, 0, 1, 12));
- expect(Number.isNaN(excelSerialToDate(-1, DateSystem.Date1900).getTime())).toBe(true);
- });
-
- it('converts UTC native Dates to serials for both Excel date systems', () => {
- expect(excelDateSerial(new Date(Date.UTC(1900, 1, 28)))).toBe(59);
- expect(excelDateSerial(new Date(Date.UTC(1900, 2, 1)))).toBe(61);
- expect(excelDateSerial(new Date(Date.UTC(1904, 0, 1)), DateSystem.Date1904)).toBe(0);
- expect(excelDateTimeSerial(new Date(Date.UTC(2024, 0, 2, 12)))).toBe(45293.5);
- expect(Number.isNaN(excelDateSerial(new Date(Number.NaN)))).toBe(true);
- });
-});
diff --git a/packages/core/src/shared/numfmt/__tests__/serial-date.spec.ts b/packages/core/src/shared/numfmt/__tests__/serial-date.spec.ts
index 34cb289dde..9252ecc241 100644
--- a/packages/core/src/shared/numfmt/__tests__/serial-date.spec.ts
+++ b/packages/core/src/shared/numfmt/__tests__/serial-date.spec.ts
@@ -19,7 +19,18 @@
// @vitest-environment node
-import { dateFromSerial, dateToSerial } from '../api';
+import { describe, expect, it } from 'vitest';
+import { DateSystem } from '../../../types/enum/date-system';
+import {
+ dateFromSerial,
+ dateToSerial,
+ excelDateSerial,
+ excelDateTimePartsToSerial,
+ excelDateTimeSerial,
+ excelSerialToDate,
+ excelSerialToDateTime,
+ excelSerialToDateTimeParts,
+} from '../serial-date';
import { getTimeZoneName, numfmtTest } from './test-utils';
/* globals process */
@@ -28,6 +39,23 @@ function round(n: number) {
return Math.round(n * 1e10) / 1e10;
}
+describe('Excel serial bounds', () => {
+ it.each([
+ [DateSystem.Date1900, 2_958_465],
+ [DateSystem.Date1904, 2_957_003],
+ ])('rejects overflowing serials and preserves the last day in %s', (dateSystem, maxSerial) => {
+ for (const serial of [maxSerial + 1, 1e12, Number.MAX_SAFE_INTEGER, Number.MAX_VALUE]) {
+ expect(excelSerialToDateTimeParts(serial, { dateSystem })).toBeNull();
+ }
+ expect(excelSerialToDateTimeParts(maxSerial + 0.5, { dateSystem })).toMatchObject({
+ year: 9999,
+ month: 12,
+ day: 31,
+ hours: 12,
+ });
+ });
+});
+
numfmtTest('dateToSerial (Date):', (t) => {
process.env.TZ = 'Asia/Calcutta';
t.equal(getTimeZoneName(), 'India Standard Time', 'Timezone is IST');
@@ -105,3 +133,85 @@ numfmtTest('dateFromSerial:', (t) => {
'dateFromSerial(42341)'
);
});
+
+describe('Excel date systems', () => {
+ it('preserves the Excel 1900 compatibility dates', () => {
+ expect(excelSerialToDateTimeParts(0, { dateSystem: DateSystem.Date1900 })).toEqual({
+ year: 1900,
+ month: 1,
+ day: 0,
+ hours: 0,
+ minutes: 0,
+ seconds: 0,
+ fractionalSecond: 0,
+ });
+ expect(excelSerialToDateTimeParts(60, { dateSystem: DateSystem.Date1900 })).toEqual({
+ year: 1900,
+ month: 2,
+ day: 29,
+ hours: 0,
+ minutes: 0,
+ seconds: 0,
+ fractionalSecond: 0,
+ });
+ });
+
+ it('uses 1904-01-01 as serial zero in the Excel 1904 system', () => {
+ const parts = {
+ year: 1904,
+ month: 1,
+ day: 1,
+ hours: 0,
+ minutes: 0,
+ seconds: 0,
+ fractionalSecond: 0,
+ };
+
+ expect(excelSerialToDateTimeParts(0, { dateSystem: DateSystem.Date1904 })).toEqual(parts);
+ expect(excelDateTimePartsToSerial(parts, { dateSystem: DateSystem.Date1904 })).toBe(0);
+ });
+
+ it('preserves fractional seconds without using a native Date', () => {
+ const parts = excelSerialToDateTimeParts(0.5242683912037037, { dateSystem: DateSystem.Date1900 });
+
+ expect(parts).toMatchObject({
+ year: 1900,
+ month: 1,
+ day: 0,
+ hours: 12,
+ minutes: 34,
+ seconds: 56,
+ });
+ expect(parts?.fractionalSecond).toBeCloseTo(0.789, 9);
+ });
+
+ it('rejects invalid calendar inputs', () => {
+ expect(excelSerialToDateTimeParts(-1, { dateSystem: DateSystem.Date1900 })).toBeNull();
+ expect(excelSerialToDateTimeParts(Number.POSITIVE_INFINITY, { dateSystem: DateSystem.Date1900 })).toBeNull();
+ expect(excelDateTimePartsToSerial({
+ year: 1900,
+ month: 2,
+ day: 29,
+ hours: 0,
+ minutes: 0,
+ seconds: 0,
+ fractionalSecond: 0,
+ }, { dateSystem: DateSystem.Date1904 })).toBeNull();
+ });
+
+ it('converts serials to UTC native Dates and normalizes pseudo-dates', () => {
+ expect(excelSerialToDate(0, DateSystem.Date1900).getTime()).toBe(Date.UTC(1899, 11, 31));
+ expect(excelSerialToDate(60, DateSystem.Date1900).getTime()).toBe(Date.UTC(1900, 1, 28));
+ expect(excelSerialToDate(0, DateSystem.Date1904).getTime()).toBe(Date.UTC(1904, 0, 1));
+ expect(excelSerialToDateTime(0.5, DateSystem.Date1904).getTime()).toBe(Date.UTC(1904, 0, 1, 12));
+ expect(Number.isNaN(excelSerialToDate(-1, DateSystem.Date1900).getTime())).toBe(true);
+ });
+
+ it('converts UTC native Dates to serials for both Excel date systems', () => {
+ expect(excelDateSerial(new Date(Date.UTC(1900, 1, 28)))).toBe(59);
+ expect(excelDateSerial(new Date(Date.UTC(1900, 2, 1)))).toBe(61);
+ expect(excelDateSerial(new Date(Date.UTC(1904, 0, 1)), DateSystem.Date1904)).toBe(0);
+ expect(excelDateTimeSerial(new Date(Date.UTC(2024, 0, 2, 12)))).toBe(45293.5);
+ expect(Number.isNaN(excelDateSerial(new Date(Number.NaN)))).toBe(true);
+ });
+});
diff --git a/packages/core/src/shared/numfmt/serial-date.ts b/packages/core/src/shared/numfmt/serial-date.ts
index 97ebd47fc1..0afec17c96 100644
--- a/packages/core/src/shared/numfmt/serial-date.ts
+++ b/packages/core/src/shared/numfmt/serial-date.ts
@@ -101,7 +101,7 @@ export function excelSerialToDateTimeParts(
serial: number,
options: IDateSystemOptions
): IExcelDateTimeParts | null {
- if (!Number.isFinite(serial) || serial < 0) {
+ if (!Number.isFinite(serial) || serial < 0 || serial >= getDateSystemMaxSerial(options.dateSystem) + 1) {
return null;
}
diff --git a/packages/core/src/shared/record-value.ts b/packages/core/src/shared/record-value.ts
new file mode 100644
index 0000000000..abdef12ea1
--- /dev/null
+++ b/packages/core/src/shared/record-value.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 type { FilterSelectionMode } from '../types/enum/record-filter';
+import { RecordValueType } from '../types/enum/record-filter';
+
+export type RecordValue =
+ | { type: RecordValueType.Blank }
+ | { type: RecordValueType.String | RecordValueType.Error; value: string }
+ | { type: RecordValueType.Number | RecordValueType.Date; value: number }
+ | { type: RecordValueType.Boolean; value: boolean };
+
+export type RecordSelection =
+ | { mode: FilterSelectionMode.All }
+ | { mode: FilterSelectionMode.Include | FilterSelectionMode.Exclude; values: RecordValue[] };
+
+export function getRecordValueKey(_value: RecordValue): string {
+ const value = _value as unknown;
+ if (!isRecord(value) || typeof value.type !== 'string') {
+ throw new TypeError('Invalid record value.');
+ }
+
+ switch (value.type) {
+ case RecordValueType.Blank:
+ if ('value' in value) {
+ throw new TypeError('Blank record values cannot have a value.');
+ }
+ return '["blank"]';
+ case RecordValueType.String:
+ case RecordValueType.Error:
+ if (typeof value.value !== 'string') {
+ throw new TypeError('Invalid record value.');
+ }
+ return JSON.stringify([value.type, value.value]);
+ case RecordValueType.Boolean:
+ if (typeof value.value !== 'boolean') {
+ throw new TypeError('Invalid record value.');
+ }
+ return JSON.stringify([value.type, value.value]);
+ case RecordValueType.Number:
+ case RecordValueType.Date:
+ if (typeof value.value !== 'number') {
+ throw new TypeError('Invalid record value.');
+ }
+ if (!Number.isFinite(value.value)) {
+ throw new RangeError('Record numeric values must be finite.');
+ }
+ return JSON.stringify([value.type, value.value === 0 ? 0 : value.value]);
+ default:
+ throw new TypeError('Unknown record value type.');
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
diff --git a/packages/core/src/shared/units.ts b/packages/core/src/shared/units.ts
new file mode 100644
index 0000000000..7d66543483
--- /dev/null
+++ b/packages/core/src/shared/units.ts
@@ -0,0 +1,26 @@
+/**
+ * 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.
+ */
+
+/** English Metric Units per CSS pixel at 96 DPI. */
+export const EMU_PER_CSS_PX = 9525;
+
+export function cssPxToEmu(value: number): number {
+ return Math.round(value * EMU_PER_CSS_PX);
+}
+
+export function emuToCssPx(value: number): number {
+ return value / EMU_PER_CSS_PX;
+}
diff --git a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
index 2dc88a7d7a..4a211709c7 100644
--- a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
+++ b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
@@ -18,6 +18,7 @@ import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
import type { ITableManualFilterItem, ITableRecordFilterItem } from '@univerjs/sheets-table';
import {
FilterSelectionMode,
+ getRecordValueKey,
ICommandService,
Inject,
Injector,
@@ -34,7 +35,6 @@ import {
} from '@univerjs/core';
import { SetRangeValuesMutation } from '@univerjs/sheets';
import {
- getTableRecordValueKey,
SetSheetTableFilterCommand,
SetSheetTableFilterMutation,
SheetTableService,
@@ -395,9 +395,9 @@ describe('SheetsTableUiService', () => {
],
});
const items = service.getTableFilterItems(unitId, 'sheet1', 'table-orders', 1);
- const numberKey = getTableRecordValueKey({ type: RecordValueType.Number, value: 12 });
- const stringKey = getTableRecordValueKey({ type: RecordValueType.String, value: '12' });
- const eightKey = getTableRecordValueKey({ type: RecordValueType.Number, value: 8 });
+ const numberKey = getRecordValueKey({ type: RecordValueType.Number, value: 12 });
+ const stringKey = getRecordValueKey({ type: RecordValueType.String, value: '12' });
+ const eightKey = getRecordValueKey({ type: RecordValueType.Number, value: 8 });
expect(items.data.map((item) => ({ title: item.title, valueKey: item.valueKey }))).toEqual([
{ title: '12', valueKey: numberKey },
{ title: '12', valueKey: stringKey },
@@ -499,7 +499,7 @@ describe('SheetsTableUiService', () => {
values: [{ type: RecordValueType.String, value: 'book' }],
});
expect(service.getTableFilterItems(unitId, 'sheet1', 'table-orders', 0).data[0].valueKey).toBe(
- getTableRecordValueKey({ type: RecordValueType.String, value: 'book' })
+ getRecordValueKey({ type: RecordValueType.String, value: 'book' })
);
await commandService.executeCommand(UndoCommand.id);
@@ -507,7 +507,7 @@ describe('SheetsTableUiService', () => {
await commandService.executeCommand(RedoCommand.id);
expect(service.getTableFilterItems(unitId, 'sheet1', 'table-orders', 0).data[0].valueKey).toBe(
- getTableRecordValueKey({ type: RecordValueType.String, value: 'book' })
+ getRecordValueKey({ type: RecordValueType.String, value: 'book' })
);
});
});
diff --git a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
index cf8700325d..87d7e9f9d8 100644
--- a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
+++ b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
@@ -22,12 +22,6 @@ import type {
ITableManualFilterItem,
ITableRecordFilterItem,
} from '@univerjs/sheets-table';
-import type { LocaleKey } from '../locale/types';
-import type {
- IFilterByValueWithTreeItem,
- ITableFilterColorList,
- ITableFilterItemList,
-} from '../types';
import {
cellToRange,
ColorKit,
@@ -35,6 +29,7 @@ import {
Disposable,
FilterSelectionMode,
getColorStyle,
+ getRecordValueKey,
ICommandService,
Inject,
IUniverInstanceService,
@@ -47,7 +42,6 @@ import { SetRangeValuesMutation } from '@univerjs/sheets';
import {
compileTableRecordFilter,
getTableRecordValue,
- getTableRecordValueKey,
isColorTableFilter,
isConditionFilter,
isManualTableFilter,
@@ -59,6 +53,12 @@ import {
TableColumnFilterTypeEnum,
TableManager,
} from '@univerjs/sheets-table';
+import type { LocaleKey } from '../locale/types';
+import type {
+ IFilterByValueWithTreeItem,
+ ITableFilterColorList,
+ ITableFilterItemList,
+} from '../types';
import { FilterByEnum } from '../types';
interface ISheetTableFilterPanelProps {
@@ -194,7 +194,7 @@ export class SheetsTableUiService extends Disposable {
const candidateKeys = new Set(recordItems.map((item) => item.valueKey!));
const values = currentFilter.values
- .filter((value) => !candidateKeys.has(getTableRecordValueKey(value)))
+ .filter((value) => !candidateKeys.has(getRecordValueKey(value)))
.map((value) => value.type === RecordValueType.Blank ? { type: RecordValueType.Blank } as const : { ...value });
recordItems.forEach((item) => {
const selected = checkedItemSet.has(item.valueKey!);
@@ -326,7 +326,7 @@ export class SheetsTableUiService extends Disposable {
: String(cellValue);
const recordValue = useRecordValues ? getTableRecordValue(worksheet, row, column) : undefined;
- const valueKey = recordValue ? getTableRecordValueKey(recordValue) : undefined;
+ const valueKey = recordValue ? getRecordValueKey(recordValue) : undefined;
const itemKey = valueKey ?? stringItem;
if (!map.has(itemKey)) {
data.push({
diff --git a/packages/sheets-table-ui/src/types.ts b/packages/sheets-table-ui/src/types.ts
index 593a02c512..9ef41881d3 100644
--- a/packages/sheets-table-ui/src/types.ts
+++ b/packages/sheets-table-ui/src/types.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { TableRecordValue } from '@univerjs/sheets-table';
+import type { RecordValue } from '@univerjs/core';
export enum FilterByEnum {
Items = 'items',
@@ -37,7 +37,7 @@ export interface IFilterByValueWithTreeItem {
key: string;
leaf: boolean;
valueKey?: string;
- recordValue?: TableRecordValue;
+ recordValue?: RecordValue;
originValues?: Set<string>;
children?: IFilterByValueWithTreeItem[];
}
diff --git a/packages/sheets-table/src/index.ts b/packages/sheets-table/src/index.ts
index 384c645ee1..f27bd0e455 100644
--- a/packages/sheets-table/src/index.ts
+++ b/packages/sheets-table/src/index.ts
@@ -46,7 +46,7 @@ export { SHEET_TABLE_CUSTOM_THEME_PREFIX, TABLE_FILTER_EMPTY_VALUE } from './con
export { SheetsTableThemeController } from './controllers/sheet-table-theme.controller';
export { SheetsTableController } from './controllers/sheets-table.controller';
export { customEmptyThemeWithBorderStyle, processStyleWithBorderStyle } from './controllers/table-theme.factory';
-export { compileTableRecordFilter, getTableRecordValue, getTableRecordValueKey } from './models/filter-util/record-filter';
+export { compileTableRecordFilter, getTableRecordValue } from './models/filter-util/record-filter';
export { TableManager } from './models/table-manager';
export { UniverSheetsTablePlugin } from './plugin';
export { SheetTableService } from './services/table.service';
@@ -76,10 +76,15 @@ export type {
ITableRangeWithState,
ITableRecordFilterItem,
TableMetaType,
- TableRecordValue,
TableRelationTupleType,
} from './types/type';
export type { ITableJson, ITableSetConfig } from './types/type';
-export { getExistingNamesSet, isColorTableFilter, isConditionFilter, isManualTableFilter, isRecordTableFilter } from './util';
+export {
+ getExistingNamesSet,
+ isColorTableFilter,
+ isConditionFilter,
+ isManualTableFilter,
+ isRecordTableFilter,
+} from './util';
export { validateSheetTableName } from './util/table-name';
export type { ISheetTableNameValidationResult, SheetTableNameValidationReason } from './util/table-name';
diff --git a/packages/sheets-table/src/models/filter-util/__tests__/record-filter.spec.ts b/packages/sheets-table/src/models/filter-util/__tests__/record-filter.spec.ts
index 311148268f..aa96385342 100644
--- a/packages/sheets-table/src/models/filter-util/__tests__/record-filter.spec.ts
+++ b/packages/sheets-table/src/models/filter-util/__tests__/record-filter.spec.ts
@@ -18,6 +18,7 @@ import type { IWorkbookData, Workbook } from '@univerjs/core';
import {
CellValueType,
FilterSelectionMode,
+ getRecordValueKey,
InterceptorEffectEnum,
LocaleType,
RecordValueType,
@@ -27,7 +28,7 @@ import {
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { afterEach, describe, expect, it } from 'vitest';
import { TableColumnFilterTypeEnum } from '../../../types/enum';
-import { compileTableRecordFilter, getTableRecordValue, getTableRecordValueKey } from '../record-filter';
+import { compileTableRecordFilter, getTableRecordValue } from '../record-filter';
function createWorkbookData(): IWorkbookData {
return {
@@ -107,8 +108,8 @@ describe('record-filter', () => {
expect(include({ type: RecordValueType.Blank })).toBe(true);
expect(exclude({ type: RecordValueType.String, value: 'blocked' })).toBe(false);
expect(exclude({ type: RecordValueType.String, value: 'new' })).toBe(true);
- const numberKey = getTableRecordValueKey({ type: RecordValueType.Number, value: 1 });
- const stringKey = getTableRecordValueKey({ type: RecordValueType.String, value: '1' });
+ const numberKey = getRecordValueKey({ type: RecordValueType.Number, value: 1 });
+ const stringKey = getRecordValueKey({ type: RecordValueType.String, value: '1' });
expect(numberKey).not.toBe(stringKey);
});
@@ -145,7 +146,7 @@ describe('record-filter', () => {
mode: FilterSelectionMode.Include,
values: [{ type: RecordValueType.Number, value: Number.POSITIVE_INFINITY }],
})).toThrow(RangeError);
- expect(() => getTableRecordValueKey({ type: RecordValueType.Blank, value: 'not-blank' } as never)).toThrow(TypeError);
- expect(() => getTableRecordValueKey({ type: 'unknown', value: 'x' } as never)).toThrow(TypeError);
+ expect(() => getRecordValueKey({ type: RecordValueType.Blank, value: 'not-blank' } as never)).toThrow(TypeError);
+ expect(() => getRecordValueKey({ type: 'unknown', value: 'x' } as never)).toThrow(TypeError);
});
});
diff --git a/packages/sheets-table/src/models/filter-util/record-filter.ts b/packages/sheets-table/src/models/filter-util/record-filter.ts
index 59ba651ce8..538ecaf27b 100644
--- a/packages/sheets-table/src/models/filter-util/record-filter.ts
+++ b/packages/sheets-table/src/models/filter-util/record-filter.ts
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-import type { Worksheet } from '@univerjs/core';
-import type { ITableRecordFilterItem, TableRecordValue } from '../../types/type';
-import { CellValueType, FilterSelectionMode, numfmt, RecordValueType } from '@univerjs/core';
+import type { RecordValue, Worksheet } from '@univerjs/core';
+import { CellValueType, FilterSelectionMode, getRecordValueKey, numfmt, RecordValueType } from '@univerjs/core';
import { extractFormulaError } from '@univerjs/engine-formula';
+import type { ITableRecordFilterItem } from '../../types/type';
import { TableColumnFilterTypeEnum } from '../../types/enum';
import { convertCellDataToString } from '../../util';
/**
* Formula errors are recognized when the cell retains formula, shared-formula, or intercepted array-formula context.
*/
-export function getTableRecordValue(sheet: Worksheet, row: number, column: number): TableRecordValue {
+export function getTableRecordValue(sheet: Worksheet, row: number, column: number): RecordValue {
const cell = sheet.getCell(row, column);
const error = extractFormulaError(cell, cell?.isInArrayFormulaRange === true);
if (error !== null) {
@@ -73,44 +73,7 @@ export function getTableRecordValue(sheet: Worksheet, row: number, column: numbe
throw new TypeError('Invalid table record cell value.');
}
-export function getTableRecordValueKey(_value: TableRecordValue): string {
- const value = _value as unknown;
- if (!isRecord(value) || typeof value.type !== 'string') {
- throw new TypeError('Invalid table record value.');
- }
-
- switch (value.type) {
- case RecordValueType.Blank:
- if ('value' in value) {
- throw new TypeError('Blank table record values cannot have a value.');
- }
- return '["blank"]';
- case RecordValueType.String:
- case RecordValueType.Error:
- if (typeof value.value !== 'string') {
- throw new TypeError('Invalid table record value.');
- }
- return JSON.stringify([value.type, value.value]);
- case RecordValueType.Boolean:
- if (typeof value.value !== 'boolean') {
- throw new TypeError('Invalid table record value.');
- }
- return JSON.stringify([value.type, value.value]);
- case RecordValueType.Number:
- case RecordValueType.Date:
- if (typeof value.value !== 'number') {
- throw new TypeError('Invalid table record value.');
- }
- if (!Number.isFinite(value.value)) {
- throw new RangeError('Table record numeric values must be finite.');
- }
- return JSON.stringify([value.type, value.value === 0 ? 0 : value.value]);
- default:
- throw new TypeError('Unknown table record value type.');
- }
-}
-
-export function compileTableRecordFilter(_filter: ITableRecordFilterItem): (value: TableRecordValue) => boolean {
+export function compileTableRecordFilter(_filter: ITableRecordFilterItem): (value: RecordValue) => boolean {
const filter = _filter as unknown;
if (!isRecord(filter) || filter.filterType !== TableColumnFilterTypeEnum.record) {
throw new TypeError('Invalid table record filter.');
@@ -119,11 +82,11 @@ export function compileTableRecordFilter(_filter: ITableRecordFilterItem): (valu
throw new TypeError('Invalid table record filter.');
}
- const keys = new Set(filter.values.map((value) => getTableRecordValueKey(value as TableRecordValue)));
+ const keys = new Set(filter.values.map((value) => getRecordValueKey(value as RecordValue)));
if (filter.mode === FilterSelectionMode.Include) {
- return (value) => keys.has(getTableRecordValueKey(value));
+ return (value) => keys.has(getRecordValueKey(value));
}
- return (value) => !keys.has(getTableRecordValueKey(value));
+ return (value) => !keys.has(getRecordValueKey(value));
}
export function cloneTableRecordFilter(filter: ITableRecordFilterItem): ITableRecordFilterItem {
diff --git a/packages/sheets-table/src/types/type.ts b/packages/sheets-table/src/types/type.ts
index 04a3633a85..4473c9333f 100644
--- a/packages/sheets-table/src/types/type.ts
+++ b/packages/sheets-table/src/types/type.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { FilterSelectionMode, IRange, IStyleData, Nullable, RecordValueType } from '@univerjs/core';
+import type { FilterSelectionMode, IRange, IStyleData, Nullable, RecordValue } from '@univerjs/core';
import type {
SheetsTableButtonStateEnum,
SheetsTableSortStateEnum,
@@ -74,13 +74,6 @@ export interface ITableFilterJSON {
tableSortInfo?: { columnIndex: number; sortState: SheetsTableSortStateEnum };
}
-export type TableRecordValue =
- | { type: RecordValueType.Blank }
- | { type: RecordValueType.String; value: string }
- | { type: RecordValueType.Number | RecordValueType.Date; value: number }
- | { type: RecordValueType.Boolean; value: boolean }
- | { type: RecordValueType.Error; value: string };
-
export type ITableFilterItem =
| ITableManualFilterItem
| ITableConditionFilterItem
@@ -120,7 +113,7 @@ export interface ITableColorFilterItem {
export interface ITableRecordFilterItem {
filterType: TableColumnFilterTypeEnum.record;
mode: FilterSelectionMode.Include | FilterSelectionMode.Exclude;
- values: TableRecordValue[];
+ values: RecordValue[];
}
export interface ITableDateFilterInfo {