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(sheet): alias ref (#556)

Gpound.liuc43e9a91783d
diff --git a/packages/core/src/shared/__test__/ref-alias.spec.ts b/packages/core/src/shared/__test__/ref-alias.spec.ts
new file mode 100644
index 0000000000..45fbd36bc6
--- /dev/null
+++ b/packages/core/src/shared/__test__/ref-alias.spec.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+
+import { RefAlias } from '../ref-alias';
+
+const createInstance = () =>
+ new RefAlias<{ a: string; b: string; c: string; d: string }, 'a' | 'c'>(
+ [
+ { a: 'aa', b: 'bb', c: 'cc', d: 'dd' },
+ { a: 'aaa', b: 'bbb', c: 'ccc', d: 'ddd' },
+ { a: 'aaaa', b: 'bbbb', c: 'cccc', d: 'dddd' },
+ { a: 'aaaaa', b: 'bbbbb', c: 'ccccc', d: 'ddddd' },
+ ],
+ ['a', 'c']
+ );
+describe('test for RefAlias', () => {
+ it('test getValue ', () => {
+ const instance = createInstance();
+ expect(instance.getValue('aa')).toEqual({ a: 'aa', b: 'bb', c: 'cc', d: 'dd' });
+ expect(instance.getValue('aas')).toEqual(null);
+ });
+ it('test hasValue ', () => {
+ const instance = createInstance();
+ expect(instance.hasValue('aa')).toBe(true);
+ expect(instance.hasValue('aas')).toBe(false);
+ });
+
+ it('test setValue ', () => {
+ const instance = createInstance();
+ instance.setValue('aa', 'c', 'abc');
+ expect(instance.getValue('aa')).toEqual({ a: 'aa', b: 'bb', c: 'abc', d: 'dd' });
+ });
+ it('test deleteValue ', () => {
+ const instance = createInstance();
+ instance.deleteValue('aa');
+ expect(instance.getValue('aa')).toEqual(null);
+ expect(instance.getKeyMap('a').length).toBe(3);
+ expect(instance.getKeyMap('c').length).toBe(3);
+ expect(instance.getKeyMap('b' as any).length).toBe(0);
+ instance.deleteValue('aaa');
+ instance.deleteValue('aaaa');
+ instance.deleteValue('aaaaa');
+ expect(instance.getKeyMap('a').length).toBe(0);
+ });
+
+ it('test ref is keepalive', () => {
+ const instance = createInstance();
+ const aa = instance.getValue('aa');
+ instance.setValue('aa', 'c', 'aaaa');
+ expect(instance.getValue('aa')).toEqual({ a: 'aa', b: 'bb', c: 'aaaa', d: 'dd' });
+ expect(instance.getValue('aa')).toBe(aa);
+ });
+
+ it('test addValue', () => {
+ const instance = createInstance();
+ instance.addValue({ a: 'asa', b: 'bsb', c: 'csc', d: 'dsd' });
+ const aa = instance.getValue('asa');
+ expect(aa).toEqual({ a: 'asa', b: 'bsb', c: 'csc', d: 'dsd' });
+ expect(instance.getValues().length).toBe(5);
+ expect(instance.getKeyMap('a').length).toBe(5);
+ });
+
+ it('test clear', () => {
+ const instance = createInstance();
+ instance.clear();
+ expect(instance.getValues().length).toBe(0);
+ expect(instance.getKeyMap('a').length).toBe(0);
+ expect(instance.getKeyMap('c').length).toBe(0);
+ });
+
+ it('test toJson', () => {
+ const instance = createInstance();
+ const values = [...instance.getValues()];
+ const newInstance = new RefAlias(values, ['a', 'c']);
+ expect(newInstance.getKeyMap('a')).toEqual(instance.getKeyMap('a'));
+ expect(newInstance.getKeyMap('c')).toEqual(instance.getKeyMap('c'));
+
+ newInstance.deleteValue('aa');
+ instance.deleteValue('aa');
+ expect(newInstance.getValue('aa')).toEqual(instance.getValue('aa'));
+ expect(newInstance.getValues()).toEqual(instance.getValues());
+ });
+});
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index 7ab699b409..ddaad16195 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -23,6 +23,7 @@ export * from './object-matrix';
export * from './permission';
export * from './random';
export * from './rectangle';
+export { RefAlias } from './ref-alias';
export * from './row-col-iter';
export * from './sequence';
export * from './serialize/index';
diff --git a/packages/core/src/shared/ref-alias.ts b/packages/core/src/shared/ref-alias.ts
new file mode 100644
index 0000000000..4a5ac8723f
--- /dev/null
+++ b/packages/core/src/shared/ref-alias.ts
@@ -0,0 +1,93 @@
+/**
+ * Enter an object, indexed by the keys in the object
+ * example:
+ * object a is {a:'a',b:'b',c:'c'}
+ * object b is {a:'aa',b:'bb',c:'cc'}
+ * object b is {a:'aaa',b:'bbb',c:'ccc'}
+ * const model = new RefAlias([a,b,c],['a','b']) // the index is 'a' and 'b'.
+ * we can use model.getValue('aa') or model.getValue('bb') get the object b
+ * but can't use model.getValue('cc') to get the object b ,because model([a,b,c],['a','b']) is not set 'c' in the second parameter array
+ */
+export class RefAlias<T extends Record<string, unknown>, K extends keyof T = keyof T> {
+ private _values: T[] = [];
+ private _keys: K[] = [];
+ private _keyMaps: Map<keyof T, Map<unknown, T>> = new Map();
+
+ constructor(values: T[], keys: K[]) {
+ this._values = values;
+ this._keys = keys;
+ values.forEach((item) => {
+ this._initKeyMap(item);
+ });
+ }
+
+ _initKeyMap(item: T) {
+ this._keys.forEach((key) => {
+ const value = item[key];
+ const keyMap = this._keyMaps.get(key) || new Map();
+ keyMap.set(value, item);
+ this._keyMaps.set(key, keyMap);
+ });
+ }
+
+ getValue(key: string) {
+ for (let index = 0; index < this._keys.length; index++) {
+ const keyMap = this._keyMaps.get(this._keys[index]);
+ if (keyMap?.has(key)) {
+ return keyMap.get(key);
+ }
+ }
+ return null;
+ }
+
+ hasValue(key: string) {
+ for (let index = 0; index < this._keys.length; index++) {
+ const keyMap = this._keyMaps.get(this._keys[index]);
+ if (keyMap?.has(key)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ addValue(item: T) {
+ this._values.push(item);
+ this._initKeyMap(item);
+ }
+
+ setValue(key: string, attr: keyof T, value: unknown) {
+ const item = this.getValue(key);
+ if (item) {
+ if (Object.keys(item).includes(attr as string)) {
+ item[attr] = value as T[keyof T];
+ }
+ }
+ }
+
+ deleteValue(key: string) {
+ const value = this.getValue(key);
+ if (value) {
+ this._keys.forEach((keyItem) => {
+ const keyMap = this._keyMaps.get(keyItem);
+ const _key = value[keyItem];
+ keyMap?.delete(_key);
+ });
+ const index = this._values.findIndex((item) => item === value);
+ this._values.splice(index, 1);
+ }
+ }
+
+ getValues() {
+ return this._values;
+ }
+
+ getKeyMap(key: K) {
+ return [...(this._keyMaps.get(key)?.keys() || [])];
+ }
+
+ clear() {
+ this._values = [];
+ this._keys = [];
+ this._keyMaps.clear();
+ }
+}
diff --git a/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts b/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts
index e441164372..66a28c698e 100644
--- a/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts
+++ b/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts
@@ -15,7 +15,10 @@ export const factorySetNumfmtUndoMutation = (
.map((item) => {
const { row, col } = item;
const oldValue = numfmtService.getValue(option.workbookId, option.worksheetId, row, col);
- return { pattern: oldValue?.pattern, type: oldValue?.type, row, col };
+ if (oldValue) {
+ return { pattern: oldValue.pattern, type: oldValue.type, row, col };
+ }
+ return { row, col };
})
.reverse(),
};
@@ -39,10 +42,11 @@ export const SetNumfmtMutation: ICommand<SetNumfmtMutationParams> = {
const numfmtService = accessor.get(INumfmtService);
const workbookId = params.workbookId;
const sheetId = params.worksheetId;
- values.forEach((item) => {
- const value = item.pattern ? { pattern: item.pattern!, type: item.type! } : null;
- numfmtService.setValue(workbookId, sheetId, Number(item.row), Number(item.col), value);
- });
+ numfmtService.setValues(
+ workbookId,
+ sheetId,
+ values.map((item) => ({ ...item, type: item.type! }))
+ );
return true;
},
};
diff --git a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts b/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
index 777f733f47..e673938942 100644
--- a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
+++ b/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
@@ -1,29 +1,62 @@
-import { Disposable, ICommandService, Nullable, ObjectMatrix } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ LifecycleStages,
+ Nullable,
+ ObjectMatrix,
+ OnLifecycle,
+ RefAlias,
+ toDisposable,
+} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { NumfmtItem } from '../base/types';
import { SetNumfmtMutation } from '../commands/mutations/set.numfmt.mutation';
import type { INumfmtService, NumfmtItemWithCache } from './type';
+@OnLifecycle(LifecycleStages.Ready, NumfmtService)
export class NumfmtService extends Disposable implements INumfmtService {
- numfmtModel: Map<string, ObjectMatrix<NumfmtItemWithCache>> = new Map();
- // collect effect mutations when edit end and push this to commands stack in next commands progress
+ _numfmtModel: Map<string, ObjectMatrix<NumfmtItemWithCache>> = new Map();
+
+ _refAliasModel = new RefAlias<{ count: number; numfmtId: string; pattern: string }>([], ['pattern', 'numfmtId']);
constructor(@Inject(ICommandService) private _commandService: ICommandService) {
super();
+ this._initModel();
this._initCommands();
+ this.disposeWithMe(
+ toDisposable(() => {
+ this._numfmtModel.clear();
+ this._refAliasModel.clear();
+ })
+ );
+ }
+
+ private _initModel() {
+ // todo init model after resource-plugin finished.
}
private _initCommands() {
[SetNumfmtMutation].forEach((config) => this.disposeWithMe(this._commandService.registerCommand(config)));
}
- getValue(workbookId: string, worksheetId: string, row: number, col: number) {
- const model = this.getModel(workbookId, worksheetId);
- if (!model) {
+ getValue(
+ workbookId: string,
+ worksheetId: string,
+ row: number,
+ col: number,
+ model?: ObjectMatrix<NumfmtItemWithCache>
+ ) {
+ const _model: Nullable<ObjectMatrix<NumfmtItemWithCache>> = model || this.getModel(workbookId, worksheetId);
+ if (!_model) {
return null;
}
- return model.getValue(row, col);
+ const value = _model.getValue(row, col);
+ if (value) {
+ const realPattern = this._refAliasModel.getValue(value?.pattern)?.pattern || value?.pattern;
+ return value ? { ...value, pattern: realPattern } : null;
+ }
+ return null;
}
setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) {
@@ -31,7 +64,7 @@ export class NumfmtService extends Disposable implements INumfmtService {
if (!model) {
const key = getModelKey(workbookId, worksheetId);
model = new ObjectMatrix();
- this.numfmtModel.set(key, model);
+ this._numfmtModel.set(key, model);
}
if (value) {
model.setValue(row, col, value);
@@ -40,9 +73,101 @@ export class NumfmtService extends Disposable implements INumfmtService {
}
}
+ setValues(
+ workbookId: string,
+ worksheetId: string,
+ values: Array<{ row: number; col: number; pattern?: string; type: NumfmtItem['type'] }>
+ ) {
+ const ___delete___ = '___delete___';
+ const group = this._groupByKey(values, 'pattern', ___delete___);
+ const model = this.getModel(workbookId, worksheetId);
+ Object.keys(group).forEach((pattern: string) => {
+ const values = group[pattern];
+ const length = values.length;
+ if (!length) {
+ return;
+ }
+ let refPattern = this._refAliasModel.getValue(pattern);
+ if (pattern === ___delete___) {
+ values.forEach((item) => {
+ const { row, col } = item;
+ const oldValue = this.getValue(workbookId, worksheetId, row, col, model);
+ if (oldValue && oldValue.pattern) {
+ const oldRefPattern = this._refAliasModel.getValue(oldValue.pattern);
+ if (oldRefPattern) {
+ oldRefPattern.count--;
+ // if (oldRefPattern.count <= 0) {
+ // this._refAliasModel.deleteValue(oldValue.pattern);
+ // }
+ }
+ }
+ this.setValue(workbookId, worksheetId, row, col, null);
+ });
+ if (refPattern) {
+ const count = refPattern.count - length;
+ if (count > 0) {
+ this._refAliasModel.setValue(pattern, 'count', count);
+ }
+ //else {
+ // this._refAliasModel.deleteValue(pattern);
+ // }
+ }
+ } else {
+ if (!refPattern) {
+ refPattern = { count: 0, numfmtId: this._getUniqueRefId(), pattern };
+ this._refAliasModel.addValue(refPattern);
+ }
+ values.forEach((item) => {
+ const { row, col, type } = item;
+ if (model) {
+ const oldValue = this.getValue(workbookId, worksheetId, row, col, model);
+ if (oldValue && oldValue.pattern) {
+ const oldRefPattern = this._refAliasModel.getValue(oldValue.pattern);
+ if (oldRefPattern) {
+ oldRefPattern.count--;
+ // if (oldRefPattern.count <= 0) {
+ // this._refAliasModel.deleteValue(oldValue.pattern);
+ // }
+ }
+ }
+ }
+ this.setValue(workbookId, worksheetId, row, col, {
+ pattern: refPattern?.numfmtId || pattern!,
+ type,
+ });
+ refPattern!.count++;
+ });
+ }
+ });
+ }
+
+ _groupByKey<T = Record<string, unknown>>(arr: T[], key: string, blankKey = '') {
+ return arr.reduce(
+ (result, current) => {
+ const pattern = current && ((current as Record<string, unknown>)[key] as string);
+ if (pattern) {
+ if (!result[pattern]) {
+ result[pattern] = [];
+ }
+ result[pattern].push(current);
+ } else {
+ result[blankKey].push(current);
+ }
+ return result;
+ },
+ { [blankKey]: [] } as Record<string, T[]>
+ );
+ }
+
+ _getUniqueRefId() {
+ const keyList = this._refAliasModel.getKeyMap('numfmtId') as string[];
+ const maxId = Math.max(...keyList.map(Number), 0);
+ return `${maxId + 1}`;
+ }
+
getModel(workbookId: string, worksheetId: string) {
const key = getModelKey(workbookId, worksheetId);
- return this.numfmtModel.get(key);
+ return this._numfmtModel.get(key);
}
}