Skip to content

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

refactor(resources)!: remove workbook.save and add resourceloader.saveunit (#3128)

Gpound.liu0c629f1a2612
diff --git a/packages/core/src/common/unit.ts b/packages/core/src/common/unit.ts
index c817d6baa9..533af8b1b1 100644
--- a/packages/core/src/common/unit.ts
+++ b/packages/core/src/common/unit.ts
@@ -22,10 +22,12 @@ export { UniverType as UniverInstanceType } from '@univerjs/protocol';
export type UnitType = UniverType | number;
-export abstract class UnitModel<_D = object, T extends UnitType = UnitType> extends Disposable {
+export abstract class UnitModel<D = object, T extends UnitType = UnitType> extends Disposable {
abstract readonly type: T;
abstract getUnitId(): string;
abstract name$: Observable<string>;
abstract setName(name: string): void;
+
+ abstract getSnapshot(): D;
}
diff --git a/packages/core/src/services/__tests__/index.ts b/packages/core/src/services/__tests__/index.ts
index 7a72c8bc93..4cc2ee702d 100644
--- a/packages/core/src/services/__tests__/index.ts
+++ b/packages/core/src/services/__tests__/index.ts
@@ -42,7 +42,7 @@ const TEST_WORKBOOK_DATA_DEMO: () => IWorkbookData = () => ({
name: '',
sheetOrder: [],
styles: {},
- resources: [],
+ resources: [{ name: 'SHEET_test_PLUGIN', data: '{"a":123}' }],
});
export const createTestBed = (dependencies?: Dependency[]) => {
@@ -59,9 +59,6 @@ export const createTestBed = (dependencies?: Dependency[]) => {
@Inject(Injector) override readonly _injector: Injector
) {
super();
- }
-
- override onStarting(): void {
dependencies?.forEach((d) => this._injector.add(d));
}
}
diff --git a/packages/core/src/services/__tests__/resources.spec.ts b/packages/core/src/services/__tests__/resources.spec.ts
new file mode 100644
index 0000000000..17d468e1b9
--- /dev/null
+++ b/packages/core/src/services/__tests__/resources.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { beforeEach, describe, expect, it } from 'vitest';
+import { IResourceLoaderService } from '../resource-loader/type';
+import { IResourceManagerService } from '../resource-manager/type';
+import type { Univer } from '../../univer';
+import { UniverInstanceType } from '../../common/unit';
+import { createTestBed } from './index';
+
+describe('Test resources service', () => {
+ let univer: Univer;
+
+ beforeEach(() => {
+ univer?.dispose();
+ const instance = createTestBed();
+ univer = instance.univer;
+ });
+
+ it('test register resources', () => {
+ const resourceManagerService = univer.__getInjector().get(IResourceManagerService);
+ const resourceLoaderService = univer.__getInjector().get(IResourceLoaderService);
+ const pluginName = 'SHEET_test_PLUGIN';
+ const model: Record<string, any> = {};
+ resourceManagerService.registerPluginResource({
+ pluginName,
+ businesses: [UniverInstanceType.UNIVER_SHEET],
+ onLoad: () => { },
+ onUnLoad: () => { },
+ toJson: () => JSON.stringify(model),
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+ const snapshot = resourceLoaderService.saveUnit('test');
+ const resource = snapshot?.resources.find((item) => item.name === pluginName);
+ expect(!!resource).toBeTruthy();
+ expect(resource?.data).toBe(JSON.stringify(model));
+ // update model
+ model.a = 123;
+ const snapshotRev1 = resourceLoaderService.saveUnit('test');
+ const resourceRev1 = snapshotRev1?.resources.find((item) => item.name === pluginName);
+ expect(resourceRev1?.data).toBe(JSON.stringify(model));
+ });
+
+ it('test resources load', () => {
+ const resourceManagerService = univer.__getInjector().get(IResourceManagerService);
+ const pluginName = 'SHEET_test_PLUGIN';
+ const model: Record<string, any> = {};
+ let result = '';
+ resourceManagerService.registerPluginResource({
+ pluginName,
+ businesses: [UniverInstanceType.UNIVER_SHEET],
+ onLoad: (v, r) => { result = r; },
+ onUnLoad: () => { },
+ toJson: () => JSON.stringify(model),
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+ // The value in the snapshot
+ expect(result).toEqual({ a: 123 });
+ });
+});
diff --git a/packages/core/src/services/resource-loader/resource-loader.service.ts b/packages/core/src/services/resource-loader/resource-loader.service.ts
index 05edda2e1e..24c877a69f 100644
--- a/packages/core/src/services/resource-loader/resource-loader.service.ts
+++ b/packages/core/src/services/resource-loader/resource-loader.service.ts
@@ -23,7 +23,7 @@ import { Disposable } from '../../shared/lifecycle';
import { UniverInstanceType } from '../../common/unit';
import type { DocumentDataModel } from '../../docs';
import { isInternalEditorID } from '../../common/const';
-import type { IWorkbookData } from '../../sheets/typedef';
+import { Tools } from '../../shared';
import type { IResourceLoaderService } from './type';
export class ResourceLoaderService extends Disposable implements IResourceLoaderService {
@@ -109,19 +109,14 @@ export class ResourceLoaderService extends Disposable implements IResourceLoader
);
}
- saveWorkbook: (workbook: Workbook) => IWorkbookData = (workbook) => {
- const unitId = workbook.getUnitId();
- const resources = this._resourceManagerService.getResources(unitId, UniverInstanceType.UNIVER_SHEET);
- const snapshot = workbook.getSnapshot();
+ saveUnit<T = object>(unitId: string) {
+ const unit = this._univerInstanceService.getUnit(unitId);
+ if (!unit) {
+ return null;
+ }
+ const resources = this._resourceManagerService.getResources(unitId, unit.type);
+ const snapshot = Tools.deepClone(unit.getSnapshot()) as { resources: typeof resources } & T;
snapshot.resources = resources;
return snapshot;
- };
-
- saveDoc(doc: DocumentDataModel) {
- const unitId = doc.getUnitId();
- const resources = this._resourceManagerService.getResources(unitId, UniverInstanceType.UNIVER_DOC);
- const snapshot = doc.getSnapshot();
- snapshot.resources = resources;
- return snapshot;
- };
+ }
}
diff --git a/packages/core/src/services/resource-loader/type.ts b/packages/core/src/services/resource-loader/type.ts
index 5b01b85475..612906b94e 100644
--- a/packages/core/src/services/resource-loader/type.ts
+++ b/packages/core/src/services/resource-loader/type.ts
@@ -15,15 +15,11 @@
*/
import { createIdentifier } from '../../common/di';
-import type { Workbook } from '../../sheets/workbook';
import { LifecycleStages, runOnLifecycle } from '../lifecycle/lifecycle';
-import type { IDocumentData } from '../../types/interfaces';
-import type { DocumentDataModel } from '../../docs';
-import type { IWorkbookData } from '../../sheets/typedef';
+import type { IResources } from '../resource-manager/type';
export interface IResourceLoaderService {
- saveWorkbook: (workbook: Workbook) => IWorkbookData;
- saveDoc: (doc: DocumentDataModel) => IDocumentData;
+ saveUnit<T = object>(unitId: string): T & { resources: IResources } | null;
}
export const IResourceLoaderService = createIdentifier<IResourceLoaderService>('resource-loader-service');
runOnLifecycle(LifecycleStages.Ready, IResourceLoaderService);
diff --git a/packages/core/src/services/resource-manager/resource-manager.service.ts b/packages/core/src/services/resource-manager/resource-manager.service.ts
index 6f1d64ef50..31faf391d7 100644
--- a/packages/core/src/services/resource-manager/resource-manager.service.ts
+++ b/packages/core/src/services/resource-manager/resource-manager.service.ts
@@ -17,7 +17,7 @@
import { Subject } from 'rxjs';
import { Disposable, toDisposable } from '../../shared/lifecycle';
import type { UniverInstanceType } from '../../common/unit';
-import type { Resources } from '../../types/interfaces/resource';
+import type { IResources } from '../resource-manager/type';
import type { IResourceHook, IResourceManagerService, IResourceName } from './type';
export class ResourceManagerService extends Disposable implements IResourceManagerService {
@@ -31,9 +31,9 @@ export class ResourceManagerService extends Disposable implements IResourceManag
return list;
}
- public getResources(unitId: string): Resources;
- public getResources(unitId: string, type: UniverInstanceType): Resources;
- public getResources(unitId: string, type?: UniverInstanceType): Resources {
+ public getResources(unitId: string): IResources;
+ public getResources(unitId: string, type: UniverInstanceType): IResources;
+ public getResources(unitId: string, type?: UniverInstanceType): IResources {
if (type) {
return this.getResourcesByType(unitId, type);
}
@@ -75,7 +75,7 @@ export class ResourceManagerService extends Disposable implements IResourceManag
this._resourceMap.delete(pluginName);
}
- public loadResources(unitId: string, resources?: Resources) {
+ public loadResources(unitId: string, resources?: IResources) {
this.getAllResourceHooks().forEach((hook) => {
const data = resources?.find((resource) => resource.name === hook.pluginName)?.data;
if (data) {
diff --git a/packages/core/src/services/resource-manager/type.ts b/packages/core/src/services/resource-manager/type.ts
index 9bae32b3c5..45589d9230 100644
--- a/packages/core/src/services/resource-manager/type.ts
+++ b/packages/core/src/services/resource-manager/type.ts
@@ -18,7 +18,8 @@ import type { Observable } from 'rxjs';
import type { UniverInstanceType } from '@univerjs/core';
import type { IDisposable } from '../../common/di';
import { createIdentifier } from '../../common/di';
-import type { Resources } from '../../types/interfaces/resource';
+
+export type IResources = Array<{ id?: string; name: string; data: string }>;
type IBusinessName = 'SHEET' | 'DOC';
export type IResourceName = `${IBusinessName}_${string}_PLUGIN`;
@@ -40,10 +41,10 @@ export interface IResourceManagerService {
/**
* @deprecated You should get resource with type specified.
*/
- getResources(unitId: string): Resources;
- getResources(unitId: string, type: UniverInstanceType): Resources;
- getResourcesByType: (unitId: string, type: UniverInstanceType) => Resources;
- loadResources: (unitId: string, resources?: Resources) => void;
+ getResources(unitId: string): IResources;
+ getResources(unitId: string, type: UniverInstanceType): IResources;
+ getResourcesByType: (unitId: string, type: UniverInstanceType) => IResources;
+ loadResources: (unitId: string, resources?: IResources) => void;
unloadResources(unitId: string): void;
}
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index 779cd3f6aa..b5fdfebbb9 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -16,7 +16,7 @@
import type { LocaleType } from '../types/enum/locale-type';
import type { IStyleData } from '../types/interfaces/i-style-data';
-import type { Resources } from '../types/interfaces/resource';
+import type { IResources } from '../services/resource-manager/type';
import type { IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType, Nullable } from '../shared';
import { type BooleanNumber, CellValueType } from '../types/enum';
import type { IDocumentData } from '../types/interfaces';
@@ -69,7 +69,7 @@ export interface IWorkbookData {
/**
* Resources of the Univer Sheet. It is used to store the data of other plugins.
*/
- resources?: Resources;
+ resources?: IResources;
}
/**
diff --git a/packages/core/src/types/interfaces/resource.ts b/packages/core/src/types/interfaces/resource.ts
deleted file mode 100644
index 498951fa67..0000000000
--- a/packages/core/src/types/interfaces/resource.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 Resources = Array<{ id?: string; name: string; data: string }>;
diff --git a/packages/debugger/src/commands/operations/save-snapshot.operations.ts b/packages/debugger/src/commands/operations/save-snapshot.operations.ts
index 7d7d68e487..34da7f5982 100644
--- a/packages/debugger/src/commands/operations/save-snapshot.operations.ts
+++ b/packages/debugger/src/commands/operations/save-snapshot.operations.ts
@@ -54,11 +54,10 @@ export const SaveSnapshotOptions: ICommand = {
const gitBranch = process.env.GIT_REF_NAME;
const buildTime = process.env.BUILD_TIME;
const preName = new Date().toLocaleString();
-
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
if (!workbook) {
const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
- const snapshot = resourceLoaderService.saveDoc(doc);
+ const snapshot = resourceLoaderService.saveUnit(doc.getUnitId());
(snapshot as any).__env__ = { gitHash, gitBranch, buildTime };
const text = JSON.stringify(snapshot, null, 2);
exportController.exportJson(text, `${preName} snapshot`);
@@ -69,7 +68,7 @@ export const SaveSnapshotOptions: ICommand = {
if (!worksheet) {
return false;
}
- const snapshot = resourceLoaderService.saveWorkbook(workbook);
+ const snapshot = resourceLoaderService.saveUnit<ReturnType<typeof workbook.getSnapshot>>(workbook.getUnitId())!;
(snapshot as any).__env__ = { gitHash, gitBranch, buildTime };
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index acdb90c203..8d6f665c97 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -16,7 +16,7 @@
/* eslint-disable max-lines-per-function */
-import type { Dependency, IWorkbookData, UnitModel, Workbook } from '@univerjs/core';
+import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
import {
ILogService,
Inject,
@@ -114,7 +114,7 @@ function getTestWorkbookDataDemo(): IWorkbookData {
export interface ITestBed {
univer: Univer;
get: Injector['get'];
- sheet: UnitModel<Workbook>;
+ sheet: UnitModel<IWorkbookData>;
univerAPI: FUniver;
injector: Injector;
}
@@ -206,7 +206,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
univer.registerPlugin(UniverSheetsFilterPlugin);
univer.registerPlugin(UniverDataValidationPlugin);
- const sheet = univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());
+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());
const univerInstanceService = injector.get(IUniverInstanceService);
univerInstanceService.focusUnit('test');
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
index de4045c911..90d2d2d616 100644
--- a/packages/facade/src/apis/__tests__/facade.spec.ts
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -274,7 +274,7 @@ describe('Test FUniver', () => {
});
it('Function getSnapshot', () => {
- const snapshot = univerAPI.getActiveWorkbook()?.getSnapshot();
+ const snapshot = univerAPI.getActiveWorkbook()?.save();
expect(snapshot?.resources).toEqual([
{
data: '{}',
diff --git a/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts
index d4ad76b596..f4c9c08877 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, Injector, IStyleData, Nullable, UnitModel, Workbook } from '@univerjs/core';
+import type { ICellData, Injector, IStyleData, Nullable, Workbook } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -22,7 +22,6 @@ import { Subject } from 'rxjs';
import type { IDragCellPosition, IHoverCellPosition } from '@univerjs/sheets-ui';
import { DragManagerService, HoverManagerService } from '@univerjs/sheets-ui';
-import type { FUniver } from '../../facade';
import { createFacadeTestBed } from '../../__tests__/create-test-bed';
import { FSheetHooks } from '../f-sheet-hooks';
@@ -53,8 +52,6 @@ describe('Test FSheetHooks', () => {
let get: Injector['get'];
let injector: Injector;
let commandService: ICommandService;
- let univerAPI: FUniver;
- let sheet: UnitModel<Workbook>;
let getValueByPosition: (
startRow: number,
startColumn: number,
@@ -101,8 +98,6 @@ describe('Test FSheetHooks', () => {
]);
get = testBed.get;
injector = testBed.injector;
- univerAPI = testBed.univerAPI;
- sheet = testBed.sheet;
workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
commandService = get(ICommandService);
diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts
index 819cdab308..ca4c836f64 100644
--- a/packages/facade/src/apis/sheets/f-workbook.ts
+++ b/packages/facade/src/apis/sheets/f-workbook.ts
@@ -62,10 +62,10 @@ export class FWorkbook {
}
/**
- * Returns workbook snapshot data, including conditional formatting, data validation, and other plugin data.
+ * save workbook snapshot data, including conditional formatting, data validation, and other plugin data.
*/
- getSnapshot(): IWorkbookData {
- const snapshot = this._resourceLoaderService.saveWorkbook(this._workbook);
+ save(): IWorkbookData {
+ const snapshot = this._resourceLoaderService.saveUnit<IWorkbookData>(this._workbook.getUnitId())!;
return snapshot;
}
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index 90f1d382cb..bfa3af2ffe 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -877,7 +877,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
worksheet.getCellRaw(row, column) || {},
documentLayoutObject,
this._lexerTreeBuilder,
- (model) => this._resourceLoaderService.saveDoc(model),
+ (model) => this._resourceLoaderService.saveUnit(model.getUnitId())!,
this._localService,
this._functionService
);