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
fix(sheet): support bind delete & date type source (#4487)
VicKun4aff7f7817b3
diff --git a/packages-experimental/sheets-source-binding/src/controllers/binding-manager.ts b/packages-experimental/sheets-source-binding/src/controllers/binding-manager.tsindex 55b9d24509..b3508df2e0 100644--- a/packages-experimental/sheets-source-binding/src/controllers/binding-manager.ts+++ b/packages-experimental/sheets-source-binding/src/controllers/binding-manager.ts@@ -14,8 +14,11 @@* limitations under the License.*/-import type { ICellBindingNode, ICellBindingNodeParam } from '../types';-import { Disposable, generateRandomId } from '@univerjs/core';+import type { IMutationInfo } from '@univerjs/core';+import type { ICellBindingJSON, ICellBindingNode, ICellBindingNodeParam } from '../types';+import { Disposable, generateRandomId, Inject, IUniverInstanceService, Range } from '@univerjs/core';++import { ClearSelectionAllCommand, ClearSelectionContentCommand, getSheetCommandTarget, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import { Subject } from 'rxjs';import { SheetBindingModel } from '../model/binding-model';import { BindingSourceChangeTypeEnum } from '../types';@@ -32,12 +35,47 @@ interface IBindingNodeInfo {export class SheetsBindingManager extends Disposable {modelMap: Map<string, Map<string, SheetBindingModel>> = new Map();- private _cellBindInfoUpdate$ = new Subject<IBindingNodeInfo & { changeType: BindingSourceChangeTypeEnum;oldSourceId?: string }>();+ private _cellBindInfoUpdate$ = new Subject<IBindingNodeInfo & { changeType: BindingSourceChangeTypeEnum; oldSourceId?: string }>();cellBindInfoUpdate$ = this._cellBindInfoUpdate$.asObservable();constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(SheetsSelectionsService) private readonly _sheetsSelectionsService: SheetsSelectionsService) {super();+ this._initRemoveCommand();+ }++ private _initRemoveCommand() {+ this.disposeWithMe(+ this._sheetInterceptorService.interceptCommand({+ getMutations: (command) => {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ const selections = this._sheetsSelectionsService.getCurrentSelections();+ const target = getSheetCommandTarget(this._univerInstanceService);+ if (!target || !selections || selections.length === 0) {+ return {+ redos: [],+ undos: [],+ };+ }+ const { unitId, subUnitId } = target;+ if (command.id === ClearSelectionContentCommand.id || command.id === ClearSelectionAllCommand.id) {+ selections.forEach(({ range }) => {+ Range.foreach(range, (row, column) => {+ const node = this.getBindingNode(unitId, subUnitId, row, column);+ if (node) {+ this.removeBindingNode(unitId, subUnitId, row, column);+ }+ });+ });+ }+ return { redos, undos };+ },+ })+ );}getBindingModelBySourceId(sourceId: string) {@@ -127,13 +165,31 @@ export class SheetsBindingManager extends Disposable {return undefined;}- createModel(unitId: string, subunitId: string, json?: any): SheetBindingModel {+ createModel(unitId: string, subunitId: string, json?: ICellBindingNode[]): SheetBindingModel {const model = new SheetBindingModel(json);this.addModel(unitId, subunitId, model);return model;}+ toJSON(unitId: string) {+ const rs: ICellBindingJSON = {};+ const subMap = this.modelMap.get(unitId);+ if (subMap) {+ subMap.forEach((model, subunitId) => {+ rs[subunitId] = model.toJSON();+ });+ }+ return rs;+ }++ fromJSON(unitId: string, json: ICellBindingJSON) {+ Object.entries(json).forEach(([subunitId, nodes]) => {+ this.createModel(unitId, subunitId, nodes);+ });+ }+override dispose(): void {this.modelMap.clear();+ this._cellBindInfoUpdate$.complete();}}diff --git a/packages-experimental/sheets-source-binding/src/controllers/source-manager.ts b/packages-experimental/sheets-source-binding/src/controllers/source-manager.tsindex eefb7423bf..b5890b73a3 100644--- a/packages-experimental/sheets-source-binding/src/controllers/source-manager.ts+++ b/packages-experimental/sheets-source-binding/src/controllers/source-manager.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ISourceEvent } from '../types';+import type { ISourceEvent, ISourceJSON } from '../types';import { Disposable, generateRandomId } from '@univerjs/core';import { Subject } from 'rxjs';import { ListSourceModel, ObjectSourceModel, SourceModelBase } from '../model/source-model';@@ -85,4 +85,39 @@ export class SheetsSourceManager extends Disposable {this._sourceDataUpdate$.next({ ...source.getSourceInfo(), unitId, changeType: BindingSourceChangeTypeEnum.Remove });}}++ toJSON(unitId: string): ISourceJSON[] {+ const sourceList: ISourceJSON[] = [];+ const unitMap = this._getUnitMap(unitId);+ if (unitMap) {+ for (const source of unitMap.values()) {+ sourceList.push(source.toJSON());+ }+ }+ return sourceList;+ }++ fromJSON(unitId: string, sources: ISourceJSON[]): void {+ const unitMap = this._ensureUnitMap(unitId);+ for (const source of sources) {+ let model: SourceModelBase;+ switch (source.type) {+ case DataBindingNodeTypeEnum.List:+ model = new ListSourceModel(source.id);+ break;+ case DataBindingNodeTypeEnum.Object:+ model = new ObjectSourceModel(source.id);+ break;+ default:+ throw new Error(`Invalid source type: ${source.type}`);+ }+ model.fromJSON(source);+ unitMap.set(source.id, model);+ }+ }++ override dispose(): void {+ this._sourceDataUpdate$.complete();+ this.sourceMap.clear();+ }}diff --git a/packages-experimental/sheets-source-binding/src/facade/f-workbook.ts b/packages-experimental/sheets-source-binding/src/facade/f-workbook.tsindex 41e8bf62bc..08cbac761c 100644--- a/packages-experimental/sheets-source-binding/src/facade/f-workbook.ts+++ b/packages-experimental/sheets-source-binding/src/facade/f-workbook.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { DataBindingNodeTypeEnum, SourceModelBase } from '@univerjs/sheets-source-binding';-import { SheetsSourceBindService } from '@univerjs/sheets-source-binding';+import type { DataBindingNodeTypeEnum, ISourceBindingInfo, SourceModelBase } from '@univerjs/sheets-source-binding';+import { SheetsSourceBindService, SheetsSourceManager } from '@univerjs/sheets-source-binding';import { FWorkbook } from '@univerjs/sheets/facade';export interface IFWorkbookSourceBindingMixin {@@ -23,9 +23,10 @@ export interface IFWorkbookSourceBindingMixin {* Create a source model with the specified type.* @param {DataBindingNodeTypeEnum} type The source type.* @param {boolean} [isListObject] Whether the source is a list object.+ * @param {string} [id] The source id.* @returns {SourceModelBase} The source data of sheet.*/- createSource(type: DataBindingNodeTypeEnum, isListObject?: boolean): SourceModelBase;+ createSource(type: DataBindingNodeTypeEnum, isListObject?: boolean, id?: string | undefined): SourceModelBase;/*** Switch to path mode.In this mode, the path will show in cell.*/@@ -39,13 +40,37 @@ export interface IFWorkbookSourceBindingMixin {* @param {string} sourceId The source id.*/getSource(sourceId: string): SourceModelBase | undefined;+ /**+ * Set the source data by the specified source id.+ * @param {string} sourceId - The source id which you want to set data.+ * @param data - The source data. If the source is a list object, the data should be an array of objects.+ * If the isListObject is false, the data should look like below:+ * ```typescript+ * {+ * fields: ['name', 'age'],+ * records: [['Tom', 18], ['Jerry', 20]]+ * }+ * ```+ * If the isListObject is true, the data should look like below:+ * ```typescript+ * {+ * fields: ['name', 'age'],+ * records: [{name: 'Tom', age: 18}, {name: 'Jerry', age: 20}]+ * }+ * ```+ */+ setSourceData(sourceId: string, data: any): void;++ loadSourceBindingPathInfo(obj: ISourceBindingInfo): void;++ saveSourceBindingPathInfo(): ISourceBindingInfo;}export class FWorkbookSourceBinding extends FWorkbook implements IFWorkbookSourceBindingMixin {- override createSource(type: DataBindingNodeTypeEnum, isListObject?: boolean): SourceModelBase {+ override createSource(type: DataBindingNodeTypeEnum, isListObject?: boolean, id?: string | undefined): SourceModelBase {const injector = this._injector;const sheetsSourceBindService = injector.get(SheetsSourceBindService);- return sheetsSourceBindService.createSource(this.getId(), type, isListObject);+ return sheetsSourceBindService.createSource(this.getId(), type, isListObject, id);}override getSource(sourceId: string): SourceModelBase | undefined {@@ -54,6 +79,12 @@ export class FWorkbookSourceBinding extends FWorkbook implements IFWorkbookSourcreturn sheetsSourceBindService.getSource(this.getId(), sourceId);}+ override setSourceData(sourceId: string, data: any): void {+ const injector = this._injector;+ const sheetsSourceManager = injector.get(SheetsSourceManager);+ sheetsSourceManager.updateSourceData(this.getId(), sourceId, data);+ }+override usePathMode(): void {const injector = this._injector;const sheetsSourceBindService = injector.get(SheetsSourceBindService);@@ -65,6 +96,18 @@ export class FWorkbookSourceBinding extends FWorkbook implements IFWorkbookSourcconst sheetsSourceBindService = injector.get(SheetsSourceBindService);sheetsSourceBindService.useValueMode();}++ override loadSourceBindingPathInfo(obj: ISourceBindingInfo): void {+ const injector = this._injector;+ const sheetsSourceBindService = injector.get(SheetsSourceBindService);+ sheetsSourceBindService.loadSourceBindingPathInfo(this.getId(), obj);+ }++ override saveSourceBindingPathInfo(): ISourceBindingInfo {+ const injector = this._injector;+ const sheetsSourceBindService = injector.get(SheetsSourceBindService);+ return sheetsSourceBindService.getSourceBindingPathInfo(this.getId());+ }}FWorkbook.extend(FWorkbookSourceBinding);diff --git a/packages-experimental/sheets-source-binding/src/index.ts b/packages-experimental/sheets-source-binding/src/index.tsindex 7777889b29..ab8d30244b 100644--- a/packages-experimental/sheets-source-binding/src/index.ts+++ b/packages-experimental/sheets-source-binding/src/index.ts@@ -19,4 +19,5 @@ export { SourceModelBase } from './model/source-model';export { UniverSheetsBindingSourcePlugin } from './plugin';export { BindModeEnum, DataBindingNodeTypeEnum } from './types';export { SheetsSourceBindService } from './services/source-binding-service';-export type { ICellBindingNode, ICellBindingNodeParam } from './types';+export { SheetsSourceManager } from './controllers/source-manager';+export type { ICellBindingNode, ICellBindingNodeParam, ISourceBindingInfo } from './types';diff --git a/packages-experimental/sheets-source-binding/src/model/binding-model.ts b/packages-experimental/sheets-source-binding/src/model/binding-model.tsindex b00dc30bda..1bca00efa6 100644--- a/packages-experimental/sheets-source-binding/src/model/binding-model.ts+++ b/packages-experimental/sheets-source-binding/src/model/binding-model.ts@@ -23,14 +23,14 @@ export class SheetBindingModel {private _sourceIdMap: Map<string, string[]> = new Map();- constructor(json?: any) {+ constructor(json?: ICellBindingNode[]) {if (json) {this._init(json);}}- _init(json: any): void {- this.fromJSON();+ _init(json: ICellBindingNode[]): void {+ this.fromJSON(json);}getBindingNodesBySourceId(sourceId: string): ICellBindingNode[] | undefined {@@ -86,12 +86,14 @@ export class SheetBindingModel {return this._nodeMap.get(nodeId);}- fromJSON(): void {-+ fromJSON(nodes: ICellBindingNode[]): void {+ nodes.forEach((node) => {+ this.setBindingNode(node.row, node.column, node);+ });}- toJSON() {-+ toJSON(): ICellBindingNode[] {+ return Array.from(this._nodeMap.values());}}diff --git a/packages-experimental/sheets-source-binding/src/model/source-model.ts b/packages-experimental/sheets-source-binding/src/model/source-model.tsindex c633379a3b..c9e21ac376 100644--- a/packages-experimental/sheets-source-binding/src/model/source-model.ts+++ b/packages-experimental/sheets-source-binding/src/model/source-model.ts@@ -14,9 +14,34 @@* limitations under the License.*/-import type { ICellBindingNode, IListDataBindingNode, IListSourceData, IListSourceInfo, IObjectSourceInfo } from '../types';+import type { ICellBindingNode, IListDataBindingNode, IListSourceData, IListSourceInfo, IObjectSourceInfo, ISourceJSON } from '../types';+import { CellValueType, type ICellData } from '@univerjs/core';import { DataBindingNodeTypeEnum } from '../types';+function isValidDate(date: Date): date is Date {+ return date instanceof Date && !isNaN(date.getTime());+}++function transformDate(dateString: string | number): number | string {+ const date = new Date(dateString);+ if (!isValidDate(date)) {+ return dateString;+ }+ const baseDate = new Date(Date.UTC(1900, 0, 1, 0, 0, 0)); // January 1, 1900, UTC at midnight+ const leapDayDate = new Date(Date.UTC(1900, 1, 28, 0, 0, 0)); // February 28, 1900, UTC at midnight++ // Calculate the difference in milliseconds between the input date and the base date+ const diffMilliseconds = date.getTime() - baseDate.getTime();+ let dayDifference = diffMilliseconds / (1000 * 3600 * 24);++ // Adjusting for the Excel leap year bug+ if (date > leapDayDate) {+ dayDifference += 1;+ }++ return dayDifference + 1; // Excel serial number starts from 1+}+export abstract class SourceModelBase {protected _data: any;readonly id: string;@@ -43,9 +68,23 @@ export abstract class SourceModelBase {this._hasData = true;}+ toJSON(): ISourceJSON {+ return {+ id: this.id,+ type: this.type,+ };+ }++ fromJSON(info: ISourceJSON): void {+ // @ts-ignore+ this.id = info.id;+ // @ts-ignore+ this.type = info.type;+ }+abstract getSourceInfo(): any;- abstract getData(node: ICellBindingNode, row: number, col: number): string | number | boolean | null;+ abstract getData(node: ICellBindingNode, row: number, col: number): ICellData | null;}export class ListSourceModel extends SourceModelBase {@@ -67,17 +106,35 @@ export class ListSourceModel extends SourceModelBase {this._isListObject = isListObject;}- getData(node: IListDataBindingNode, row: number): string | number | boolean | null {+ getData(node: IListDataBindingNode, row: number): ICellData | null {const { path, row: baseRow } = node;const colIndex = this._fieldIndexMap.get(path)!;const rowIndex = row - baseRow;if (rowIndex === 0) {- return this._data.fields[colIndex];+ return {+ v: this._data.fields[colIndex],+ };}+ let data;if (this._isListObject) {- return (this._data.records as Record<string | number, any>)[rowIndex - 1][path];+ data = (this._data.records as Record<string | number, any>)[rowIndex - 1][path];+ }+ data = this._data.records[rowIndex - 1][colIndex];+ if (node.isDate === true) {+ return {+ v: transformDate(data),+ s: {+ n: {+ pattern: 'yyyy-m-d am/pm h:mm',+ },+ },+ t: CellValueType.NUMBER,+ };+ } else {+ return {+ v: data,+ };}- return this._data.records[rowIndex - 1][colIndex];}override setSourceData(data: IListSourceData): void {@@ -105,7 +162,7 @@ export class ObjectSourceModel extends SourceModelBase {super(id);}- getData(node: ICellBindingNode): string | number | boolean | null {+ getData(node: ICellBindingNode): ICellData | null {const path = node.path;const paths = path.split('.');let data = this._data;@@ -115,7 +172,21 @@ export class ObjectSourceModel extends SourceModelBase {return null;}}- return data;+ if (node.isDate === true) {+ return {+ v: transformDate(data),+ s: {+ n: {+ pattern: 'yyyy-m-d am/pm h:mm',+ },+ },+ t: CellValueType.NUMBER,+ };+ } else {+ return {+ v: data,+ };+ }}override getSourceInfo(): IObjectSourceInfo {diff --git a/packages-experimental/sheets-source-binding/src/services/source-binding-service.ts b/packages-experimental/sheets-source-binding/src/services/source-binding-service.tsindex 8ea6fb1fe5..5d1c546108 100644--- a/packages-experimental/sheets-source-binding/src/services/source-binding-service.ts+++ b/packages-experimental/sheets-source-binding/src/services/source-binding-service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellBindingNodeParam, IListSourceInfo } from '../types';+import type { ICellBindingNodeParam, IListSourceInfo, ISourceBindingInfo } from '../types';import { Disposable, Inject, InterceptorEffectEnum, RTree } from '@univerjs/core';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';@@ -81,6 +81,18 @@ export class SheetsSourceBindService extends Disposable {return this._sheetsSourceManager.createSource(unitId, type, isListObject, id);}+ getSourceBindingPathInfo(unitId: string) {+ return {+ source: this._sheetsSourceManager.toJSON(unitId),+ cellBinding: this._sheetsBindingManager.toJSON(unitId),+ };+ }++ loadSourceBindingPathInfo(unitId: string, obj: ISourceBindingInfo) {+ this._sheetsSourceManager.fromJSON(unitId, obj.source);+ this._sheetsBindingManager.fromJSON(unitId, obj.cellBinding);+ }+private _ensureRTreeCollection(unitId: string) {if (!this._bindModelRTreeCollection.has(unitId)) {this._bindModelRTreeCollection.set(unitId, new RTree());@@ -203,9 +215,7 @@ export class SheetsSourceBindService extends Disposable {const { sourceId } = node;const source = this._sheetsSourceManager.getSource(unitId, sourceId);if (source && source.hasData()) {- return {- v: source?.getData(node, row, col) || '',- };+ return source?.getData(node, row, col) || { v: '' };}}}@@ -219,9 +229,7 @@ export class SheetsSourceBindService extends Disposable {const { sourceId } = node;const source = this._sheetsSourceManager.getSource(unitId, sourceId);if (source && source.hasData()) {- return {- v: source?.getData(node, row, col) || '',- };+ return source?.getData(node, row, col) || { v: '' };}}}@@ -230,7 +238,8 @@ export class SheetsSourceBindService extends Disposable {private _registerInterceptor() {this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {- effect: InterceptorEffectEnum.Value,+ effect: InterceptorEffectEnum.Value | InterceptorEffectEnum.Style,+ priority: 102,handler: (cell, context, next) => {const { row, col, unitId, subUnitId } = context;let value = null;@@ -247,4 +256,8 @@ export class SheetsSourceBindService extends Disposable {},}));}++ override dispose(): void {+ this._bindModelRTreeCollection.clear();+ }}diff --git a/packages-experimental/sheets-source-binding/src/types.ts b/packages-experimental/sheets-source-binding/src/types.tsindex c41f68c773..c5ccb6415d 100644--- a/packages-experimental/sheets-source-binding/src/types.ts+++ b/packages-experimental/sheets-source-binding/src/types.ts@@ -100,6 +100,10 @@ export interface ICellBindingNodeParam {* The target column of the binding node.*/column: number;+ /**+ * Whether treat the data as date.+ */+ isDate?: boolean;nodeId?: string; // optional in ICellBindingNodeParam}@@ -162,3 +166,16 @@ export enum BindingSourceChangeTypeEnum {Update = 'update',}+export interface ISourceJSON {+ id: string;+ type: DataBindingNodeTypeEnum;+}++export interface ICellBindingJSON {+ [subUnitId: string]: ICellBindingNode[];+}++export interface ISourceBindingInfo {+ source: ISourceJSON[];+ cellBinding: ICellBindingJSON;+}diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.tsindex b05039c19a..5081e2f453 100644--- a/packages/sheets/src/facade/f-workbook.ts+++ b/packages/sheets/src/facade/f-workbook.ts@@ -403,6 +403,7 @@ export class FWorkbook extends FBaseInitialable {* activeSpreadsheet.onCommandExecuted((command) => {* console.log('Command executed:', command);* });+ * ```*/onCommandExecuted(callback: CommandListener): IDisposable {return this._commandService.onCommandExecuted((command) => {