Skip to content

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

feat(base): add record identity and record link contracts (#7380)

Univer767ba3e41162
diff --git a/packages/core/src/bases/__tests__/base-data-model.spec.ts b/packages/core/src/bases/__tests__/base-data-model.spec.ts
index b98ee0d711..2b9e9b1b57 100644
--- a/packages/core/src/bases/__tests__/base-data-model.spec.ts
+++ b/packages/core/src/bases/__tests__/base-data-model.spec.ts
@@ -15,11 +15,17 @@
*/
import type { IBaseSnapshot } from '../typedef';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { BaseDataModel } from '../base-data-model';
+import { BASE_RECORD_ID_FIELD_ID, createBaseRecordIdField } from '../record-identity';
import { BaseFieldType } from '../typedef';
describe('BaseDataModel', () => {
+ it('exposes RecordLink without the removed TwoWayLink field type', () => {
+ expect(Object.values(BaseFieldType)).toContain('recordLink');
+ expect(Object.values(BaseFieldType)).not.toContain('twoWayLink');
+ });
+
it('creates an empty default table without persistent records', () => {
const model = new BaseDataModel({ id: 'base-1', name: 'Base' });
const snapshot = model.getSnapshot();
@@ -31,14 +37,15 @@ describe('BaseDataModel', () => {
expect(table.rowId).toEqual({});
expect(table.rowIndex).toEqual({});
expect(table.cellData).toEqual({});
+ expect(table.fieldOrder[0]).toBe(BASE_RECORD_ID_FIELD_ID);
+ expect(table.fields[BASE_RECORD_ID_FIELD_ID]).toEqual(createBaseRecordIdField());
+ expect(table.views[table.viewOrder[0] ?? '']?.fieldSettings?.[BASE_RECORD_ID_FIELD_ID]?.hidden).toBe(true);
});
it('keeps complete recordOrder without sorting all records', () => {
- const throwingOrderKey = {
- localeCompare: () => {
- throw new Error('complete recordOrder should avoid sorting all records');
- },
- } as unknown as string;
+ const localeCompare = vi.spyOn(String.prototype, 'localeCompare').mockImplementation(() => {
+ throw new Error('complete recordOrder should avoid sorting all records');
+ });
const snapshot: Partial<IBaseSnapshot> = {
id: 'base-1',
name: 'Base',
@@ -48,24 +55,25 @@ describe('BaseDataModel', () => {
id: 'table-1',
name: 'Table',
fields: {
+ [BASE_RECORD_ID_FIELD_ID]: createBaseRecordIdField(),
title: { id: 'title', name: 'Title', type: BaseFieldType.Text, config: {} },
},
- fieldOrder: ['title'],
+ fieldOrder: [BASE_RECORD_ID_FIELD_ID, 'title'],
primaryFieldId: 'title',
records: {
'record-1': {
id: 'record-1',
- orderKey: throwingOrderKey,
+ orderKey: '1',
createdAt: 0,
updatedAt: 0,
- values: { title: 'One' },
+ values: { [BASE_RECORD_ID_FIELD_ID]: 'record-1', title: 'One' },
},
'record-2': {
id: 'record-2',
- orderKey: throwingOrderKey,
+ orderKey: '2',
createdAt: 0,
updatedAt: 0,
- values: { title: 'Two' },
+ values: { [BASE_RECORD_ID_FIELD_ID]: 'record-2', title: 'Two' },
},
},
recordOrder: ['record-2', 'record-1'],
@@ -78,5 +86,33 @@ describe('BaseDataModel', () => {
const model = new BaseDataModel(snapshot);
expect(model.getSnapshot().tables['table-1'].recordOrder).toEqual(['record-2', 'record-1']);
+ expect(model.getSnapshot().tables['table-1'].cellData?.[0]?.[0]?.v).toBe('record-2');
+ expect(model.getSnapshot().tables['table-1'].cellData?.[1]?.[0]?.v).toBe('record-1');
+ expect(localeCompare).not.toHaveBeenCalled();
+ localeCompare.mockRestore();
+ });
+
+ it('rejects a table whose record identity is missing instead of silently migrating it', () => {
+ const snapshot: Partial<IBaseSnapshot> = {
+ id: 'base-1',
+ name: 'Base',
+ tables: {
+ 'table-1': {
+ id: 'table-1',
+ name: 'Table',
+ fields: {
+ title: { id: 'title', name: 'Title', type: BaseFieldType.Text, config: {} },
+ },
+ fieldOrder: ['title'],
+ primaryFieldId: 'title',
+ records: {},
+ recordOrder: [],
+ viewOrder: [],
+ views: {},
+ },
+ },
+ };
+
+ expect(() => new BaseDataModel(snapshot)).toThrow('has an invalid record-id system field');
});
});
diff --git a/packages/core/src/bases/base-data-model.ts b/packages/core/src/bases/base-data-model.ts
index 7e428b9021..d4aadf8b9d 100644
--- a/packages/core/src/bases/base-data-model.ts
+++ b/packages/core/src/bases/base-data-model.ts
@@ -21,6 +21,7 @@ import { UnitModel, UniverInstanceType } from '../common/unit';
import { Tools } from '../shared/tools';
import { CellValueType } from '../types/enum';
import { getEmptySnapshot } from './empty-snapshot';
+import { assertBaseTableRecordIdentity, BASE_RECORD_ID_FIELD_ID } from './record-identity';
import { BaseFieldType } from './typedef';
const BASE_LIST_VALUE_SEPARATOR = ', ';
@@ -105,7 +106,9 @@ function normalizeBaseSnapshot(snapshot: IBaseSnapshot): IBaseSnapshot {
delete (snapshot as IBaseSnapshot & { compress?: unknown }).compress;
delete (snapshot as IBaseSnapshot & { kind?: unknown }).kind;
Object.values(snapshot.tables ?? {}).forEach((table) => {
+ assertBaseTableRecordIdentity(table);
normalizeBaseTable(table);
+ assertMaterializedRecordIdentity(table);
});
return snapshot;
}
@@ -117,6 +120,7 @@ function isNormalizedBaseSnapshot(snapshot: IBaseSnapshot): boolean {
function isNormalizedBaseTable(table: ITableSnapshot): boolean {
const records = table.records ?? {};
const fields = table.fields ?? {};
+ assertBaseTableRecordIdentity(table);
if (
!Array.isArray(table.recordOrder)
|| !table.rowIndex
@@ -137,7 +141,12 @@ function isNormalizedBaseTable(table: ITableSnapshot): boolean {
for (let index = 0; index < table.recordOrder.length; index++) {
const recordId = table.recordOrder[index];
- if (!records[recordId] || table.rowIndex[recordId] !== index || table.rowId[index] !== recordId) {
+ if (
+ !records[recordId]
+ || table.rowIndex[recordId] !== index
+ || table.rowId[index] !== recordId
+ || table.cellData[index]?.[0]?.v !== recordId
+ ) {
return false;
}
}
@@ -252,34 +261,56 @@ function rebuildColumnIndexes(table: ITableSnapshot, fields: Record<string, IFie
}
function hydrateRecordCellData(table: ITableSnapshot, records: Record<string, IRecordSnapshot>, fields: Record<string, IFieldSnapshot>): void {
+ const rowIndex = table.rowIndex ?? {};
+ const colIndex = table.colIndex ?? {};
+ const cellData = table.cellData ?? {};
+ table.rowIndex = rowIndex;
+ table.colIndex = colIndex;
+ table.cellData = cellData;
+
Object.values(records).forEach((record) => {
- const row = table.rowIndex![record.id];
+ const row = rowIndex[record.id];
if (row == null) {
return;
}
- table.cellData![row] = { ...table.cellData![row] };
+ cellData[row] = { ...cellData[row] };
+ cellData[row][0] = { v: record.id, t: CellValueType.STRING };
Object.entries(record.values ?? {}).forEach(([fieldId, value]) => {
const field = fields[fieldId];
if (field?.type === BaseFieldType.Attachment) {
writeAttachmentResources(table, record.id, fieldId, value);
}
- const col = table.colIndex![fieldId];
+ const col = colIndex[fieldId];
if (col == null) {
return;
}
- const existingCell = table.cellData![row][col];
+ const existingCell = cellData[row][col];
if (existingCell != null) {
- table.cellData![row][col] = normalizeBaseCellData(existingCell, field);
+ cellData[row][col] = normalizeBaseCellData(existingCell, field);
if (shouldRefreshCellDataFromRecord(existingCell, field, value)) {
- table.cellData![row][col] = toBaseCellData(value, field);
+ cellData[row][col] = toBaseCellData(value, field);
}
return;
}
- table.cellData![row][col] = toBaseCellData(value, field);
+ cellData[row][col] = toBaseCellData(value, field);
});
});
}
+function assertMaterializedRecordIdentity(table: ITableSnapshot): void {
+ for (const record of Object.values(table.records)) {
+ const row = table.rowIndex?.[record.id];
+ if (
+ row == null
+ || table.colIndex?.[BASE_RECORD_ID_FIELD_ID] !== 0
+ || table.colId?.[0] !== BASE_RECORD_ID_FIELD_ID
+ || table.cellData?.[row]?.[0]?.v !== record.id
+ ) {
+ throw new Error(`[BaseDataModel]: record "${record.id}" is missing its record-id cell projection.`);
+ }
+ }
+}
+
function toBaseCellData(value: CellValue | IBaseCellData, field?: IFieldSnapshot): IBaseCellData {
if (isBaseCellData(value)) {
if (field?.type === BaseFieldType.Attachment) {
@@ -361,6 +392,9 @@ function normalizeAttachmentValue(value: unknown): Record<string, unknown>[] {
}
function shouldRefreshCellDataFromRecord(cell: IBaseCellData, field: IFieldSnapshot | undefined, value: unknown): boolean {
+ if (field?.type === BaseFieldType.RecordId) {
+ return cell.v !== value;
+ }
if (field?.type === BaseFieldType.Attachment) {
return cell.v !== '';
}
diff --git a/packages/core/src/bases/empty-snapshot.ts b/packages/core/src/bases/empty-snapshot.ts
index f92f89cfcc..92479cd9e0 100644
--- a/packages/core/src/bases/empty-snapshot.ts
+++ b/packages/core/src/bases/empty-snapshot.ts
@@ -17,7 +17,8 @@
import type { IBaseSnapshot, IFieldSnapshot, IRecordSnapshot, ITableSnapshot, IViewSnapshot } from './typedef';
import pkg from '../../package.json';
import { generateRandomId } from '../shared';
-import { LocaleType } from '../types/enum';
+import { CellValueType, LocaleType } from '../types/enum';
+import { BASE_RECORD_ID_FIELD_ID, createBaseRecordIdField } from './record-identity';
import { BaseFieldType, BaseViewType } from './typedef';
export interface ICreateDefaultBaseTableSnapshotOptions {
@@ -35,6 +36,7 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableS
const primaryFieldId = options.primaryFieldId ?? generateRandomId(6);
const gridViewId = options.gridViewId ?? generateRandomId(6);
const recordCount = options.recordCount ?? 0;
+ const recordIdField = createBaseRecordIdField();
const primaryField: IFieldSnapshot = {
id: primaryFieldId,
name: options.primaryFieldName ?? 'Name',
@@ -51,7 +53,7 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableS
const recordId = `${options.id}-record-${index + 1}`;
records[recordId] = {
id: recordId,
- values: {},
+ values: { [BASE_RECORD_ID_FIELD_ID]: recordId },
orderKey: String(index + 1).padStart(4, '0'),
createdAt: now,
updatedAt: now,
@@ -59,7 +61,9 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableS
recordOrder.push(recordId);
rowIndex[recordId] = index;
rowId[index] = recordId;
- cellData[index] = {};
+ cellData[index] = {
+ 0: { v: recordId, t: CellValueType.STRING },
+ };
}
const gridView: IViewSnapshot = {
@@ -67,8 +71,10 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableS
tableId: options.id,
name: 'Grid',
type: BaseViewType.Grid,
- fieldOrder: [primaryFieldId],
- fieldSettings: {},
+ fieldOrder: [BASE_RECORD_ID_FIELD_ID, primaryFieldId],
+ fieldSettings: {
+ [BASE_RECORD_ID_FIELD_ID]: { hidden: true },
+ },
config: { frozenFieldCount: 1 },
};
@@ -76,14 +82,23 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableS
id: options.id,
name: options.name,
primaryFieldId,
- fieldOrder: [primaryFieldId],
- fields: { [primaryFieldId]: primaryField },
+ fieldOrder: [BASE_RECORD_ID_FIELD_ID, primaryFieldId],
+ fields: {
+ [BASE_RECORD_ID_FIELD_ID]: recordIdField,
+ [primaryFieldId]: primaryField,
+ },
records,
recordOrder,
rowIndex,
rowId,
- colIndex: { [primaryFieldId]: 0 },
- colId: { 0: primaryFieldId },
+ colIndex: {
+ [BASE_RECORD_ID_FIELD_ID]: 0,
+ [primaryFieldId]: 1,
+ },
+ colId: {
+ 0: BASE_RECORD_ID_FIELD_ID,
+ 1: primaryFieldId,
+ },
cellData,
resources: {
attachmentSets: {},
@@ -107,7 +122,7 @@ export function getEmptySnapshot(
name,
locale,
appVersion: pkg.version,
- schemaVersion: 1,
+ schemaVersion: 2,
tableOrder: [tableId],
tables: {
[tableId]: createDefaultBaseTableSnapshot({
diff --git a/packages/core/src/bases/index.ts b/packages/core/src/bases/index.ts
index b1ca4205be..c56b7f85b8 100644
--- a/packages/core/src/bases/index.ts
+++ b/packages/core/src/bases/index.ts
@@ -20,6 +20,14 @@ export {
getEmptySnapshot as getBasesEmptySnapshot,
type ICreateDefaultBaseTableSnapshotOptions,
} from './empty-snapshot';
+export {
+ assertBaseTableRecordIdentity,
+ BASE_RECORD_ID_FIELD_ID,
+ BASE_RECORD_ID_FIELD_NAME,
+ createBaseRecordIdField,
+ isBaseRecordIdFieldName,
+ isValidBaseRecordId,
+} from './record-identity';
export { BaseFieldType, BaseFilterConjunction, BaseFilterOperator, BaseSortDirection, BaseViewType } from './typedef';
export type {
BaseCellMatrix,
@@ -78,6 +86,7 @@ export type {
IProjectedField,
IProjectedGroup,
IProjectedRow,
+ IRecordLinkFieldConfig,
IRecordSnapshot,
ISortConfig,
ITableSnapshot,
diff --git a/packages/core/src/bases/record-identity.ts b/packages/core/src/bases/record-identity.ts
new file mode 100644
index 0000000000..0d056de24a
--- /dev/null
+++ b/packages/core/src/bases/record-identity.ts
@@ -0,0 +1,77 @@
+/**
+ * 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 { IFieldSnapshot, ITableSnapshot } from './typedef';
+import { BaseFieldType } from './typedef';
+
+export const BASE_RECORD_ID_FIELD_ID = '__record_id';
+export const BASE_RECORD_ID_FIELD_NAME = 'record-id';
+
+const BASE_RECORD_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
+
+export function createBaseRecordIdField(): IFieldSnapshot {
+ return {
+ id: BASE_RECORD_ID_FIELD_ID,
+ name: BASE_RECORD_ID_FIELD_NAME,
+ type: BaseFieldType.RecordId,
+ config: {},
+ system: true,
+ readonly: true,
+ };
+}
+
+export function isValidBaseRecordId(recordId: string): boolean {
+ return BASE_RECORD_ID_PATTERN.test(recordId);
+}
+
+export function isBaseRecordIdFieldName(name: string): boolean {
+ return name.trim().toLowerCase() === BASE_RECORD_ID_FIELD_NAME;
+}
+
+export function assertBaseTableRecordIdentity(table: ITableSnapshot): void {
+ const recordIdField = table.fields[BASE_RECORD_ID_FIELD_ID];
+ const recordIdFields = Object.values(table.fields).filter((field) => field.type === BaseFieldType.RecordId);
+ if (
+ !recordIdField
+ || recordIdFields.length !== 1
+ || recordIdField.type !== BaseFieldType.RecordId
+ || recordIdField.name !== BASE_RECORD_ID_FIELD_NAME
+ || recordIdField.system !== true
+ || recordIdField.readonly !== true
+ || table.fieldOrder[0] !== BASE_RECORD_ID_FIELD_ID
+ || table.primaryFieldId === BASE_RECORD_ID_FIELD_ID
+ || !table.fields[table.primaryFieldId]
+ ) {
+ throw new Error(`[BaseDataModel]: table "${table.id}" has an invalid record-id system field.`);
+ }
+
+ const conflictingField = Object.values(table.fields).find((field) => {
+ return field.id !== BASE_RECORD_ID_FIELD_ID && isBaseRecordIdFieldName(field.name);
+ });
+ if (conflictingField) {
+ throw new Error(`[BaseDataModel]: field name "${conflictingField.name}" is reserved for the record-id system field.`);
+ }
+
+ for (const [recordKey, record] of Object.entries(table.records)) {
+ if (
+ record.id !== recordKey
+ || !isValidBaseRecordId(record.id)
+ || record.values[BASE_RECORD_ID_FIELD_ID] !== record.id
+ ) {
+ throw new Error(`[BaseDataModel]: record "${recordKey}" has an invalid record-id projection.`);
+ }
+ }
+}
diff --git a/packages/core/src/bases/typedef.ts b/packages/core/src/bases/typedef.ts
index dcc8b49f5b..d114206eeb 100644
--- a/packages/core/src/bases/typedef.ts
+++ b/packages/core/src/bases/typedef.ts
@@ -115,7 +115,7 @@ export enum BaseFieldType {
Progress = 'progress',
Currency = 'currency',
Rating = 'rating',
- TwoWayLink = 'twoWayLink',
+ RecordLink = 'recordLink',
RecordId = 'recordId',
CreatedBy = 'createdBy',
UpdatedBy = 'updatedBy',
@@ -124,6 +124,15 @@ export enum BaseFieldType {
Summary = 'summary',
}
+export interface IRecordLinkFieldConfig extends Record<string, unknown> {
+ targetTableId: TableId;
+ multiple: boolean;
+ /** Field used as the single visible RecordLink label. Defaults to the target table primary field. */
+ displayFieldId?: FieldId;
+ /** Ordered target-table fields rendered as secondary context in the record picker. */
+ pickerFieldIds?: FieldId[];
+}
+
export enum BaseViewType {
Grid = 'grid',
Kanban = 'kanban',
@@ -466,6 +475,7 @@ export interface IGridProjection extends IViewProjection {
export interface IKanbanProjection extends IViewProjection {
type: BaseViewType.Kanban;
groupFieldId: FieldId;
+ titleFieldId?: FieldId;
coverFieldId?: FieldId | null;
cardLayout: KanbanCardLayoutMode;
showFieldNames: boolean;
@@ -534,6 +544,7 @@ export interface IGanttProjection extends IViewProjection {
export interface IGalleryProjection extends IViewProjection {
type: BaseViewType.Gallery;
+ titleFieldId?: FieldId;
coverFieldId?: FieldId | null;
cardLayout: KanbanCardLayoutMode;
showFieldNames: boolean;
diff --git a/packages/design/src/components/select/MultipleSelect.tsx b/packages/design/src/components/select/MultipleSelect.tsx
index 14d4613be6..4dd08f91ed 100644
--- a/packages/design/src/components/select/MultipleSelect.tsx
+++ b/packages/design/src/components/select/MultipleSelect.tsx
@@ -92,7 +92,7 @@ export function MultipleSelect(props: IMultipleSelectProps) {
},
};
});
- }, [options]);
+ }, [onChange, options, value]);
function handleClose(item: string) {
const newValue = value.filter((v) => v !== item);
diff --git a/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx b/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx
index b2e0e6919c..6f0b35c264 100644
--- a/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx
+++ b/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx
@@ -73,4 +73,16 @@ describe('MultipleSelect logic branches', () => {
fireEvent.click(screen.getByTestId('close-menu'));
expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-cursor-pointer');
});
+
+ it('uses the latest controlled value when selecting consecutive items', () => {
+ const onChange = vi.fn();
+ const { rerender } = render(<MultipleSelect value={[]} options={options} onChange={onChange} />);
+
+ fireEvent.click(screen.getByTestId('item-1'));
+ expect(onChange).toHaveBeenLastCalledWith(['1']);
+
+ rerender(<MultipleSelect value={['1']} options={options} onChange={onChange} />);
+ fireEvent.click(screen.getByTestId('item-2'));
+ expect(onChange).toHaveBeenLastCalledWith(['1', '2']);
+ });
});
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
index b2a7da766e..5661736411 100644
--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -17,10 +17,12 @@
import type { IBaseSnapshot, ICellData, Injector, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';
import type { IFormulaData } from '../../basics/common';
import {
+ BASE_RECORD_ID_FIELD_ID,
BaseDataModel,
BaseFieldType,
BooleanNumber,
CellValueType,
+ createBaseRecordIdField,
IUniverInstanceService,
LocaleType,
ObjectMatrix,
@@ -110,7 +112,7 @@ const TEST_WORKBOOK_DATA_EXTRA: IWorkbookData = {
const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
id: 'base-test',
name: 'Base',
- schemaVersion: 1,
+ schemaVersion: 2,
tableOrder: ['table-main', 'tableOther'],
createdAt: 0,
updatedAt: 0,
@@ -119,8 +121,9 @@ const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
id: 'table-main',
name: 'Sales',
primaryFieldId: 'name',
- fieldOrder: ['name', 'amount', 'qty', 'tags', 'link', 'attachment', 'total'],
+ fieldOrder: [BASE_RECORD_ID_FIELD_ID, 'name', 'amount', 'qty', 'tags', 'link', 'attachment', 'total'],
fields: {
+ [BASE_RECORD_ID_FIELD_ID]: createBaseRecordIdField(),
name: { id: 'name', name: 'Name', type: BaseFieldType.Text, config: {} },
amount: { id: 'amount', name: 'Amount', type: BaseFieldType.Number, config: {} },
qty: { id: 'qty', name: 'Qty', type: BaseFieldType.Number, config: {} },
@@ -143,6 +146,7 @@ const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
createdAt: 0,
updatedAt: 0,
values: {
+ [BASE_RECORD_ID_FIELD_ID]: 'record-1',
name: 'Order 1',
amount: 10,
qty: 2,
@@ -160,8 +164,9 @@ const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
id: 'tableOther',
name: 'Sales',
primaryFieldId: 'external',
- fieldOrder: ['external'],
+ fieldOrder: [BASE_RECORD_ID_FIELD_ID, 'external'],
fields: {
+ [BASE_RECORD_ID_FIELD_ID]: createBaseRecordIdField(),
external: { id: 'external', name: 'External', type: BaseFieldType.Number, config: {} },
},
records: {
@@ -170,7 +175,7 @@ const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
orderKey: 'a',
createdAt: 0,
updatedAt: 0,
- values: { external: 8 },
+ values: { [BASE_RECORD_ID_FIELD_ID]: 'record-2', external: 8 },
},
},
recordOrder: ['record-2'],
@@ -1054,8 +1059,8 @@ describe('Test formula data model', () => {
const formulaData = formulaDataModel.getFormulaData();
expect(formulaData['base-test']?.['table-main']).toEqual({
0: {
- 6: {
- f: '=SUM(table-main[[#This Row],[Amount]], table-main[[#This Row],[Qty]], tableOther[[#This Row],[External]])',
+ 7: {
+ f: '=SUM(table-main[[#This Row],[Amount]], table-main[[#This Row],[Qty]], tableOther[[#Data],[External]])',
si: 'total',
},
},
@@ -1070,12 +1075,13 @@ describe('Test formula data model', () => {
});
expect(calculateData.unitSheetNameMap['base-test']?.Sales).toBe('tableOther');
expect(tableData?.rowCount).toBe(1);
- expect(tableData?.columnCount).toBe(7);
- expect(tableData?.cellData.getValue(0, 0)).toEqual({ v: 'Order 1', t: CellValueType.STRING });
- expect(tableData?.cellData.getValue(0, 1)).toEqual({ v: 10, t: CellValueType.NUMBER });
- expect(tableData?.cellData.getValue(0, 3)).toEqual({ v: 'paid, online', t: CellValueType.STRING });
- expect(tableData?.cellData.getValue(0, 4)).toEqual({ v: 'Invoice', t: CellValueType.STRING });
- expect(tableData?.cellData.getValue(0, 5)).toEqual({ v: '', t: CellValueType.STRING });
+ expect(tableData?.columnCount).toBe(8);
+ expect(tableData?.cellData.getValue(0, 0)).toEqual({ v: 'record-1', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 1)).toEqual({ v: 'Order 1', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 2)).toEqual({ v: 10, t: CellValueType.NUMBER });
+ expect(tableData?.cellData.getValue(0, 4)).toEqual({ v: 'paid, online', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 5)).toEqual({ v: 'Invoice', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 6)).toEqual({ v: '', t: CellValueType.STRING });
});
it('should preserve workbook-qualified A1 references in Base formulas', () => {
@@ -1088,7 +1094,7 @@ describe('Test formula data model', () => {
};
univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
- expect(formulaDataModel.getFormulaData()['base-external-a1']?.['table-main']?.[0]?.[6]?.f).toBe(
+ expect(formulaDataModel.getFormulaData()['base-external-a1']?.['table-main']?.[0]?.[7]?.f).toBe(
'=SUM([Host.xlsx]Sheet1!$A$1:$B$10)'
);
});
@@ -1103,7 +1109,7 @@ describe('Test formula data model', () => {
};
univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
- expect(formulaDataModel.getFormulaData()['base-external-table']?.['table-main']?.[0]?.[6]?.f).toBe(
+ expect(formulaDataModel.getFormulaData()['base-external-table']?.['table-main']?.[0]?.[7]?.f).toBe(
'=SUM([Orders Base]!Orders[Amount])'
);
});
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index c396ff04c9..7d94d9a81d 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -952,7 +952,7 @@ function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnap
.replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName: string) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot)))
.replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName: string, fieldName: string) => {
const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
- return targetTable ? hold(createEngineThisRowRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
+ return targetTable ? hold(createEngineColumnRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
})
.replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix: string, fieldName: string) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`);
return normalized.replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index: string) => refs[Number(index)] ?? '');
@@ -1015,6 +1015,10 @@ function createEngineThisRowRef(table: ITableSnapshot, fieldName: string, snapsh
return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
}
+function createEngineColumnRef(table: ITableSnapshot, fieldName: string, snapshot: IBaseSnapshot): string {
+ return `${getEngineBaseTableName(table, snapshot)}[[#Data],[${fieldName}]]`;
+}
+
function getEngineBaseTableName(table: ITableSnapshot, snapshot: IBaseSnapshot): string {
const tables = Object.values(snapshot.tables);
let sameNameCount = 0;