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): version 1 (#6979)

Univer4170c72ecc98
diff --git a/packages/core/src/base/__tests__/base-data-model.spec.ts b/packages/core/src/base/__tests__/base-data-model.spec.ts
new file mode 100644
index 0000000000..ae3bcddf6e
--- /dev/null
+++ b/packages/core/src/base/__tests__/base-data-model.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * 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 { IBaseSnapshot } from '../typedef';
+import { describe, expect, it } from 'vitest';
+import { BaseDataModel } from '../base-data-model';
+
+describe('BaseDataModel', () => {
+ 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 snapshot: Partial<IBaseSnapshot> = {
+ id: 'base-1',
+ name: 'Base',
+ tableOrder: ['table-1'],
+ tables: {
+ 'table-1': {
+ id: 'table-1',
+ name: 'Table',
+ fields: {
+ title: { id: 'title', name: 'Title', type: 'text', config: {} },
+ },
+ fieldOrder: ['title'],
+ primaryFieldId: 'title',
+ records: {
+ 'record-1': {
+ id: 'record-1',
+ orderKey: throwingOrderKey,
+ createdAt: 0,
+ updatedAt: 0,
+ values: { title: 'One' },
+ },
+ 'record-2': {
+ id: 'record-2',
+ orderKey: throwingOrderKey,
+ createdAt: 0,
+ updatedAt: 0,
+ values: { title: 'Two' },
+ },
+ },
+ recordOrder: ['record-2', 'record-1'],
+ viewOrder: [],
+ views: {},
+ },
+ },
+ };
+
+ const model = new BaseDataModel(snapshot);
+
+ expect(model.getSnapshot().tables['table-1'].recordOrder).toEqual(['record-2', 'record-1']);
+ });
+});
diff --git a/packages/core/src/base/base-data-model.ts b/packages/core/src/base/base-data-model.ts
new file mode 100644
index 0000000000..336eacfd0f
--- /dev/null
+++ b/packages/core/src/base/base-data-model.ts
@@ -0,0 +1,393 @@
+/**
+ * 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 { Observable } from 'rxjs';
+import type { CellValue, IBaseCellData, IBaseSnapshot, IFieldSnapshot, IRecordSnapshot, ITableSnapshot } from './typedef';
+import { BehaviorSubject } from 'rxjs';
+import { UnitModel, UniverInstanceType } from '../common/unit';
+import { Tools } from '../shared/tools';
+import { CellValueType } from '../types/enum';
+import { isBasePerformanceTracingEnabled, traceBasePerformance } from './base-performance';
+
+const BASE_LIST_VALUE_SEPARATOR = ', ';
+const BASE_ATTACHMENT_RESOURCE_KEY_SEPARATOR = '\u001F';
+type ICompressedBaseCellTuple = [number, number, IBaseCellData & { c?: 1 }];
+
+export class BaseDataModel extends UnitModel<IBaseSnapshot, UniverInstanceType.UNIVER_BASE> {
+ override readonly type: UniverInstanceType.UNIVER_BASE = UniverInstanceType.UNIVER_BASE;
+
+ private readonly _name$: BehaviorSubject<string>;
+ override readonly name$: Observable<string>;
+ private _snapshot: IBaseSnapshot;
+
+ constructor(snapshot: Partial<IBaseSnapshot> = {}) {
+ super();
+
+ const now = Date.now();
+ this._snapshot = traceBasePerformance('Core.BaseDataModel.normalizeSnapshot', () => normalizeBaseSnapshot(Tools.commonExtend({
+ id: '',
+ name: '',
+ schemaVersion: 1,
+ tables: {},
+ tableOrder: [],
+ createdAt: now,
+ updatedAt: now,
+ rev: 1,
+ } as IBaseSnapshot, snapshot)), {
+ tables: Object.keys(snapshot.tables ?? {}).length,
+ });
+
+ if (!this._snapshot.id) {
+ this._snapshot.id = `base-${Math.random().toString(36).slice(2, 10)}`;
+ }
+
+ this._name$ = new BehaviorSubject<string>(this._snapshot.name);
+ this.name$ = this._name$.asObservable();
+ }
+
+ override getUnitId(): string {
+ return this._snapshot.id;
+ }
+
+ override setName(name: string): void {
+ this._snapshot.name = name;
+ this._snapshot.updatedAt = Date.now();
+ this._name$.next(name);
+ }
+
+ override getSnapshot(): IBaseSnapshot {
+ return this._snapshot;
+ }
+
+ setSnapshot(snapshot: IBaseSnapshot): void {
+ this._snapshot = normalizeBaseSnapshot(snapshot);
+ this._name$.next(snapshot.name);
+ }
+
+ override getRev(): number {
+ return this._snapshot.rev ?? 1;
+ }
+
+ override incrementRev(): void {
+ this._snapshot.rev = this.getRev() + 1;
+ }
+
+ override setRev(rev: number): void {
+ this._snapshot.rev = rev;
+ }
+
+ override dispose(): void {
+ super.dispose();
+ this._name$.complete();
+ }
+}
+
+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) => {
+ if (!isBasePerformanceTracingEnabled()) {
+ normalizeBaseTable(table);
+ return;
+ }
+
+ traceBasePerformance('Core.BaseDataModel.normalizeTable', () => normalizeBaseTable(table), {
+ tableId: table.id,
+ records: Object.keys(table.records ?? {}).length,
+ fields: table.fieldOrder.length,
+ });
+ });
+ return snapshot;
+}
+
+function normalizeBaseTable(table: ITableSnapshot): void {
+ traceBasePerformance('Core.BaseDataModel.hydrateCompressedCellData', () => hydrateCompressedCellData(table), {
+ tableId: table.id,
+ });
+
+ const records = table.records ?? {};
+ const fields = table.fields ?? {};
+ const orderedRecordIds = traceBasePerformance('Core.BaseDataModel.getOrderedRecordIds', () => getOrderedRecordIds(table, records), {
+ tableId: table.id,
+ records: Object.keys(records).length,
+ hasRecordOrder: Boolean(table.recordOrder?.length),
+ });
+ const orderedFieldIds = traceBasePerformance('Core.BaseDataModel.getOrderedFieldIds', () => getOrderedFieldIds(table, fields), {
+ tableId: table.id,
+ fields: Object.keys(fields).length,
+ });
+
+ table.recordOrder = orderedRecordIds;
+ traceBasePerformance('Core.BaseDataModel.cloneMutableMaps', () => cloneBaseTableMutableMaps(table), {
+ tableId: table.id,
+ });
+ traceBasePerformance('Core.BaseDataModel.normalizeExistingCellData', () => normalizeExistingCellData(table, fields), {
+ tableId: table.id,
+ });
+ traceBasePerformance('Core.BaseDataModel.rebuildRowIndexes', () => rebuildRowIndexes(table, records, orderedRecordIds), {
+ tableId: table.id,
+ records: orderedRecordIds.length,
+ });
+ traceBasePerformance('Core.BaseDataModel.rebuildColumnIndexes', () => rebuildColumnIndexes(table, fields, orderedFieldIds), {
+ tableId: table.id,
+ fields: orderedFieldIds.length,
+ });
+ traceBasePerformance('Core.BaseDataModel.hydrateRecordCellData', () => hydrateRecordCellData(table, records, fields), {
+ tableId: table.id,
+ records: orderedRecordIds.length,
+ fields: orderedFieldIds.length,
+ });
+}
+
+function hydrateCompressedCellData(table: ITableSnapshot): void {
+ const compressedCellData = (table as ITableSnapshot & { cd?: ICompressedBaseCellTuple[] }).cd;
+ if (compressedCellData && !table.cellData) {
+ table.cellData = Object.create(null) as ITableSnapshot['cellData'];
+ compressedCellData.forEach(([row, col, cell]) => {
+ table.cellData![row] = table.cellData![row] ?? {};
+ const { c: _compressed, ...cellData } = cell;
+ table.cellData![row][col] = cellData;
+ });
+ delete (table as ITableSnapshot & { cd?: unknown }).cd;
+ }
+}
+
+function getOrderedRecordIds(table: ITableSnapshot, records: Record<string, IRecordSnapshot>): string[] {
+ const orderedRecordIds = table.recordOrder?.filter((recordId) => records[recordId]) ?? [];
+ const orderedRecordIdSet = new Set(orderedRecordIds);
+ const missingRecords = Object.values(records).filter((record) => !orderedRecordIdSet.has(record.id));
+ if (!missingRecords.length) {
+ return orderedRecordIds;
+ }
+
+ return [
+ ...orderedRecordIds,
+ ...missingRecords.sort((a, b) => a.orderKey.localeCompare(b.orderKey)).map((record) => record.id),
+ ];
+}
+
+function getOrderedFieldIds(table: ITableSnapshot, fields: Record<string, IFieldSnapshot>): string[] {
+ return table.fieldOrder.filter((fieldId) => fields[fieldId]);
+}
+
+function cloneBaseTableMutableMaps(table: ITableSnapshot): void {
+ table.rowIndex = { ...table.rowIndex };
+ table.rowId = { ...table.rowId };
+ table.colIndex = { ...table.colIndex };
+ table.colId = { ...table.colId };
+ table.cellData = { ...table.cellData };
+ table.resources = { ...table.resources };
+ table.resources.attachmentSets = { ...table.resources.attachmentSets };
+ table.resources.attachments = { ...table.resources.attachments };
+}
+
+function normalizeExistingCellData(table: ITableSnapshot, fields: Record<string, IFieldSnapshot>): void {
+ Object.entries(table.cellData ?? {}).forEach(([rowKey, rowData]) => {
+ const row = Number(rowKey);
+ table.cellData![row] = { ...rowData };
+ Object.entries(table.cellData![row] ?? {}).forEach(([colKey, cell]) => {
+ const col = Number(colKey);
+ const fieldId = table.colId?.[col];
+ table.cellData![row][col] = normalizeBaseCellData(cell, fieldId ? fields[fieldId] : undefined);
+ });
+ });
+}
+
+function rebuildRowIndexes(table: ITableSnapshot, records: Record<string, IRecordSnapshot>, orderedRecordIds: string[]): void {
+ orderedRecordIds.forEach((recordId, index) => {
+ if (table.rowIndex![recordId] == null) {
+ table.rowIndex![recordId] = index;
+ }
+ });
+ Object.entries(table.rowIndex ?? {}).forEach(([recordId, row]) => {
+ if (records[recordId]) {
+ table.rowId![row] = recordId;
+ }
+ });
+}
+
+function rebuildColumnIndexes(table: ITableSnapshot, fields: Record<string, IFieldSnapshot>, orderedFieldIds: string[]): void {
+ orderedFieldIds.forEach((fieldId, index) => {
+ if (table.colIndex![fieldId] == null) {
+ table.colIndex![fieldId] = index;
+ }
+ });
+ Object.entries(table.colIndex ?? {}).forEach(([fieldId, col]) => {
+ if (fields[fieldId]) {
+ table.colId![col] = fieldId;
+ }
+ });
+}
+
+function hydrateRecordCellData(table: ITableSnapshot, records: Record<string, IRecordSnapshot>, fields: Record<string, IFieldSnapshot>): void {
+ Object.values(records).forEach((record) => {
+ const row = table.rowIndex![record.id];
+ if (row == null) {
+ return;
+ }
+ table.cellData![row] = { ...table.cellData![row] };
+ Object.entries(record.values ?? {}).forEach(([fieldId, value]) => {
+ const field = fields[fieldId];
+ if (field?.type === 'attachment') {
+ writeAttachmentResources(table, record.id, fieldId, value);
+ }
+ const col = table.colIndex![fieldId];
+ if (col == null) {
+ return;
+ }
+ const existingCell = table.cellData![row][col];
+ if (existingCell != null) {
+ table.cellData![row][col] = normalizeBaseCellData(existingCell, field);
+ if (shouldRefreshCellDataFromRecord(existingCell, field, value)) {
+ table.cellData![row][col] = toBaseCellData(value, field);
+ }
+ return;
+ }
+ table.cellData![row][col] = toBaseCellData(value, field);
+ });
+ });
+}
+
+function toBaseCellData(value: CellValue | IBaseCellData, field?: IFieldSnapshot): IBaseCellData {
+ if (isBaseCellData(value)) {
+ if (field?.type === 'attachment') {
+ return { ...value, v: '', t: CellValueType.STRING };
+ }
+ return normalizeBaseCellData(value, field);
+ }
+ if (field?.type === '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)) {
+ const link = value as { text?: unknown; url?: unknown };
+ return { v: String(link.text ?? link.url ?? ''), t: CellValueType.STRING };
+ }
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return { v: value, t: inferPrimitiveType(value) };
+ }
+
+ return { v: null, t: null };
+}
+
+function normalizeBaseCellData(cell: IBaseCellData, _field?: IFieldSnapshot): IBaseCellData {
+ const type = normalizeBaseCellValueType(cell.t, cell.v);
+ if (type === undefined) {
+ const { t: _t, ...rest } = cell;
+ return rest;
+ }
+ return { ...cell, t: type };
+}
+
+function isBaseCellData(value: unknown): value is IBaseCellData {
+ return !!value && typeof value === 'object' && (
+ Object.prototype.hasOwnProperty.call(value, 'v')
+ || Object.prototype.hasOwnProperty.call(value, 't')
+ || Object.prototype.hasOwnProperty.call(value, 'p')
+ || Object.prototype.hasOwnProperty.call(value, 'f')
+ || Object.prototype.hasOwnProperty.call(value, 'si')
+ );
+}
+
+function writeAttachmentResources(table: ITableSnapshot, recordId: string, fieldId: string, value: unknown): void {
+ const attachments = normalizeAttachmentValue(value);
+ table.resources = { ...table.resources };
+ table.resources.attachmentSets = { ...table.resources.attachmentSets };
+ table.resources.attachments = { ...table.resources.attachments };
+ const key = `${fieldId}${BASE_ATTACHMENT_RESOURCE_KEY_SEPARATOR}${recordId}`;
+ table.resources.attachmentSets[key] = attachments.map((attachment, index) => {
+ const id = String(attachment.id ?? `${key}${BASE_ATTACHMENT_RESOURCE_KEY_SEPARATOR}${index}`);
+ const normalizedAttachment = { ...attachment, id };
+ table.resources!.attachments![id] = normalizedAttachment;
+ return id;
+ });
+}
+
+function normalizeAttachmentValue(value: unknown): Record<string, unknown>[] {
+ if (value == null || value === '') {
+ return [];
+ }
+ if (isBaseCellData(value) && !('id' in value) && !('name' in value)) {
+ return [];
+ }
+ const values = Array.isArray(value) ? value : [value];
+ return values.map((item, index) => {
+ if (item && typeof item === 'object') {
+ return { ...(item as Record<string, unknown>) };
+ }
+ return { id: `attachment-${index}`, name: String(item) };
+ }).filter((attachment) => Object.keys(attachment).length > 0);
+}
+
+function shouldRefreshCellDataFromRecord(cell: IBaseCellData, field: IFieldSnapshot | undefined, value: unknown): boolean {
+ if (field?.type === 'attachment') {
+ return cell.v !== '';
+ }
+ if (isListField(field)) {
+ return Array.isArray(value) && (cell.v == null || cell.v === '');
+ }
+ return false;
+}
+
+function isListField(field?: IFieldSnapshot): field is IFieldSnapshot & { type: 'multiSelect' | 'person' | 'group' } {
+ return field?.type === 'multiSelect' || field?.type === 'person' || field?.type === 'group';
+}
+
+function normalizeListValue(value: unknown): string[] {
+ if (value == null || value === '') {
+ return [];
+ }
+ if (Array.isArray(value)) {
+ return value.map((item) => primitiveText(item)).filter(Boolean);
+ }
+ return String(value).split(',').map((item) => item.trim()).filter(Boolean);
+}
+
+function primitiveText(value: unknown): string {
+ if (value == null) {
+ return '';
+ }
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return String(value);
+ }
+ if (typeof value === 'object') {
+ const record = value as Record<string, unknown>;
+ return String(record.id ?? record.name ?? record.text ?? '');
+ }
+ return String(value);
+}
+
+function inferPrimitiveType(value: CellValue): CellValueType | null {
+ if (value == null) {
+ return null;
+ }
+ if (typeof value === 'number') {
+ return CellValueType.NUMBER;
+ }
+ if (typeof value === 'boolean') {
+ return CellValueType.BOOLEAN;
+ }
+ return CellValueType.STRING;
+}
+
+function normalizeBaseCellValueType(type: IBaseCellData['t'], value: IBaseCellData['v']): CellValueType | null | undefined {
+ if (type === CellValueType.STRING || type === CellValueType.NUMBER || type === CellValueType.BOOLEAN || type === CellValueType.FORCE_STRING || type == null) {
+ return type;
+ }
+ return inferPrimitiveType(value ?? null);
+}
diff --git a/packages/core/src/base/base-performance.ts b/packages/core/src/base/base-performance.ts
new file mode 100644
index 0000000000..a5cb0f14da
--- /dev/null
+++ b/packages/core/src/base/base-performance.ts
@@ -0,0 +1,104 @@
+/**
+ * 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.
+ */
+
+export type BasePerformanceDetails = Record<string, unknown>;
+
+interface IBasePerformanceGlobal {
+ __UNIVER_BASE_PERF__?: boolean;
+}
+
+let measurementIndex = 0;
+
+export function isBasePerformanceTracingEnabled(): boolean {
+ const globalObject = globalThis as typeof globalThis & IBasePerformanceGlobal;
+ if (globalObject.__UNIVER_BASE_PERF__ === true) {
+ return true;
+ }
+
+ try {
+ const locationSearch = typeof location === 'undefined' ? '' : location.search;
+ const searchParams = new URLSearchParams(locationSearch);
+ if (searchParams.get('basePerf') === '1' || searchParams.get('basePerf') === 'true' || searchParams.get('base-perf') === '1') {
+ return true;
+ }
+ } catch {
+ // Ignore URL parsing failures in non-browser runtimes.
+ }
+
+ try {
+ const value = typeof localStorage === 'undefined' ? null : localStorage.getItem('univer.basePerf');
+ return value === '1' || value === 'true';
+ } catch {
+ return false;
+ }
+}
+
+export function traceBasePerformance<T>(label: string, fn: () => T, details?: BasePerformanceDetails): T {
+ if (!isBasePerformanceTracingEnabled()) {
+ return fn();
+ }
+
+ const start = now();
+ const markId = `base-core-perf-${measurementIndex++}`;
+ mark(`${markId}:start`);
+ try {
+ return fn();
+ } finally {
+ const duration = now() - start;
+ mark(`${markId}:end`);
+ measure(label, `${markId}:start`, `${markId}:end`);
+ logBasePerformance(label, duration, details);
+ }
+}
+
+export function logBasePerformance(label: string, duration: number, details?: BasePerformanceDetails): void {
+ if (!isBasePerformanceTracingEnabled()) {
+ return;
+ }
+
+ const roundedDuration = Math.round(duration * 100) / 100;
+ const payload = details && Object.keys(details).length
+ ? ` ${JSON.stringify(details)}`
+ : '';
+ // eslint-disable-next-line no-console
+ console.info(`[BasePerf] ${label}: ${roundedDuration}ms${payload}`);
+}
+
+function now(): number {
+ return typeof performance !== 'undefined' && typeof performance.now === 'function'
+ ? performance.now()
+ : Date.now();
+}
+
+function mark(name: string): void {
+ try {
+ if (typeof performance !== 'undefined') {
+ performance.mark?.(name);
+ }
+ } catch {
+ // Ignore unsupported performance APIs.
+ }
+}
+
+function measure(name: string, start: string, end: string): void {
+ try {
+ if (typeof performance !== 'undefined') {
+ performance.measure?.(`[BasePerf] ${name}`, start, end);
+ }
+ } catch {
+ // Ignore unsupported performance APIs.
+ }
+}
diff --git a/packages/core/src/base/index.ts b/packages/core/src/base/index.ts
new file mode 100644
index 0000000000..4320d663e2
--- /dev/null
+++ b/packages/core/src/base/index.ts
@@ -0,0 +1,132 @@
+/**
+ * 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.
+ */
+
+export { BaseDataModel } from './base-data-model';
+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,
+ IBaseResources,
+ IBaseSnapshot,
+ IBaseViewColorCondition,
+ ICalendarEventResizeSelection,
+ ICalendarEventSelection,
+ ICalendarProjection,
+ ICalendarViewConfig,
+ ICardLayoutConfig,
+ IFieldCapabilities,
+ IFieldSnapshot,
+ IFilterCondition,
+ IFilterConfig,
+ IGalleryCardSelection,
+ IGalleryProjection,
+ IGalleryViewConfig,
+ IGanttBarSelection,
+ IGanttCellSelection,
+ IGanttProjection,
+ IGanttTimeColumn,
+ IGanttViewConfig,
+ IGridCellSelection,
+ IGridFieldSelection,
+ IGridGroupSelection,
+ IGridProjection,
+ IGridRecordSelection,
+ IGridViewConfig,
+ IGroupConfig,
+ IInvalidViewProjection,
+ IKanbanCardSelection,
+ IKanbanColumnSetting,
+ 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/base/typedef.ts b/packages/core/src/base/typedef.ts
new file mode 100644
index 0000000000..a33b13ba52
--- /dev/null
+++ b/packages/core/src/base/typedef.ts
@@ -0,0 +1,794 @@
+/**
+ * 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 { CellValueType } from '../types/enum';
+import type { IDocumentData } from '../types/interfaces';
+
+export type BaseId = string;
+export type TableId = string;
+export type FieldId = string;
+export type RecordId = string;
+export type ViewId = string;
+
+export type PrimitiveCellValue = string | number | boolean;
+export type CellValue =
+ | PrimitiveCellValue
+ | PrimitiveCellValue[]
+ | Record<string, unknown>
+ | Record<string, unknown>[]
+ | null;
+
+export type BaseCellPrimitiveValue = string | number | boolean | null;
+export type BaseCellValueType = CellValueType;
+
+export interface IBaseCellData {
+ v?: BaseCellPrimitiveValue;
+ t?: BaseCellValueType | null;
+ p?: IDocumentData | null;
+ f?: string | null;
+ si?: string | null;
+}
+
+export type BaseCellMatrix = Record<number, Record<number, IBaseCellData>>;
+
+export interface IBaseResources {
+ multiValueSets?: Record<string, string[]>;
+ memberSets?: Record<string, string[]>;
+ attachmentSets?: Record<string, string[]>;
+ 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 type FieldConfig = Record<string, unknown>;
+export type ViewSpecificConfig =
+ | IGridViewConfig
+ | IKanbanViewConfig
+ | ICalendarViewConfig
+ | IGanttViewConfig
+ | IGalleryViewConfig
+ | Record<string, unknown>;
+
+export interface IBaseSnapshot {
+ id: BaseId;
+ name: string;
+ schemaVersion: number;
+ tables: Record<TableId, ITableSnapshot>;
+ tableOrder: TableId[];
+ createdAt: number;
+ updatedAt: number;
+ createdBy?: string;
+ rev?: number;
+}
+
+export interface ITableSnapshot {
+ id: TableId;
+ name: string;
+ fields: Record<FieldId, IFieldSnapshot>;
+ fieldOrder: FieldId[];
+ records: Record<RecordId, IRecordSnapshot>;
+ recordOrder?: RecordId[];
+ rowIndex?: Record<RecordId, number>;
+ rowId?: Record<number, RecordId>;
+ colIndex?: Record<FieldId, number>;
+ colId?: Record<number, FieldId>;
+ cellData?: BaseCellMatrix;
+ resources?: IBaseResources;
+ views: Record<ViewId, IViewSnapshot>;
+ viewOrder: ViewId[];
+ primaryFieldId: FieldId;
+ deleted?: boolean;
+}
+
+export interface IRecordSnapshot {
+ id: RecordId;
+ values: Record<FieldId, CellValue>;
+ orderKey: string;
+ createdAt: number;
+ updatedAt: number;
+ createdBy?: string;
+ updatedBy?: string;
+ deleted?: boolean;
+}
+
+export interface IFieldSnapshot {
+ id: FieldId;
+ name: string;
+ description?: string;
+ type: FieldType;
+ config: FieldConfig;
+ defaultValue?: CellValue;
+ system?: boolean;
+ readonly?: boolean;
+ deleted?: boolean;
+}
+
+export interface IViewSnapshot<TConfig extends ViewSpecificConfig = ViewSpecificConfig> {
+ id: ViewId;
+ tableId: TableId;
+ name: string;
+ type: ViewType;
+ fieldOrder?: FieldId[];
+ fieldSettings?: Record<FieldId, IViewFieldSetting>;
+ filter?: IFilterConfig | null;
+ sort?: ISortConfig[];
+ group?: IGroupConfig[];
+ config: TConfig;
+ deleted?: boolean;
+}
+
+export type BaseSnapshot = IBaseSnapshot;
+export type TableSnapshot = ITableSnapshot;
+export type RecordSnapshot = IRecordSnapshot;
+export type FieldSnapshot = IFieldSnapshot;
+export type ViewSnapshot<TConfig extends ViewSpecificConfig = ViewSpecificConfig> = IViewSnapshot<TConfig>;
+
+export interface IViewFieldSetting {
+ hidden?: boolean;
+ width?: number;
+ showInCard?: boolean;
+}
+
+export interface IFieldCapabilities {
+ editable: boolean;
+ sortable: boolean;
+ filterable: boolean;
+ groupable: boolean;
+ usableAsKanbanGroup: boolean;
+ usableAsCalendarDate: boolean;
+ usableAsGanttStart: boolean;
+ usableAsGanttEnd: boolean;
+ usableAsGanttProgress: boolean;
+ usableAsCardCover: boolean;
+ usableAsTitle: boolean;
+ supportsMultipleValues?: boolean;
+ supportsOptions?: boolean;
+ supportsRelation?: boolean;
+}
+
+export interface IValidationResult {
+ valid: boolean;
+ reason?: string;
+}
+
+export type FilterOperator =
+ | 'is'
+ | 'isNot'
+ | 'contains'
+ | 'notContains'
+ | 'isEmpty'
+ | 'isNotEmpty'
+ | 'greaterThan'
+ | 'greaterThanOrEqual'
+ | 'lessThan'
+ | 'lessThanOrEqual';
+
+export interface IFilterConfig {
+ conjunction: 'and' | 'or';
+ conditions: IFilterCondition[];
+}
+
+export interface IFilterCondition {
+ fieldId: FieldId;
+ operator: string;
+ operand?: unknown;
+}
+
+export interface ISortConfig {
+ fieldId: FieldId;
+ direction: 'asc' | 'desc';
+}
+
+export interface IGroupConfig {
+ fieldId: FieldId;
+ direction?: 'asc' | 'desc';
+ hideEmptyGroup?: boolean;
+}
+
+export interface IGridViewConfig {
+ frozenFieldCount?: number;
+ showRecordIndex?: boolean;
+ rowHeight?: 'short' | 'medium' | 'tall' | 'extraTall';
+}
+
+export interface ICardLayoutConfig {
+ titleFieldId?: FieldId;
+ coverFieldId?: FieldId | null;
+ fieldIds: FieldId[];
+}
+
+export type KanbanCardLayoutMode = 'normal' | 'compose';
+
+export interface IKanbanFieldCardSetting {
+ hidden?: boolean;
+ order?: number;
+}
+
+export interface IKanbanColumnSetting {
+ title?: string;
+ color?: string;
+ collapsed?: boolean;
+}
+
+export interface IKanbanViewConfig {
+ groupFieldId: FieldId;
+ coverFieldId?: FieldId | null;
+ cardLayout?: KanbanCardLayoutMode;
+ showFieldNames?: boolean;
+ fieldSettings?: Record<FieldId, IKanbanFieldCardSetting>;
+ columnSettings?: Record<string, IKanbanColumnSetting>;
+ card?: ICardLayoutConfig;
+}
+
+export interface ICalendarViewConfig {
+ startDateFieldId: FieldId;
+ endDateFieldId?: FieldId;
+ titleFieldId?: FieldId;
+ colorFieldId?: FieldId;
+ mode: 'month' | 'week' | 'day';
+ timeslotSize?: 'short' | 'medium' | 'long';
+ timeZone?: 'local' | string;
+ displayColor?: { type: 'custom'; color: string } | { type: 'selectField'; fieldId: FieldId };
+ fieldSettings?: Record<FieldId, { hidden?: boolean; order?: number }>;
+}
+
+export interface IBaseViewColorCondition {
+ id: string;
+ color: string;
+ target?: 'cell' | 'row' | 'column';
+ fieldId: FieldId;
+ operator:
+ | 'is'
+ | 'isNot'
+ | 'contains'
+ | 'notContains'
+ | 'isEmpty'
+ | 'isNotEmpty'
+ | 'greaterThan'
+ | 'lessThan'
+ | 'before'
+ | 'after';
+ operand?: unknown;
+ dateMode?:
+ | 'exact'
+ | 'today'
+ | 'tomorrow'
+ | 'yesterday'
+ | 'thisWeek'
+ | 'lastWeek'
+ | 'thisMonth'
+ | 'lastMonth'
+ | 'past7'
+ | 'next7'
+ | 'past30'
+ | 'next30';
+}
+
+export interface IGanttViewConfig {
+ startDateFieldId: FieldId;
+ endDateFieldId: FieldId;
+ titleFieldId?: FieldId;
+ progressFieldId?: FieldId;
+ dependencyFieldId?: FieldId;
+ scale: 'week' | 'month' | 'quarter' | 'year';
+ leftPaneWidth?: number;
+ leftPaneCollapsed?: boolean;
+ showTodayLine?: boolean;
+ showWeekend?: boolean;
+ displayColor?:
+ | { type: 'custom'; color: string }
+ | { type: 'selectField'; fieldId: FieldId }
+ | { type: 'conditional'; rules: IBaseViewColorCondition[] };
+ fieldSettings?: Record<FieldId, { hidden?: boolean; order?: number }>;
+ workingDaysOnly?: boolean;
+ workingDays?: {
+ weekdays: Array<1 | 2 | 3 | 4 | 5 | 6 | 7>;
+ exceptions: Array<{
+ id: string;
+ date: number;
+ name: string;
+ type: 'off' | 'working';
+ }>;
+ };
+}
+
+export interface IGalleryViewConfig {
+ card: ICardLayoutConfig;
+ coverFieldId?: FieldId | null;
+ cardLayout?: KanbanCardLayoutMode;
+ showFieldNames?: boolean;
+ fieldSettings?: Record<FieldId, IKanbanFieldCardSetting>;
+ cardSize?: 'small' | 'medium' | 'large';
+}
+
+export interface IProjectedField {
+ id: FieldId;
+ name: string;
+ description?: string;
+ type: FieldType;
+ config?: FieldConfig;
+ width?: number;
+ setting: IViewFieldSetting;
+}
+
+export interface IViewProjection {
+ type: ViewType;
+ fields: IProjectedField[];
+ rows: IProjectedRow[];
+ groups?: IProjectedGroup[];
+}
+
+export interface IProjectedRow {
+ recordId: RecordId;
+ values: Record<FieldId, CellValue>;
+}
+
+export interface IProjectedGroup {
+ key: string;
+ path?: string;
+ label: string;
+ recordIds: RecordId[];
+ fieldId?: FieldId;
+ level?: number;
+ children?: IProjectedGroup[];
+}
+
+export interface IGridProjection extends IViewProjection {
+ type: 'grid';
+ frozenFieldCount?: number;
+}
+
+export interface IKanbanProjection extends IViewProjection {
+ type: 'kanban';
+ groupFieldId: FieldId;
+ coverFieldId?: FieldId | null;
+ cardLayout: KanbanCardLayoutMode;
+ showFieldNames: boolean;
+ visibleCardFieldIds: FieldId[];
+ lanes: Array<{
+ key: string;
+ title: string;
+ color?: string;
+ recordIds: RecordId[];
+ }>;
+}
+
+export interface ICalendarProjection extends IViewProjection {
+ type: 'calendar';
+ config: ICalendarViewConfig;
+ events: Array<{
+ recordId: RecordId;
+ title: string;
+ start: number;
+ end?: number;
+ color?: string;
+ startMs: number;
+ endMs?: number;
+ allDay: boolean;
+ fieldValues: Record<FieldId, CellValue>;
+ }>;
+}
+
+export interface IGanttTimeColumn {
+ id: string;
+ label: string;
+ majorLabel?: string;
+ start: number;
+ end: number;
+ nonWorking?: boolean;
+}
+
+export interface IGanttProjection extends IViewProjection {
+ type: 'gantt';
+ config: IGanttViewConfig;
+ dateRangeAllDay?: boolean;
+ timeline: {
+ scale: 'week' | 'month' | 'quarter' | 'year';
+ start: number;
+ end: number;
+ unitWidth: number;
+ majorHeaders: Array<{
+ id: string;
+ label: string;
+ start: number;
+ end: number;
+ }>;
+ columns: IGanttTimeColumn[];
+ };
+ bars: Array<{
+ recordId: RecordId;
+ title: string;
+ start: number;
+ end: number;
+ color: string;
+ progress?: number;
+ workingDayCount?: number;
+ dependencyRecordIds?: RecordId[];
+ }>;
+}
+
+export interface IGalleryProjection extends IViewProjection {
+ type: 'gallery';
+ coverFieldId?: FieldId | null;
+ cardLayout: KanbanCardLayoutMode;
+ showFieldNames: boolean;
+ visibleCardFieldIds: FieldId[];
+ cardSize: 'small' | 'medium' | 'large';
+ cards: Array<{
+ recordId: RecordId;
+ title: string;
+ values: Record<FieldId, CellValue>;
+ }>;
+}
+
+export interface IInvalidViewProjection {
+ type: 'invalid';
+ viewType: ViewType;
+ reason:
+ | 'missingField'
+ | 'invalidGroupField'
+ | 'invalidDateField'
+ | 'invalidGanttStartField'
+ | 'invalidGanttEndField';
+ fieldId?: FieldId;
+}
+
+export type BaseViewProjection =
+ | IGridProjection
+ | IKanbanProjection
+ | ICalendarProjection
+ | IGanttProjection
+ | IGalleryProjection
+ | IInvalidViewProjection;
+
+export interface IViewport {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface IRect extends IViewport {}
+
+export type BaseSelection =
+ | IGridCellSelection
+ | IGridGroupSelection
+ | IGridRecordSelection
+ | IGridFieldSelection
+ | IKanbanCardSelection
+ | ICalendarEventSelection
+ | IGanttCellSelection
+ | IGanttBarSelection
+ | IGalleryCardSelection;
+
+export interface IGridCellSelection {
+ type: 'grid-cell';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ fieldId: FieldId;
+}
+
+export interface IGridGroupSelection {
+ type: 'grid-group';
+ tableId: TableId;
+ viewId: ViewId;
+ fieldId: FieldId;
+ groupKey: string;
+ groupPath: string;
+ level: number;
+ collapsed: boolean;
+}
+
+export interface IGridRecordSelection {
+ type: 'grid-record';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+}
+
+export interface IGridFieldSelection {
+ type: 'grid-field';
+ tableId: TableId;
+ viewId: ViewId;
+ fieldId: FieldId;
+}
+
+export interface IKanbanCardSelection {
+ type: 'kanban-card';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ groupKey?: string;
+}
+
+export interface ICalendarEventSelection {
+ type: 'calendar-event';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ allDay?: boolean;
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+}
+
+export interface ICalendarEventResizeSelection {
+ type: 'calendar-event-resize';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ edge: 'start' | 'end';
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+}
+
+export interface IGanttCellSelection {
+ type: 'gantt-cell';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ fieldId: FieldId;
+}
+
+export interface IGanttBarSelection {
+ type: 'gantt-bar';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+}
+
+export interface IGalleryCardSelection {
+ type: 'gallery-card';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+}
+
+export type BaseHitTestResult =
+ | { type: 'empty'; x: number; y: number }
+ | {
+ type: 'grid-fill-handle';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ fieldId: FieldId;
+ }
+ | {
+ type: 'grid-freeze-handle';
+ tableId: TableId;
+ viewId: ViewId;
+ frozenFieldCount: number;
+ x: number;
+ }
+ | {
+ type: 'grid-stat';
+ tableId: TableId;
+ viewId: ViewId;
+ fieldId: FieldId;
+ fieldIndex: number;
+ }
+ | {
+ type: 'grid-record-open';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ }
+ | {
+ type: 'kanban-add-record';
+ tableId: TableId;
+ viewId: ViewId;
+ groupFieldId: FieldId;
+ groupKey: string;
+ }
+ | {
+ type: 'kanban-add-group';
+ tableId: TableId;
+ viewId: ViewId;
+ groupFieldId: FieldId;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }
+ | {
+ type: 'kanban-column';
+ tableId: TableId;
+ viewId: ViewId;
+ groupFieldId: FieldId;
+ groupKey: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }
+ | {
+ type: 'kanban-column-title';
+ tableId: TableId;
+ viewId: ViewId;
+ groupFieldId: FieldId;
+ groupKey: string;
+ title: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }
+ | {
+ type: 'kanban-column-color';
+ tableId: TableId;
+ viewId: ViewId;
+ groupFieldId: FieldId;
+ groupKey: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }
+ | {
+ type: 'kanban-card-checkbox';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ fieldId: FieldId;
+ groupKey?: string;
+ }
+ | {
+ type: 'kanban-lane-scrollbar-edge' | 'kanban-lane-scrollbar-thumb';
+ tableId: TableId;
+ viewId: ViewId;
+ groupKey: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ trackY: number;
+ trackHeight: number;
+ thumbHeight: number;
+ maxScroll: number;
+ }
+ | {
+ type: 'calendar-mode-tab';
+ tableId: TableId;
+ viewId: ViewId;
+ mode: 'day' | 'week' | 'month';
+ }
+ | {
+ type: 'calendar-today';
+ tableId: TableId;
+ viewId: ViewId;
+ }
+ | {
+ type: 'calendar-navigate';
+ tableId: TableId;
+ viewId: ViewId;
+ direction: 'prev' | 'next';
+ }
+ | {
+ type: 'calendar-day-cell';
+ tableId: TableId;
+ viewId: ViewId;
+ dateMs: number;
+ }
+ | {
+ type: 'calendar-more-events';
+ tableId: TableId;
+ viewId: ViewId;
+ dateMs: number;
+ count: number;
+ }
+ | {
+ type: 'gantt-offscreen-record';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ direction: 'prev' | 'next';
+ }
+ | {
+ type: 'gantt-row';
+ tableId: TableId;
+ viewId: ViewId;
+ recordId: RecordId;
+ }
+ | ICalendarEventResizeSelection
+ | BaseSelection;
+
+export interface IBaseInvalidation {
+ tableId: TableId;
+ viewId?: ViewId;
+ recordId?: RecordId;
+ fieldId?: FieldId;
+ row?: number;
+ 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;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fea7ae7834..f15e9d7959 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -18,6 +18,7 @@ import { installShims } from './common/shims';
installShims();
+export * from './base';
export { dedupe, dedupeBy, groupBy, makeArray, remove, rotate } from './common/array';
export * from './common/async';
export { isBooleanString } from './common/boolean';
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index e2829124d5..cc12a64380 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -19,6 +19,7 @@ import type { IDisposable } from '../../common/di';
import type { UnitModel } from '../../common/unit';
import type { Nullable } from '../../shared';
import { BehaviorSubject, distinctUntilChanged, filter, map, Subject } from 'rxjs';
+import { traceBasePerformance } from '../../base/base-performance';
import { createIdentifier, Inject, Injector } from '../../common/di';
import { UniverInstanceType } from '../../common/unit';
import { DocumentDataModel } from '../../docs/data-model/document-data-model';
@@ -140,7 +141,9 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
}
createUnit<T, U extends UnitModel>(type: UniverInstanceType, data: T, options?: ICreateUnitOptions): U {
- const model = this._createHandler(type, data, this._ctorByType.get(type)!, options);
+ const model = traceBasePerformance('Core.InstanceService.createUnitHandler', () => this._createHandler(type, data, this._ctorByType.get(type)!, options), {
+ type,
+ });
return model as U;
}
@@ -192,25 +195,36 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
* @param unit The unit to be added.
*/
__addUnit(unit: UnitModel, options?: ICreateUnitOptions): void {
- this._logService.debug(`[UniverInstanceService]: Adding unit with id ${unit.getUnitId()}`);
- const type = unit.type;
+ traceBasePerformance('Core.InstanceService.__addUnit', () => {
+ this._logService.debug(`[UniverInstanceService]: Adding unit with id ${unit.getUnitId()}`);
+ const type = unit.type;
- if (!this._unitsByType.has(type)) {
- this._unitsByType.set(type, []);
- }
-
- const units = this._unitsByType.get(type)!;
- const newUnitId = unit.getUnitId();
- if (units.findIndex((u) => u.getUnitId() === newUnitId) !== -1) {
- throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);
- }
+ if (!this._unitsByType.has(type)) {
+ this._unitsByType.set(type, []);
+ }
- units.push(unit);
- this._unitAdded$.next({ unit, options });
+ const units = this._unitsByType.get(type)!;
+ const newUnitId = unit.getUnitId();
+ if (units.findIndex((u) => u.getUnitId() === newUnitId) !== -1) {
+ throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);
+ }
- if (options?.makeCurrent ?? true) {
- this.setCurrentUnitForType(unit.getUnitId());
- }
+ units.push(unit);
+ traceBasePerformance('Core.InstanceService.unitAdded.next', () => this._unitAdded$.next({ unit, options }), {
+ type,
+ unitId: unit.getUnitId(),
+ });
+
+ if (options?.makeCurrent ?? true) {
+ traceBasePerformance('Core.InstanceService.setCurrentUnitForType', () => this.setCurrentUnitForType(unit.getUnitId()), {
+ type,
+ unitId: unit.getUnitId(),
+ });
+ }
+ }, {
+ type: unit.type,
+ unitId: unit.getUnitId(),
+ });
}
private _unitDisposed$ = new Subject<UnitModel>();
diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.ts
index 497704430d..24686bffa2 100644
--- a/packages/core/src/univer.ts
+++ b/packages/core/src/univer.ts
@@ -22,6 +22,7 @@ import type { DependencyOverride } from './services/plugin/plugin-override';
import type { Plugin, PluginCtor } from './services/plugin/plugin.service';
import type { ILocales } from './shared';
import type { LocaleType } from './types/enum/locale-type';
+import { traceBasePerformance } from './base/base-performance';
import { Injector, touchDependencies } from './common/di';
import { UniverInstanceType } from './common/unit';
import { DocumentDataModel } from './docs/data-model/document-data-model';
@@ -167,7 +168,9 @@ export class Univer implements IDisposable {
}
createUnit<T, U extends UnitModel>(type: UniverInstanceType, data: Partial<T>): U {
- return this._univerInstanceService.createUnit(type, data);
+ return traceBasePerformance('Core.Univer.createUnit', () => this._univerInstanceService.createUnit(type, data), {
+ type,
+ });
}
private _init(injector: Injector): void {
@@ -180,7 +183,9 @@ export class Univer implements IDisposable {
(type: UniverInstanceType, data, ctor, options) => {
const isFirstTime = !this._startedTypes.has(type);
if (isFirstTime) {
- this._pluginService.startPluginsForType(type);
+ traceBasePerformance('Core.Univer.startPluginsForType', () => this._pluginService.startPluginsForType(type), {
+ type,
+ });
this._startedTypes.add(type);
}
@@ -189,11 +194,19 @@ export class Univer implements IDisposable {
throw new Error(`[Univer]: No constructor registered for unit type ${type}.`);
}
- const model = injector.createInstance(actualCtor, data);
- univerInstanceService.__addUnit(model, options);
+ const model = traceBasePerformance('Core.Univer.createModelInstance', () => injector.createInstance(actualCtor, data), {
+ type,
+ ctor: actualCtor.name,
+ });
+ traceBasePerformance('Core.Univer.addUnit', () => univerInstanceService.__addUnit(model, options), {
+ type,
+ unitId: model.getUnitId(),
+ });
if (isFirstTime) {
- this._tryProgressToReady();
+ traceBasePerformance('Core.Univer.tryProgressToReady', () => this._tryProgressToReady(), {
+ type,
+ });
}
return model;
diff --git a/packages/design/src/components/segmented/Segmented.tsx b/packages/design/src/components/segmented/Segmented.tsx
index 1d986b15ad..f3fc7693f6 100644
--- a/packages/design/src/components/segmented/Segmented.tsx
+++ b/packages/design/src/components/segmented/Segmented.tsx
@@ -62,7 +62,7 @@ export function Segmented<T extends ItemValue = ItemValue>({
const containerRect = containerRef.current.getBoundingClientRect();
const newRect = newItemElement.getBoundingClientRect();
- // Calculate position relative to container's padding
+ // Calculate position relative to container's padding
const newLeft = newRect.left - containerRect.left - 4; // Subtract padding-left (p-1 = 4px)
if (oldItemElement) {
diff --git a/packages/design/src/components/select/Select.tsx b/packages/design/src/components/select/Select.tsx
index f4252efab9..56fbfa92f2 100644
--- a/packages/design/src/components/select/Select.tsx
+++ b/packages/design/src/components/select/Select.tsx
@@ -146,7 +146,7 @@ export function Select(props: ISelectProps) {
return (
<DropdownMenu
- className="max-h univer-w-[--radix-popper-anchor-width] univer-min-w-36"
+ className="univer-max-h-80 univer-w-[--radix-popper-anchor-width] univer-min-w-36 univer-overflow-auto"
align="start"
open={open}
items={items}
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 62c9902a46..c81a83e267 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType, IRange, IRowData, IUnitRange, Nullable, Workbook } from '@univerjs/core';
+import type { BaseCellValue, BaseDataModel, IBaseCellData, IBaseSnapshot, ICellData, IFieldSnapshot, IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType, IRange, IRowData, ITableSnapshot, IUnitRange, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaRangeType,
IArrayFormulaUnitCellType,
@@ -30,7 +30,7 @@ import type {
IUnitStylesData,
} from '../basics/common';
import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';
-import { BooleanNumber, Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, CellValueType, Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Styles, UniverInstanceType } from '@univerjs/core';
import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';
import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';
@@ -164,10 +164,6 @@ export class FormulaDataModel extends Disposable {
getFormulaData(): IFormulaData {
const formulaData: IFormulaData = {};
const allSheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (allSheets.length === 0) {
- return formulaData;
- }
-
allSheets.forEach((workbook) => {
const unitId = workbook.getUnitId();
formulaData[unitId] = {};
@@ -181,6 +177,39 @@ export class FormulaDataModel extends Disposable {
});
});
+ const allBases = this._univerInstanceService.getAllUnitsForType<BaseDataModel>(UniverInstanceType.UNIVER_BASE);
+ allBases.forEach((base) => {
+ const snapshot = base.getSnapshot();
+ const unitId = base.getUnitId();
+ formulaData[unitId] = {};
+
+ Object.values(snapshot.tables).filter((table) => !table.deleted).forEach((table) => {
+ const tableFormulaData: Record<number, Record<number, IFormulaDataItem>> = {};
+ table.recordOrder?.forEach((recordId, row) => {
+ const record = table.records[recordId];
+ if (!record || record.deleted) {
+ return;
+ }
+ table.fieldOrder.forEach((fieldId, col) => {
+ const field = table.fields[fieldId];
+ if (!field || field.deleted || field.type !== 'formula') {
+ return;
+ }
+ const formula = String(field.config?.formula ?? '').trim();
+ if (!formula) {
+ return;
+ }
+ tableFormulaData[row] ??= {};
+ tableFormulaData[row][col] = {
+ f: normalizeBaseFormulaForEngine(formula, table, snapshot),
+ si: field.id,
+ };
+ });
+ });
+ formulaData[unitId]![table.id] = tableFormulaData;
+ });
+ });
+
return formulaData;
}
@@ -344,6 +373,29 @@ export class FormulaDataModel extends Disposable {
unitSheetNameMap[unitId] = sheetNameMap;
}
+ const unitAllBases = this._univerInstanceService.getAllUnitsForType<BaseDataModel>(UniverInstanceType.UNIVER_BASE);
+ for (const base of unitAllBases) {
+ const snapshot = base.getSnapshot();
+ const unitId = base.getUnitId();
+ const baseData: ISheetData = {};
+ const tableNameMap: { [tableName: string]: string } = {};
+
+ for (const table of Object.values(snapshot.tables).filter((item) => !item.deleted)) {
+ baseData[table.id] = {
+ cellData: new ObjectMatrix(buildBaseRuntimeCellData(table)) as unknown as ObjectMatrix<ICellData>,
+ rowCount: table.recordOrder?.filter((recordId) => !table.records[recordId]?.deleted).length ?? 0,
+ columnCount: table.fieldOrder.filter((fieldId) => !table.fields[fieldId]?.deleted).length,
+ rowData: {},
+ columnData: {},
+ };
+ tableNameMap[table.name] = table.id;
+ }
+
+ allUnitData[unitId] = baseData;
+ unitStylesData[unitId] = new Styles();
+ unitSheetNameMap[unitId] = tableNameMap;
+ }
+
return {
allUnitData,
unitStylesData,
@@ -762,3 +814,117 @@ export function initSheetFormulaData(
},
};
}
+
+const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;
+const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;
+const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;
+
+function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnapshot, snapshot: IBaseSnapshot): string {
+ const refs: string[] = [];
+ const hold = (ref: string) => {
+ const index = refs.push(ref) - 1;
+ return `__BASE_FORMULA_REF_${index}__`;
+ };
+ const normalized = formula
+ .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}]`;
+ })
+ .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)] ?? '');
+}
+
+function createEngineThisRowRef(table: ITableSnapshot, fieldName: string, snapshot: IBaseSnapshot): string {
+ return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
+}
+
+function getEngineBaseTableName(table: ITableSnapshot, snapshot: IBaseSnapshot): string {
+ const sameNameCount = Object.values(snapshot.tables).filter((item) => !item.deleted && item.name === table.name).length;
+ return sameNameCount === 1 ? table.name : table.id;
+}
+
+function buildBaseRuntimeCellData(table: ITableSnapshot): Record<number, Record<number, IBaseCellData>> {
+ const cellData: Record<number, Record<number, IBaseCellData>> = { ...table.cellData };
+ const fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] && !table.fields[fieldId].deleted);
+ const recordOrder = table.recordOrder?.filter((recordId) => table.records[recordId] && !table.records[recordId].deleted)
+ ?? Object.values(table.records ?? {}).filter((record) => !record.deleted).sort((a, b) => a.orderKey.localeCompare(b.orderKey)).map((record) => record.id);
+
+ recordOrder.forEach((recordId, row) => {
+ const record = table.records[recordId];
+ if (!record || record.deleted) {
+ return;
+ }
+ cellData[row] = { ...cellData[row] };
+ fieldOrder.forEach((fieldId, col) => {
+ if (!Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId)) {
+ return;
+ }
+ cellData[row][col] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]);
+ });
+ });
+
+ return cellData;
+}
+
+function toBaseRuntimeCellData(value: BaseCellValue | IBaseCellData, field?: IFieldSnapshot): IBaseCellData {
+ if (isBaseCellData(value)) {
+ return normalizeBaseCellData(value);
+ }
+ if (field?.type === 'attachment') {
+ return { v: '', t: CellValueType.STRING };
+ }
+ if (Array.isArray(value)) {
+ return { v: value.join(', '), t: CellValueType.STRING };
+ }
+ if (field?.type === 'link' && value && typeof value === 'object') {
+ const link = value as { text?: unknown; url?: unknown };
+ return { v: String(link.text ?? link.url ?? ''), t: CellValueType.STRING };
+ }
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return { v: value, t: inferBaseRuntimeCellType(value) };
+ }
+ return { v: null, t: null };
+}
+
+function normalizeBaseCellData(cell: IBaseCellData): IBaseCellData {
+ const type = inferBaseRuntimeCellType(cell.v ?? null);
+ return { ...cell, t: type };
+}
+
+function inferBaseRuntimeCellType(value: IBaseCellData['v']): CellValueType | null {
+ if (typeof value === 'number') {
+ return CellValueType.NUMBER;
+ }
+ if (typeof value === 'boolean') {
+ return CellValueType.BOOLEAN;
+ }
+ if (typeof value === 'string') {
+ return CellValueType.STRING;
+ }
+ return null;
+}
+
+function isBaseCellData(value: unknown): value is IBaseCellData {
+ return !!value && typeof value === 'object' && (
+ Object.prototype.hasOwnProperty.call(value, 'v')
+ || Object.prototype.hasOwnProperty.call(value, 't')
+ || Object.prototype.hasOwnProperty.call(value, 'p')
+ || Object.prototype.hasOwnProperty.call(value, 'f')
+ || Object.prototype.hasOwnProperty.call(value, 'si')
+ );
+}
+
+function resolveBaseFormulaTable(tableName: string | undefined, currentTable: ITableSnapshot, snapshot: IBaseSnapshot): ITableSnapshot | undefined {
+ if (!tableName || tableName === 'table' || tableName === currentTable.id || tableName === currentTable.name) {
+ return currentTable;
+ }
+
+ const byId = snapshot.tables[tableName];
+ if (byId && !byId.deleted) {
+ return byId;
+ }
+
+ const matches = Object.values(snapshot.tables).filter((table) => !table.deleted && table.name === tableName);
+ return matches.length === 1 ? matches[0] : undefined;
+}
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 1f756167df..277cda3f50 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IUnitRange, LocaleType, Nullable, Workbook } from '@univerjs/core';
+import type { BaseDataModel, ITableSnapshot, IUnitRange, LocaleType, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaRangeType,
IDirtyUnitDefinedNameMap,
@@ -518,9 +518,11 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _loadSheetData() {
const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook?.getActiveSheet();
+ const base = workbook ? null : this._univerInstanceService.getCurrentUnitOfType<BaseDataModel>(UniverInstanceType.UNIVER_BASE);
+ const table = base ? getFirstLiveBaseTable(base.getSnapshot().tables, base.getSnapshot().tableOrder) : null;
- this._executeUnitId = workbook?.getUnitId();
- this._executeSubUnitId = worksheet?.getSheetId();
+ this._executeUnitId = workbook?.getUnitId() ?? base?.getUnitId();
+ this._executeSubUnitId = worksheet?.getSheetId() ?? table?.id;
return this._formulaDataModel.getCalculateData();
}
@@ -560,6 +562,17 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
}
+function getFirstLiveBaseTable(tables: Record<string, ITableSnapshot>, tableOrder: string[]): ITableSnapshot | null {
+ for (const tableId of tableOrder) {
+ const table = tables[tableId];
+ if (table && !table.deleted) {
+ return table;
+ }
+ }
+
+ return Object.values(tables).find((table) => !table.deleted) ?? null;
+}
+
export const IFormulaCurrentConfigService = createIdentifier<IFormulaCurrentConfigService>(
'univer.formula.current-data.service'
);
diff --git a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts b/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
index 757c3fa9d0..d67da7382a 100644
--- a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
+++ b/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
@@ -63,6 +63,18 @@ describe('Test Canvas Color', () => {
expect(invertedColor2).toEqual('rgba(255,85,85, 1)');
});
+ it('uses stable dark-mode overrides for common canvas interaction colors', async () => {
+ themeService.setDarkMode(false);
+ expect(canvasColorService.getRenderColor('#f3f6fa')).toEqual('#f3f6fa');
+ expect(canvasColorService.getRenderColor('rgba(37, 99, 235, 0.08)')).toEqual('rgba(37, 99, 235, 0.08)');
+
+ themeService.setDarkMode(true);
+ expect(canvasColorService.getRenderColor('#f3f6fa')).toEqual('#18243a');
+ expect(canvasColorService.getRenderColor('#1d5cff')).toEqual('#60a5fa');
+ expect(canvasColorService.getRenderColor('rgba(37, 99, 235, 0.08)')).toEqual('rgba(96,165,250,0.22)');
+ expect(canvasColorService.getRenderColor('rgba(37,99,235,0.08)')).toEqual('rgba(96,165,250,0.22)');
+ });
+
it('test short hex color', async () => {
const color = '#ccc';
themeService.setDarkMode(false);
diff --git a/packages/engine-render/src/services/canvas-color.service.ts b/packages/engine-render/src/services/canvas-color.service.ts
index 98f481d7c4..de66715a6b 100644
--- a/packages/engine-render/src/services/canvas-color.service.ts
+++ b/packages/engine-render/src/services/canvas-color.service.ts
@@ -32,6 +32,43 @@ export class DumbCanvasColorService implements ICanvasColorService {
}
}
+const DARK_RENDER_COLOR_OVERRIDES: Record<string, string> = {
+ '#17212b': '#e2e8f0',
+ '#64748b': '#94a3b8',
+ '#d9e0e7': '#253044',
+ '#edf1f5': '#1b2535',
+ '#eef2f6': '#1b2535',
+ '#f2f5f8': '#101827',
+ '#f3f6fa': '#18243a',
+ '#f4f8ff': '#172a46',
+ '#f5f9ff': '#12233a',
+ '#f7f9fb': '#0d1422',
+ '#f7f9fc': '#0d1422',
+ '#f8fafc': '#0f172a',
+ '#fbfcfd': '#07111f',
+ '#fcfdff': '#050914',
+ '#e8f1ff': '#173a69',
+ '#eaf5ff': '#12315a',
+ '#dbeafe': '#1e3a8a',
+ '#bfdbfe': '#60a5fa',
+ '#93c5fd': '#60a5fa',
+ '#8eb6f5': '#60a5fa',
+ '#60a5fa': '#60a5fa',
+ '#2563eb': '#60a5fa',
+ '#1d64d8': '#93c5fd',
+ '#1d5cff': '#60a5fa',
+ '#0f766e': '#2dd4bf',
+ '#d7f4ef': '#134e4a',
+ 'rgba(37,99,235,0.05)': 'rgba(96,165,250,0.16)',
+ 'rgba(37,99,235,0.06)': 'rgba(96,165,250,0.18)',
+ 'rgba(37,99,235,0.08)': 'rgba(96,165,250,0.22)',
+ 'rgba(37,99,235,0.12)': 'rgba(96,165,250,0.26)',
+ 'rgba(37,99,235,0.18)': 'rgba(96,165,250,0.30)',
+ 'rgba(37,99,235,0.28)': 'rgba(96,165,250,0.38)',
+ 'rgba(239,246,255,0.88)': 'rgba(30,64,175,0.72)',
+ 'rgba(148,163,184,0.45)': 'rgba(148,163,184,0.52)',
+};
+
/**
* This service inverts a color for dark mode. This service is exposed
*/
@@ -55,7 +92,10 @@ export class CanvasColorService extends Disposable implements ICanvasColorServic
}
let cachedColor = '';
- if (color.startsWith('#')) {
+ const mappedColor = getDarkRenderColorOverride(color);
+ if (mappedColor) {
+ cachedColor = mappedColor;
+ } else if (color.startsWith('#')) {
const invertedColor = this._invertAlgo(hexToRgb(color));
cachedColor = rgbToHex(invertedColor);
@@ -63,10 +103,8 @@ export class CanvasColorService extends Disposable implements ICanvasColorServic
if (color.length === 5) {
const alpha = color.charAt(4);
cachedColor += alpha + alpha;
- }
-
- // For 8-digit hex (e.g., #RRGGBB[AA]), the alpha is the last two characters
- else if (color.length === 9) {
+ } else if (color.length === 9) {
+ // For 8-digit hex (e.g., #RRGGBB[AA]), the alpha is the last two characters
const alpha = color.substring(7, 9);
cachedColor += alpha;
}
@@ -95,6 +133,20 @@ export class CanvasColorService extends Disposable implements ICanvasColorServic
}
}
+export function getDarkRenderColorOverride(color: string): string | null {
+ const normalized = normalizeRenderColor(color);
+ return DARK_RENDER_COLOR_OVERRIDES[normalized] ?? null;
+}
+
+function normalizeRenderColor(color: string): string {
+ const trimmed = color.trim().toLowerCase();
+ if (trimmed.startsWith('rgb')) {
+ return trimmed.replace(/\s+/g, '');
+ }
+
+ return trimmed;
+}
+
export function hexToRgb(_hex: string): RGBColorType {
const hex = _hex.replace(/^#/, '');
diff --git a/packages/protocol/src/ts/univer/constants/univer.ts b/packages/protocol/src/ts/univer/constants/univer.ts
index 852d878234..1292cf46af 100644
--- a/packages/protocol/src/ts/univer/constants/univer.ts
+++ b/packages/protocol/src/ts/univer/constants/univer.ts
@@ -20,5 +20,6 @@ export enum UniverType {
UNIVER_SHEET = 2,
UNIVER_SLIDE = 3,
UNIVER_PROJECT = 4,
+ UNIVER_BASE = 5,
UNRECOGNIZED = -1,
}
diff --git a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
index 7dbd07de53..44deb75eb1 100644
--- a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
+++ b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
@@ -41,6 +41,12 @@ function buildRemoteChannel(target: Record<string, (...args: unknown[]) => unkno
};
}
+async function flushPromises(times = 6): Promise<void> {
+ for (let index = 0; index < times; index++) {
+ await Promise.resolve();
+ }
+}
+
describe('data-sync controllers', () => {
it('DataSyncPrimaryController should sync add/dispose/mutation with branch guards', async () => {
const added$ = new Subject<{ unit: { getUnitId(): string; getSnapshot(): unknown } }>();
@@ -88,6 +94,16 @@ describe('data-sync controllers', () => {
const univerInstanceService = {
getTypeOfUnitAdded$: vi.fn(() => added$.asObservable()),
getTypeOfUnitDisposed$: vi.fn(() => disposed$.asObservable()),
+ getUnit: vi.fn((unitId: string) => {
+ if (unitId !== 'unit-2') {
+ return null;
+ }
+ return {
+ type: UniverInstanceType.UNIVER_BASE,
+ getUnitId: () => 'unit-2',
+ getSnapshot: () => ({ base: true }),
+ };
+ }),
} as unknown as IUniverInstanceService;
const remoteSyncService = {
@@ -124,13 +140,18 @@ describe('data-sync controllers', () => {
controller.registerSyncingMutations({ id: 'm-sync' } as never);
const unit2Disposable = controller.syncUnit('unit-2');
+ expect(remoteInstanceImpl.createInstance).toHaveBeenCalledWith({
+ unitID: 'unit-2',
+ type: UniverInstanceType.UNIVER_BASE,
+ snapshot: { base: true },
+ });
commandCallback?.({
id: 'm-sync',
type: CommandType.MUTATION,
params: { unitId: 'unit-2' },
}, {});
- await Promise.resolve();
+ await flushPromises();
expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(1);
commandCallback?.({
@@ -158,19 +179,116 @@ describe('data-sync controllers', () => {
type: CommandType.MUTATION,
params: {},
}, {});
- await Promise.resolve();
+ await flushPromises();
expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);
unit2Disposable.dispose();
+ expect(remoteInstanceImpl.disposeInstance).toHaveBeenCalledWith({ unitID: 'unit-2' });
commandCallback?.({
id: 'm-sync',
type: CommandType.MUTATION,
params: { unitId: 'unit-2' },
}, {});
- await Promise.resolve();
+ await flushPromises();
+ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);
+
+ controller.dispose();
+ });
+
+ it('DataSyncPrimaryController should serialize remote mutation sync calls', async () => {
+ const added$ = new Subject<{ unit: { getUnitId(): string; getSnapshot(): unknown } }>();
+ const disposed$ = new Subject<{ getUnitId(): string }>();
+ let commandCallback: ((commandInfo: unknown, options?: unknown) => void) | undefined;
+ const dependencies: Array<[unknown, IDependencyFactory]> = [];
+ let remoteProxy: unknown;
+ const resolvers: Array<(value: boolean) => void> = [];
+
+ const remoteInstanceImpl = {
+ createInstance: vi.fn(async () => true),
+ disposeInstance: vi.fn(async () => true),
+ syncMutation: vi.fn(() => new Promise<boolean>((resolve) => resolvers.push(resolve))),
+ };
+
+ const remoteChannel = buildRemoteChannel(remoteInstanceImpl);
+
+ const rpcChannelService: IRPCChannelService = {
+ requestChannel: vi.fn(() => remoteChannel),
+ registerChannel: vi.fn(),
+ };
+
+ const injector = {
+ add: vi.fn((dependency: [unknown, IDependencyFactory]) => {
+ dependencies.push(dependency);
+ }),
+ get: vi.fn((token: unknown) => {
+ if (token === IRemoteInstanceService) {
+ if (!remoteProxy) {
+ const record = dependencies.find(([depToken]) => depToken === IRemoteInstanceService);
+ remoteProxy = record?.[1].useFactory();
+ }
+ return remoteProxy;
+ }
+ return undefined;
+ }),
+ } as unknown as Injector;
+
+ const commandService = {
+ onCommandExecuted: vi.fn((callback: (commandInfo: unknown, options?: unknown) => void) => {
+ commandCallback = callback;
+ return { dispose: vi.fn() };
+ }),
+ } as unknown as ICommandService;
+
+ const univerInstanceService = {
+ getTypeOfUnitAdded$: vi.fn(() => added$.asObservable()),
+ getTypeOfUnitDisposed$: vi.fn(() => disposed$.asObservable()),
+ getUnit: vi.fn(() => null),
+ } as unknown as IUniverInstanceService;
+
+ const remoteSyncService = {
+ syncMutation: vi.fn(async () => true),
+ };
+
+ const controller = new DataSyncPrimaryController(
+ injector,
+ commandService,
+ univerInstanceService,
+ rpcChannelService,
+ remoteSyncService as never
+ );
+
+ controller.registerSyncingMutations({ id: 'm-source' } as never);
+ controller.registerSyncingMutations({ id: 'm-calculate' } as never);
+ controller.syncUnit('unit-1');
+
+ commandCallback?.({
+ id: 'm-source',
+ type: CommandType.MUTATION,
+ params: { unitId: 'unit-1' },
+ }, {});
+ commandCallback?.({
+ id: 'm-calculate',
+ type: CommandType.MUTATION,
+ params: { unitId: 'unit-1' },
+ }, {});
+
+ await flushPromises();
+ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(1);
+ expect(remoteInstanceImpl.syncMutation).toHaveBeenNthCalledWith(1, {
+ mutationInfo: expect.objectContaining({ id: 'm-source' }),
+ }, {});
+
+ resolvers[0](true);
+ await flushPromises();
+
expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);
+ expect(remoteInstanceImpl.syncMutation).toHaveBeenNthCalledWith(2, {
+ mutationInfo: expect.objectContaining({ id: 'm-calculate' }),
+ }, {});
+ resolvers[1](true);
+ await flushPromises();
controller.dispose();
});
diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
index 22c03b977c..12b27026d3 100644
--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDisposable, IMutation, IMutationInfo, Workbook } from '@univerjs/core';
+import type { BaseDataModel, IDisposable, IMutation, IMutationInfo, Workbook } from '@univerjs/core';
import type { IRemoteSyncMutationOptions } from '../../services/remote-instance/remote-instance.service';
import {
CommandType,
@@ -49,6 +49,8 @@ export class DataSyncPrimaryController extends RxDisposable {
private readonly _syncingMutations = new Set<string>();
+ private _syncMutationQueue: Promise<unknown> = Promise.resolve();
+
constructor(
@Inject(Injector) private readonly _injector: Injector,
@ICommandService private readonly _commandService: ICommandService,
@@ -71,8 +73,28 @@ export class DataSyncPrimaryController extends RxDisposable {
* sync other types of documents, you should manually call this method with that document's id.
*/
syncUnit(unitId: string): IDisposable {
+ const alreadySyncing = this._syncingUnits.has(unitId);
this._syncingUnits.add(unitId);
- return toDisposable(() => this._syncingUnits.delete(unitId));
+ const unit = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)
+ ?? this._univerInstanceService.getUnit<BaseDataModel>(unitId, UniverInstanceType.UNIVER_BASE);
+ if (!alreadySyncing && unit) {
+ this._remoteInstanceService.createInstance({
+ unitID: unit.getUnitId(),
+ type: unit.type,
+ snapshot: unit.getSnapshot(),
+ });
+ }
+
+ return toDisposable(() => {
+ if (!alreadySyncing) {
+ this._syncingUnits.delete(unitId);
+ }
+ if (!alreadySyncing && unit) {
+ this._remoteInstanceService.disposeInstance({
+ unitID: unit.getUnitId(),
+ });
+ }
+ });
}
private _initRPCChannels(): void {
@@ -121,7 +143,8 @@ export class DataSyncPrimaryController extends RxDisposable {
!(options as IRemoteSyncMutationOptions)?.fromSync &&
// do not sync mutations those are not meant to be synced
this._syncingMutations.has(id)) {
- this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo as IMutationInfo }, options);
+ const sync = () => this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo as IMutationInfo }, options);
+ this._syncMutationQueue = this._syncMutationQueue.then(sync, sync).catch(() => false);
}
}));
}
diff --git a/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
index 7e40249101..8cff38433a 100644
--- a/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
+++ b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
@@ -115,6 +115,13 @@ describe('remote-instance.service', () => {
})).resolves.toBe(true);
expect(createUnit).toHaveBeenCalledWith(UniverInstanceType.UNIVER_SHEET, { id: 'snapshot' });
+ await expect(service.createInstance({
+ unitID: 'base-1',
+ type: UniverInstanceType.UNIVER_BASE,
+ snapshot: { id: 'base-snapshot' } as never,
+ })).resolves.toBe(true);
+ expect(createUnit).toHaveBeenCalledWith(UniverInstanceType.UNIVER_BASE, { id: 'base-snapshot' });
+
await expect(service.disposeInstance({ unitID: 'sheet-1' })).resolves.toBe(true);
expect(disposeUnit).toHaveBeenCalledWith('sheet-1');
expect(debug).toHaveBeenCalled();
diff --git a/packages/rpc/src/services/remote-instance/remote-instance.service.ts b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
index ddd86b2c81..fdc50039c0 100644
--- a/packages/rpc/src/services/remote-instance/remote-instance.service.ts
+++ b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IExecutionOptions, IMutationInfo, IWorkbookData } from '@univerjs/core';
+import type { IBaseSnapshot, IExecutionOptions, IMutationInfo, IWorkbookData } from '@univerjs/core';
import { createIdentifier, ICommandService, ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
export interface IRemoteSyncMutationOptions extends IExecutionOptions {
@@ -60,7 +60,7 @@ export interface IRemoteInstanceService {
/** Tell other modules if the `IRemoteInstanceService` is ready to load files. */
whenReady(): Promise<true>;
- createInstance(params: { unitID: string; type: UniverInstanceType; snapshot: IWorkbookData }): Promise<boolean>;
+ createInstance(params: { unitID: string; type: UniverInstanceType; snapshot: IWorkbookData | IBaseSnapshot }): Promise<boolean>;
disposeInstance(params: { unitID: string }): Promise<boolean>;
syncMutation(params: { mutationInfo: IMutationInfo }, options?: IExecutionOptions): Promise<boolean>;
}
@@ -85,7 +85,7 @@ export class WebWorkerRemoteInstanceService implements IRemoteInstanceService {
async createInstance(params: {
unitID: string;
type: UniverInstanceType;
- snapshot: IWorkbookData;
+ snapshot: IWorkbookData | IBaseSnapshot;
}): Promise<boolean> {
this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${params.unitID}`);
const { type, snapshot } = params;
@@ -94,6 +94,9 @@ export class WebWorkerRemoteInstanceService implements IRemoteInstanceService {
case UniverInstanceType.UNIVER_SHEET:
this._univerInstanceService.createUnit(UniverInstanceType.UNIVER_SHEET, snapshot);
return true;
+ case UniverInstanceType.UNIVER_BASE:
+ this._univerInstanceService.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
+ return true;
default:
throw new Error(
`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`