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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(core): add runtime enums for bases (#7234)
wpxp12345668536170034a
diff --git a/packages/core/src/bases/__tests__/base-data-model.spec.ts b/packages/core/src/bases/__tests__/base-data-model.spec.tsindex ae3bcddf6e..20947e8d3f 100644--- a/packages/core/src/bases/__tests__/base-data-model.spec.ts+++ b/packages/core/src/bases/__tests__/base-data-model.spec.ts@@ -17,6 +17,7 @@import type { IBaseSnapshot } from '../typedef';import { describe, expect, it } from 'vitest';import { BaseDataModel } from '../base-data-model';+import { BaseFieldType } from '../typedef';describe('BaseDataModel', () => {it('keeps complete recordOrder without sorting all records', () => {@@ -34,7 +35,7 @@ describe('BaseDataModel', () => {id: 'table-1',name: 'Table',fields: {- title: { id: 'title', name: 'Title', type: 'text', config: {} },+ title: { id: 'title', name: 'Title', type: BaseFieldType.Text, config: {} },},fieldOrder: ['title'],primaryFieldId: 'title',diff --git a/packages/core/src/bases/base-data-model.ts b/packages/core/src/bases/base-data-model.tsindex 249522c184..36408592ca 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 { BaseFieldType } from './typedef';const BASE_LIST_VALUE_SEPARATOR = ', ';const BASE_ATTACHMENT_RESOURCE_KEY_SEPARATOR = '\u001F';@@ -61,6 +62,27 @@ export class BaseDataModel extends UnitModel<IBaseSnapshot, UniverInstanceType.Ureturn this._snapshot;}+ /**+ * Check if a non-deleted table name already exists, ignoring case.+ * Returns true when the name is already used.+ */+ checkTableName(name: string): boolean {+ return Object.values(this._snapshot.tables).some((table) => !table.deleted && table.name.toLowerCase() === name.toLowerCase());+ }++ /**+ * Generate a table name that does not conflict with existing non-deleted tables.+ */+ uniqueTableName(name: string): string {+ let output = name;+ let count = 1;+ while (this.checkTableName(output)) {+ output = `${name}${count}`;+ count++;+ }+ return output;+ }+setSnapshot(snapshot: IBaseSnapshot): void {this._snapshot = isNormalizedBaseSnapshot(snapshot) ? snapshot : normalizeBaseSnapshot(snapshot);this._name$.next(snapshot.name);@@ -243,7 +265,7 @@ function hydrateRecordCellData(table: ITableSnapshot, records: Record<string, IRtable.cellData![row] = { ...table.cellData![row] };Object.entries(record.values ?? {}).forEach(([fieldId, value]) => {const field = fields[fieldId];- if (field?.type === 'attachment') {+ if (field?.type === BaseFieldType.Attachment) {writeAttachmentResources(table, record.id, fieldId, value);}const col = table.colIndex![fieldId];@@ -265,18 +287,18 @@ function hydrateRecordCellData(table: ITableSnapshot, records: Record<string, IRfunction toBaseCellData(value: CellValue | IBaseCellData, field?: IFieldSnapshot): IBaseCellData {if (isBaseCellData(value)) {- if (field?.type === 'attachment') {+ if (field?.type === BaseFieldType.Attachment) {return { ...value, v: '', t: CellValueType.STRING };}return normalizeBaseCellData(value, field);}- if (field?.type === 'attachment') {+ if (field?.type === BaseFieldType.Attachment) {return { v: '', t: CellValueType.STRING };}if (isListField(field)) {return { v: normalizeListValue(value).join(BASE_LIST_VALUE_SEPARATOR), t: CellValueType.STRING };}- if (field?.type === 'link' && value && typeof value === 'object' && !Array.isArray(value)) {+ if (field?.type === BaseFieldType.Link && value && typeof value === 'object' && !Array.isArray(value)) {const link = value as { text?: unknown; url?: unknown };return { v: String(link.text ?? link.url ?? ''), t: CellValueType.STRING };}@@ -344,7 +366,7 @@ function normalizeAttachmentValue(value: unknown): Record<string, unknown>[] {}function shouldRefreshCellDataFromRecord(cell: IBaseCellData, field: IFieldSnapshot | undefined, value: unknown): boolean {- if (field?.type === 'attachment') {+ if (field?.type === BaseFieldType.Attachment) {return cell.v !== '';}if (isListField(field)) {@@ -353,8 +375,8 @@ function shouldRefreshCellDataFromRecord(cell: IBaseCellData, field: IFieldSnapsreturn false;}-function isListField(field?: IFieldSnapshot): field is IFieldSnapshot & { type: 'multiSelect' | 'person' | 'group' } {- return field?.type === 'multiSelect' || field?.type === 'person' || field?.type === 'group';+function isListField(field?: IFieldSnapshot): boolean {+ return field?.type === BaseFieldType.MultiSelect || field?.type === BaseFieldType.Person || field?.type === BaseFieldType.Group;}function normalizeListValue(value: unknown): string[] {diff --git a/packages/core/src/bases/empty-snapshot.ts b/packages/core/src/bases/empty-snapshot.tsindex 854d1e7123..79acf61bf8 100644--- a/packages/core/src/bases/empty-snapshot.ts+++ b/packages/core/src/bases/empty-snapshot.ts@@ -18,6 +18,7 @@ import type { IBaseSnapshot, IFieldSnapshot, IRecordSnapshot, ITableSnapshot, IVimport pkg from '../../package.json';import { generateRandomId } from '../shared';import { LocaleType } from '../types/enum';+import { BaseFieldType, BaseViewType } from './typedef';export interface ICreateDefaultBaseTableSnapshotOptions {id: string;@@ -31,13 +32,13 @@ export interface ICreateDefaultBaseTableSnapshotOptions {export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableSnapshotOptions): ITableSnapshot {const now = options.now ?? Date.now();- const primaryFieldId = options.primaryFieldId ?? `${options.id}-field-name`;- const gridViewId = options.gridViewId ?? `${options.id}-view-grid`;+ const primaryFieldId = options.primaryFieldId ?? generateRandomId(6);+ const gridViewId = options.gridViewId ?? generateRandomId(6);const recordCount = options.recordCount ?? 5;const primaryField: IFieldSnapshot = {id: primaryFieldId,name: options.primaryFieldName ?? 'Name',- type: 'text',+ type: BaseFieldType.Text,config: { placeholder: 'bases.fieldConfig.textPlaceholder' },};const records: Record<string, IRecordSnapshot> = {};@@ -65,7 +66,7 @@ export function createDefaultBaseTableSnapshot(options: ICreateDefaultBaseTableSid: gridViewId,tableId: options.id,name: 'Grid',- type: 'grid',+ type: BaseViewType.Grid,fieldOrder: [primaryFieldId],fieldSettings: {},config: { frozenFieldCount: 1 },diff --git a/packages/core/src/bases/index.ts b/packages/core/src/bases/index.tsindex f41e3485f8..4fad5afd77 100644--- a/packages/core/src/bases/index.ts+++ b/packages/core/src/bases/index.ts@@ -20,54 +20,28 @@ export {getEmptySnapshot as getBasesEmptySnapshot,type ICreateDefaultBaseTableSnapshotOptions,} from './empty-snapshot';+export { BaseFieldType, BaseFilterConjunction, BaseFilterOperator, BaseSortDirection, BaseViewType } from './typedef';export type {- BaseCellData,BaseCellMatrix,BaseCellPrimitiveValue,CellValue as BaseCellValue,BaseCellValueType,BaseHitTestResult,BaseId,- BaseInvalidation,PrimitiveCellValue as BasePrimitiveCellValue,- BaseResources,BaseSelection,BaseSnapshot,- BaseViewColorCondition,BaseViewProjection,- CalendarEventResizeSelection,- CalendarEventSelection,- CalendarProjection,- CalendarViewConfig,- CardLayoutConfig,- FieldCapabilities,FieldConfig,FieldId,FieldSnapshot,- FieldType,- FilterCondition,- FilterConfig,- FilterOperator,- GalleryCardSelection,- GalleryProjection,- GalleryViewConfig,- GanttBarSelection,- GanttCellSelection,- GanttProjection,- GanttTimeColumn,- GanttViewConfig,- GridCellSelection,- GridFieldSelection,- GridGroupSelection,- GridProjection,- GridRecordSelection,- GridViewConfig,- GroupConfig,IBaseCellData,IBaseInvalidation,+ IBaseRect,IBaseResources,IBaseSnapshot,IBaseViewColorCondition,+ IBaseViewport,ICalendarEventResizeSelection,ICalendarEventSelection,ICalendarProjection,@@ -98,40 +72,22 @@ export type {IKanbanFieldCardSetting,IKanbanProjection,IKanbanViewConfig,- InvalidViewProjection,IProjectedField,IProjectedGroup,IProjectedRow,IRecordSnapshot,- IRect,ISortConfig,ITableSnapshot,IValidationResult,IViewFieldSetting,- IViewport,IViewProjection,IViewSnapshot,KanbanCardLayoutMode,- KanbanCardSelection,- KanbanColumnSetting,- KanbanFieldCardSetting,- KanbanProjection,- KanbanViewConfig,- ProjectedField,- ProjectedGroup,- ProjectedRow,RecordId,RecordSnapshot,- Rect,- SortConfig,TableId,TableSnapshot,- ValidationResult,- ViewFieldSetting,ViewId,- Viewport,- ViewProjection,ViewSnapshot,ViewSpecificConfig,- ViewType,} from './typedef';diff --git a/packages/core/src/bases/typedef.ts b/packages/core/src/bases/typedef.tsindex 0de8d92e82..7c89f12af2 100644--- a/packages/core/src/bases/typedef.ts+++ b/packages/core/src/bases/typedef.ts@@ -51,38 +51,45 @@ export interface IBaseResources {attachments?: Record<string, Record<string, unknown>>;}-export type FieldType =- | 'text'- | 'singleSelect'- | 'multiSelect'- | 'person'- | 'group'- | 'date'- | 'attachment'- | 'number'- | 'checkbox'- | 'link'- | 'formula'- | 'lookup'- | 'flow'- | 'button'- | 'numbering'- | 'phone'- | 'email'- | 'location'- | 'barcode'- | 'progress'- | 'currency'- | 'rating'- | 'twoWayLink'- | 'recordId'- | 'createdBy'- | 'updatedBy'- | 'createdAt'- | 'updatedAt'- | 'summary';--export type ViewType = 'grid' | 'kanban' | 'calendar' | 'gantt' | 'gallery';+export enum BaseFieldType {+ Text = 'text',+ SingleSelect = 'singleSelect',+ MultiSelect = 'multiSelect',+ Person = 'person',+ Group = 'group',+ Date = 'date',+ Attachment = 'attachment',+ Number = 'number',+ Checkbox = 'checkbox',+ Link = 'link',+ Formula = 'formula',+ Lookup = 'lookup',+ Flow = 'flow',+ Button = 'button',+ Numbering = 'numbering',+ Phone = 'phone',+ Email = 'email',+ Location = 'location',+ Barcode = 'barcode',+ Progress = 'progress',+ Currency = 'currency',+ Rating = 'rating',+ TwoWayLink = 'twoWayLink',+ RecordId = 'recordId',+ CreatedBy = 'createdBy',+ UpdatedBy = 'updatedBy',+ CreatedAt = 'createdAt',+ UpdatedAt = 'updatedAt',+ Summary = 'summary',+}++export enum BaseViewType {+ Grid = 'grid',+ Kanban = 'kanban',+ Calendar = 'calendar',+ Gantt = 'gantt',+ Gallery = 'gallery',+}export type FieldConfig = Record<string, unknown>;export type ViewSpecificConfig =@@ -141,7 +148,7 @@ export interface IFieldSnapshot {id: FieldId;name: string;description?: string;- type: FieldType;+ type: BaseFieldType;config: FieldConfig;defaultValue?: CellValue;system?: boolean;@@ -153,7 +160,7 @@ export interface IViewSnapshot<TConfig extends ViewSpecificConfig = ViewSpecificid: ViewId;tableId: TableId;name: string;- type: ViewType;+ type: BaseViewType;fieldOrder?: FieldId[];fieldSettings?: Record<FieldId, IViewFieldSetting>;filter?: IFilterConfig | null;@@ -197,37 +204,50 @@ export interface IValidationResult {reason?: string;}-export type FilterOperator =- | 'is'- | 'isNot'- | 'contains'- | 'notContains'- | 'isEmpty'- | 'isNotEmpty'- | 'greaterThan'- | 'greaterThanOrEqual'- | 'lessThan'- | 'lessThanOrEqual';+export enum BaseFilterOperator {+ IS = 'is',+ IS_NOT = 'isNot',+ CONTAINS = 'contains',+ NOT_CONTAINS = 'notContains',+ IS_EMPTY = 'isEmpty',+ IS_NOT_EMPTY = 'isNotEmpty',+ GREATER_THAN = 'greaterThan',+ GREATER_THAN_OR_EQUAL = 'greaterThanOrEqual',+ LESS_THAN = 'lessThan',+ LESS_THAN_OR_EQUAL = 'lessThanOrEqual',+ BEFORE = 'before',+ AFTER = 'after',+}++export enum BaseFilterConjunction {+ AND = 'and',+ OR = 'or',+}export interface IFilterConfig {- conjunction: 'and' | 'or';+ conjunction: BaseFilterConjunction;conditions: IFilterCondition[];}export interface IFilterCondition {fieldId: FieldId;- operator: string;+ operator: BaseFilterOperator;operand?: unknown;}+export enum BaseSortDirection {+ ASC = 'asc',+ DESC = 'desc',+}+export interface ISortConfig {fieldId: FieldId;- direction: 'asc' | 'desc';+ direction: BaseSortDirection;}export interface IGroupConfig {fieldId: FieldId;- direction?: 'asc' | 'desc';+ direction?: BaseSortDirection;hideEmptyGroup?: boolean;}@@ -351,14 +371,14 @@ export interface IProjectedField {id: FieldId;name: string;description?: string;- type: FieldType;+ type: BaseFieldType;config?: FieldConfig;width?: number;setting: IViewFieldSetting;}export interface IViewProjection {- type: ViewType;+ type: BaseViewType;fields: IProjectedField[];rows: IProjectedRow[];groups?: IProjectedGroup[];@@ -380,12 +400,12 @@ export interface IProjectedGroup {}export interface IGridProjection extends IViewProjection {- type: 'grid';+ type: BaseViewType.Grid;frozenFieldCount?: number;}export interface IKanbanProjection extends IViewProjection {- type: 'kanban';+ type: BaseViewType.Kanban;groupFieldId: FieldId;coverFieldId?: FieldId | null;cardLayout: KanbanCardLayoutMode;@@ -400,7 +420,7 @@ export interface IKanbanProjection extends IViewProjection {}export interface ICalendarProjection extends IViewProjection {- type: 'calendar';+ type: BaseViewType.Calendar;config: ICalendarViewConfig;events: Array<{recordId: RecordId;@@ -425,7 +445,7 @@ export interface IGanttTimeColumn {}export interface IGanttProjection extends IViewProjection {- type: 'gantt';+ type: BaseViewType.Gantt;config: IGanttViewConfig;dateRangeAllDay?: boolean;timeline: {@@ -454,7 +474,7 @@ export interface IGanttProjection extends IViewProjection {}export interface IGalleryProjection extends IViewProjection {- type: 'gallery';+ type: BaseViewType.Gallery;coverFieldId?: FieldId | null;cardLayout: KanbanCardLayoutMode;showFieldNames: boolean;@@ -469,7 +489,7 @@ export interface IGalleryProjection extends IViewProjection {export interface IInvalidViewProjection {type: 'invalid';- viewType: ViewType;+ viewType: BaseViewType;reason:| 'missingField'| 'invalidGroupField'@@ -487,14 +507,14 @@ export type BaseViewProjection =| IGalleryProjection| IInvalidViewProjection;-export interface IViewport {+export interface IBaseViewport {x: number;y: number;width: number;height: number;}-export interface IRect extends IViewport {}+export interface IBaseRect extends IBaseViewport {}export type BaseSelection =| IGridCellSelection@@ -751,46 +771,3 @@ export interface IBaseInvalidation {column?: number;reason: 'cell' | 'field' | 'record' | 'view' | 'table' | 'unknown';}--export type BaseCellData = IBaseCellData;-export type BaseResources = IBaseResources;-export type ViewFieldSetting = IViewFieldSetting;-export type FieldCapabilities = IFieldCapabilities;-export type ValidationResult = IValidationResult;-export type FilterConfig = IFilterConfig;-export type FilterCondition = IFilterCondition;-export type SortConfig = ISortConfig;-export type GroupConfig = IGroupConfig;-export type GridViewConfig = IGridViewConfig;-export type CardLayoutConfig = ICardLayoutConfig;-export type KanbanFieldCardSetting = IKanbanFieldCardSetting;-export type KanbanColumnSetting = IKanbanColumnSetting;-export type KanbanViewConfig = IKanbanViewConfig;-export type CalendarViewConfig = ICalendarViewConfig;-export type BaseViewColorCondition = IBaseViewColorCondition;-export type GanttViewConfig = IGanttViewConfig;-export type GalleryViewConfig = IGalleryViewConfig;-export type ProjectedField = IProjectedField;-export type ViewProjection = IViewProjection;-export type ProjectedRow = IProjectedRow;-export type ProjectedGroup = IProjectedGroup;-export type GridProjection = IGridProjection;-export type KanbanProjection = IKanbanProjection;-export type CalendarProjection = ICalendarProjection;-export type GanttTimeColumn = IGanttTimeColumn;-export type GanttProjection = IGanttProjection;-export type GalleryProjection = IGalleryProjection;-export type InvalidViewProjection = IInvalidViewProjection;-export type Viewport = IViewport;-export type Rect = IRect;-export type GridCellSelection = IGridCellSelection;-export type GridGroupSelection = IGridGroupSelection;-export type GridRecordSelection = IGridRecordSelection;-export type GridFieldSelection = IGridFieldSelection;-export type KanbanCardSelection = IKanbanCardSelection;-export type CalendarEventSelection = ICalendarEventSelection;-export type CalendarEventResizeSelection = ICalendarEventResizeSelection;-export type GanttCellSelection = IGanttCellSelection;-export type GanttBarSelection = IGanttBarSelection;-export type GalleryCardSelection = IGalleryCardSelection;-export type BaseInvalidation = IBaseInvalidation;