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
style(core): eslint member ordering
Dushusir58b8d409ff68
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 963b462357..303664bba9 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -4,7 +4,7 @@"editor.codeActionsOnSave": {"source.fixAll.eslint": true},- "editor.defaultFormatter": "esbenp.prettier-vscode",+ // "editor.defaultFormatter": "esbenp.prettier-vscode","commentTranslate.targetLanguage": "zh-CN","[html]": {"editor.defaultFormatter": "vscode.html-language-features"diff --git a/packages/core/src/Basics/SlideContext.ts b/packages/core/src/Basics/SlideContext.tsindex 189cd3e561..6dd52c8338 100644--- a/packages/core/src/Basics/SlideContext.ts+++ b/packages/core/src/Basics/SlideContext.ts@@ -13,9 +13,9 @@ export class SlideContext extends ContextBase {this._slide = new SlideModel(univerSlideData, this);}- protected _setObserver(): void {}-getSlide(): SlideModel {return this._slide;}++ protected _setObserver(): void {}}diff --git a/packages/core/src/Basics/UniverDoc.ts b/packages/core/src/Basics/UniverDoc.tsindex 770ced77f7..1458fcc88d 100644--- a/packages/core/src/Basics/UniverDoc.ts+++ b/packages/core/src/Basics/UniverDoc.ts@@ -10,11 +10,20 @@ import { VersionCode, VersionEnv } from './Version';export class UniverDoc {univerDocConfig: Partial<IDocumentData>;+ private _context: DocContext;+constructor(UniverDocData: Partial<IDocumentData> = {}) {this.univerDocConfig = UniverDocData;this._context = new DocContext(UniverDocData);}+ /**+ * get DocContext+ */+ get context() {+ return this._context;+ }+static newInstance(UniverDocData: Partial<IDocumentData> = {}): UniverDoc {Logger.capsule(VersionEnv, VersionCode, 'powered by :: UniverDoc :: ');return new UniverDoc(UniverDocData);@@ -41,15 +50,6 @@ export class UniverDoc {return IOHttp({ ...config, type: 'POST' });}- private _context: DocContext;-- /**- * get DocContext- */- get context() {- return this._context;- }-/*** get unit id*/diff --git a/packages/core/src/Basics/UniverSheet.ts b/packages/core/src/Basics/UniverSheet.tsindex 3d1097aa75..8d23fb4172 100644--- a/packages/core/src/Basics/UniverSheet.ts+++ b/packages/core/src/Basics/UniverSheet.ts@@ -9,15 +9,22 @@ import { VersionCode, VersionEnv } from './Version';* Externally provided UniverSheet root instance*/export class UniverSheet {- private _context: SheetContext;-univerSheetConfig: Partial<IWorkbookConfig>;+ private _context: SheetContext;+constructor(univerSheetData: Partial<IWorkbookConfig> = {}) {this.univerSheetConfig = univerSheetData;this._context = new SheetContext(univerSheetData);}+ /**+ * get SheetContext+ */+ get context() {+ return this._context;+ }+static newInstance(univerSheetData: Partial<IWorkbookConfig> = {}): UniverSheet {Logger.capsule(VersionEnv, VersionCode, 'powered by :: universheet :: ');return new UniverSheet(univerSheetData);@@ -71,10 +78,24 @@ export class UniverSheet {}/**- * get SheetContext+ * Save data+ *+ * @example+ * get all the core and plug-in data+ *+ * @param univerSheet*/- get context() {- return this._context;+ static toJson(univerSheet: UniverSheet) {+ const workbookConfig = univerSheet.getWorkBook().save();+ const pluginConfig = {};+ univerSheet.context+ .getPluginManager()+ .getPlugins()+ .forEach((plugin: BasePlugin) => {+ pluginConfig[`${plugin.getPluginName()}Config`] = plugin.save();+ });++ return { workbookConfig, ...pluginConfig };}/**@@ -111,27 +132,6 @@ export class UniverSheet {return this._context.getWorkBook();}- /**- * Save data- *- * @example- * get all the core and plug-in data- *- * @param univerSheet- */- static toJson(univerSheet: UniverSheet) {- const workbookConfig = univerSheet.getWorkBook().save();- const pluginConfig = {};- univerSheet.context- .getPluginManager()- .getPlugins()- .forEach((plugin: BasePlugin) => {- pluginConfig[`${plugin.getPluginName()}Config`] = plugin.save();- });-- return { workbookConfig, ...pluginConfig };- }-refreshWorkbook(univerSheetData: Partial<IWorkbookConfig> = {}) {this._context.refreshWorkbook(univerSheetData);}diff --git a/packages/core/src/Basics/UniverSlide.ts b/packages/core/src/Basics/UniverSlide.tsindex a2844197d5..b9d2b3609e 100644--- a/packages/core/src/Basics/UniverSlide.ts+++ b/packages/core/src/Basics/UniverSlide.ts@@ -11,11 +11,20 @@ import { ColorBuilder } from '../Sheets/Domain/ColorBuilder';export class UniverSlide {UniverSlideConfig: Partial<ISlideData>;+ private _context: SlideContext;+constructor(UniverSlideData: Partial<ISlideData> = {}) {this.UniverSlideConfig = UniverSlideData;this._context = new SlideContext(UniverSlideData);}+ /**+ * get SlideContext+ */+ get context() {+ return this._context;+ }+static newInstance(UniverSlideData: Partial<ISlideData> = {}): UniverSlide {Logger.capsule(VersionEnv, VersionCode, 'powered by :: UniverSlide :: ');return new UniverSlide(UniverSlideData);@@ -46,15 +55,6 @@ export class UniverSlide {return new ColorBuilder();}- private _context: SlideContext;-- /**- * get SlideContext- */- get context() {- return this._context;- }-/*** install plugin*diff --git a/packages/core/src/Command/ActionBase.ts b/packages/core/src/Command/ActionBase.tsindex 7ba5fd8ca7..9fcac6544b 100644--- a/packages/core/src/Command/ActionBase.ts+++ b/packages/core/src/Command/ActionBase.ts@@ -63,14 +63,6 @@ export abstract class ActionBase<this._operation = ActionOperationType.OBSERVER_ACTION;}- abstract redo(): void;-- abstract undo(): void;-- abstract do(): R;-- abstract validate(): boolean;-getDoActionData() {return this._doActionData;}@@ -90,4 +82,12 @@ export abstract class ActionBase<removeOperation(operation: ActionOperationType) {this._operation &= ~operation;}++ abstract redo(): void;++ abstract undo(): void;++ abstract do(): R;++ abstract validate(): boolean;}diff --git a/packages/core/src/Command/ActionExtensionManager.ts b/packages/core/src/Command/ActionExtensionManager.tsindex 48c851a20b..1f0aa5ba82 100644--- a/packages/core/src/Command/ActionExtensionManager.ts+++ b/packages/core/src/Command/ActionExtensionManager.ts@@ -5,18 +5,18 @@ import { ActionExtensionRegister } from './ActionExtensionRegister';export class ActionExtensionManager {private _actionExtensionFactoryList: BaseActionExtensionFactory[];- // 挂载到实例上+ // mounted on the instanceprivate _register: ActionExtensionRegister;- getRegister(): ActionExtensionRegister {- return this._register;- }-constructor() {this._register = new ActionExtensionRegister();this._register.initialize();}+ getRegister(): ActionExtensionRegister {+ return this._register;+ }+/*** inject all actions* @param commanddiff --git a/packages/core/src/Command/ActionOperation.ts b/packages/core/src/Command/ActionOperation.tsindex 045fe021b7..d7ae8331e4 100644--- a/packages/core/src/Command/ActionOperation.ts+++ b/packages/core/src/Command/ActionOperation.ts@@ -3,6 +3,10 @@ import { ActionOperationType, IActionData } from './ActionBase';export class ActionOperation<T extends IActionData> {protected _action: T;+ protected constructor(action: T) {+ this._action = action;+ }+static hasObserver<U extends IActionData>(action: U): boolean {if (action.operation) {return (@@ -48,10 +52,6 @@ export class ActionOperation<T extends IActionData> {return new ActionOperation<U>(action);}- protected constructor(action: T) {- this._action = action;- }-removeObserver() {if (this._action.operation) {this._action.operation &= ~ActionOperationType.OBSERVER_ACTION;diff --git a/packages/core/src/Command/CommandManager.ts b/packages/core/src/Command/CommandManager.tsindex a5f74390b5..ab2cfbacc9 100644--- a/packages/core/src/Command/CommandManager.ts+++ b/packages/core/src/Command/CommandManager.ts@@ -25,10 +25,6 @@ export class CommandManager {private _actionExtensionManager: ActionExtensionManager;- getActionExtensionManager(): ActionExtensionManager {- return this._actionExtensionManager;- }-constructor(context: ContextBase) {this._undoManager = context.getUndoManager();this._actionExtensionManager = new ActionExtensionManager();@@ -61,6 +57,10 @@ export class CommandManager {return this._commandInjectorObservers;}+ getActionExtensionManager(): ActionExtensionManager {+ return this._actionExtensionManager;+ }+undo(): void {const { _undoManager } = this;// const server = _workbook.getServer();diff --git a/packages/core/src/Command/RegistryFactory.ts b/packages/core/src/Command/RegistryFactory.tsindex a01f349c09..7385a0634f 100644--- a/packages/core/src/Command/RegistryFactory.ts+++ b/packages/core/src/Command/RegistryFactory.ts@@ -2,6 +2,10 @@class Registry {private _data: any[] = [];+ static create() {+ return new Registry();+ }+add(dataInstance: any) {this._data.push(dataInstance);}@@ -14,10 +18,6 @@ class Registry {getData() {return this._data;}-- static create() {- return new Registry();- }}export const REGISTRY_ACTION_FACTORY = Registry.create();diff --git a/packages/core/src/Const/THEME_COLOR_MAP.ts b/packages/core/src/Const/THEME_COLOR_MAP.tsindex 268dbf4e80..c99944a37a 100644--- a/packages/core/src/Const/THEME_COLOR_MAP.ts+++ b/packages/core/src/Const/THEME_COLOR_MAP.ts@@ -14,5 +14,5 @@ export const THEME_COLORS = {[ThemeColorType.LIGHT2]: '#E7E6E6',[ThemeColorType.HYPERLINK]: '#0563C1',[ThemeColorType.FOLLOWED_HYPERLINK]: '#954F72',- }-}+ },+};diff --git a/packages/core/src/IOC/IOCContainer.ts b/packages/core/src/IOC/IOCContainer.tsindex 70bc8951e5..5dc628b400 100644--- a/packages/core/src/IOC/IOCContainer.ts+++ b/packages/core/src/IOC/IOCContainer.ts@@ -86,6 +86,26 @@ export class IOCAttribute {* Register, get, inject instances*/export class IOCContainer {+ protected _circulate: CirculateData[];++ protected _mappings: Map<any, any>;++ protected _instance: Map<any, any>;++ protected _configure: Map<any, any>;++ protected _attribute: IOCAttribute;++ constructor(attribute: AttributeConfig | IOCAttribute = {}) {+ this._mappings = new Map<any, any>();+ this._instance = new Map<any, any>();+ this._configure = new Map<any, any>();+ this._attribute = isAttribute(attribute)+ ? attribute+ : new IOCAttribute(attribute);+ this._circulate = [];+ }+static postDestroy<T>(target: T): void {if (target) {const prototype = Object.getPrototypeOf(target);@@ -126,56 +146,112 @@ export class IOCContainer {}}- protected _circulate: CirculateData[];-- protected _mappings: Map<any, any>;-- protected _instance: Map<any, any>;+ inject(instance: object) {+ if (instance) {+ const collect: any = [[instance, []]];+ this._inject(instance, collect);+ this._clearCirculate();+ for (const item of collect.reverse()) {+ IOCContainer.postConstruct(item[0], item[1]);+ }+ }+ }- protected _configure: Map<any, any>;+ getAttribute(): IOCAttribute {+ return this._attribute;+ }- protected _attribute: IOCAttribute;+ getInstance<T>(baseClass: any, ...argument: any): T {+ const collect: any = [];+ const instance = this._getInstance(+ baseClass,+ collect,+ IOCScope.prototype,+ argument+ );+ this._clearCirculate();+ for (const item of collect.reverse()) {+ IOCContainer.postConstruct(item[0], item[1]);+ }+ return instance;+ }- private _printCirculate(): string {- let message =- 'The dependencies of some of the instance in the application context form a cycle:';- message += '\n';- this._circulate.reverse().forEach((element) => {- const { baseClass } = element;- const ImplClass: IOCMapClass<any> = this._mappings.get(baseClass);- const { name } = ImplClass;- message += '\n';- message += `Class: ${name} Field: ${baseClass}`;- });- return message;+ getSingleton<T>(baseClass: any, ...argument: any): T {+ const collect: any = [];+ const instance = this._getInstance(+ baseClass,+ collect,+ IOCScope.singleton,+ argument+ );+ this._clearCirculate();+ for (const item of collect.reverse()) {+ IOCContainer.postConstruct(item[0], item[1]);+ }+ return instance;}- private _clearCirculate(): void {- this._circulate = [];+ getBaseClassByInstance(target: any): any {+ if (isObject(target)) {+ const { constructor } = target;+ const entries: IterableIterator<any> = this._mappings.entries();+ for (const [key, value] of entries) {+ if (constructor === value) {+ return key;+ }+ }+ }+ return undefined;}- private _addCirculate(baseClass: any, scope: IOCScope): void {- this._circulate.forEach((element) => {- if (element.baseClass === baseClass) {- if (element.scope === scope) {- if (scope === IOCScope.prototype) {- this._circulate.push({- baseClass,- scope,- });- throw new Error(this._printCirculate());- }+ removeMapping(baseClass: any): void {+ this._mappings.delete(baseClass);+ const target = this._instance.get(baseClass);+ const destroy = (instance: any) => {+ const keys = Object.keys(instance);+ for (const key of keys) {+ const property = instance[key];+ const findClass = this.getBaseClassByInstance(property);+ if (findClass) {+ destroy(property);+ IOCContainer.postDestroy(instance);}}- });- this._circulate.push({- baseClass,- scope,+ IOCContainer.postDestroy(instance);+ };+ if (isDefine(target)) {+ destroy(target);+ }+ this._instance.delete(baseClass);+ }++ addMapping<T>(+ baseClass: any,+ implClass: IOCMapClass<T>,+ config: MappingConfig | void+ ): void {+ this._mappings.set(baseClass, implClass);+ if (isDefine(config)) {+ this._configure.set(baseClass, config);+ }+ }++ addSingletonMapping<T>(baseClass: any, implClass: IOCMapClass<T>) {+ return this.addMapping(baseClass, implClass, {+ scope: IOCScope.singleton,});}- private _popCirculate(): void {- this._circulate.pop();+ addClass<T>(implClass: IOCMapClass<T>, config: MappingConfig | void): void {+ this.addMapping(implClass.name, implClass, config);+ }++ removeClass<T>(implClass: IOCMapClass<T>): void {+ this.removeMapping(implClass.name);+ }++ addSingletonClass<T>(implClass: IOCMapClass<T>): void {+ this.addSingletonMapping(implClass.name, implClass);}private _inject<T>(target: T, collect: any[]): void {@@ -276,122 +352,46 @@ export class IOCContainer {}}- constructor(attribute: AttributeConfig | IOCAttribute = {}) {- this._mappings = new Map<any, any>();- this._instance = new Map<any, any>();- this._configure = new Map<any, any>();- this._attribute = isAttribute(attribute)- ? attribute- : new IOCAttribute(attribute);- this._circulate = [];- }-- inject(instance: object) {- if (instance) {- const collect: any = [[instance, []]];- this._inject(instance, collect);- this._clearCirculate();- for (const item of collect.reverse()) {- IOCContainer.postConstruct(item[0], item[1]);- }- }- }-- getAttribute(): IOCAttribute {- return this._attribute;- }-- getInstance<T>(baseClass: any, ...argument: any): T {- const collect: any = [];- const instance = this._getInstance(- baseClass,- collect,- IOCScope.prototype,- argument- );- this._clearCirculate();- for (const item of collect.reverse()) {- IOCContainer.postConstruct(item[0], item[1]);- }- return instance;- }-- getSingleton<T>(baseClass: any, ...argument: any): T {- const collect: any = [];- const instance = this._getInstance(- baseClass,- collect,- IOCScope.singleton,- argument- );- this._clearCirculate();- for (const item of collect.reverse()) {- IOCContainer.postConstruct(item[0], item[1]);- }- return instance;+ private _printCirculate(): string {+ let message =+ 'The dependencies of some of the instance in the application context form a cycle:';+ message += '\n';+ this._circulate.reverse().forEach((element) => {+ const { baseClass } = element;+ const ImplClass: IOCMapClass<any> = this._mappings.get(baseClass);+ const { name } = ImplClass;+ message += '\n';+ message += `Class: ${name} Field: ${baseClass}`;+ });+ return message;}- getBaseClassByInstance(target: any): any {- if (isObject(target)) {- const { constructor } = target;- const entries: IterableIterator<any> = this._mappings.entries();- for (const [key, value] of entries) {- if (constructor === value) {- return key;- }- }- }- return undefined;+ private _clearCirculate(): void {+ this._circulate = [];}- removeMapping(baseClass: any): void {- this._mappings.delete(baseClass);- const target = this._instance.get(baseClass);- const destroy = (instance: any) => {- const keys = Object.keys(instance);- for (const key of keys) {- const property = instance[key];- const findClass = this.getBaseClassByInstance(property);- if (findClass) {- destroy(property);- IOCContainer.postDestroy(instance);+ private _addCirculate(baseClass: any, scope: IOCScope): void {+ this._circulate.forEach((element) => {+ if (element.baseClass === baseClass) {+ if (element.scope === scope) {+ if (scope === IOCScope.prototype) {+ this._circulate.push({+ baseClass,+ scope,+ });+ throw new Error(this._printCirculate());+ }}}- IOCContainer.postDestroy(instance);- };- if (isDefine(target)) {- destroy(target);- }- this._instance.delete(baseClass);- }-- addMapping<T>(- baseClass: any,- implClass: IOCMapClass<T>,- config: MappingConfig | void- ): void {- this._mappings.set(baseClass, implClass);- if (isDefine(config)) {- this._configure.set(baseClass, config);- }- }-- addSingletonMapping<T>(baseClass: any, implClass: IOCMapClass<T>) {- return this.addMapping(baseClass, implClass, {- scope: IOCScope.singleton,+ });+ this._circulate.push({+ baseClass,+ scope,});}- addClass<T>(implClass: IOCMapClass<T>, config: MappingConfig | void): void {- this.addMapping(implClass.name, implClass, config);- }-- removeClass<T>(implClass: IOCMapClass<T>): void {- this.removeMapping(implClass.name);- }-- addSingletonClass<T>(implClass: IOCMapClass<T>): void {- this.addSingletonMapping(implClass.name, implClass);+ private _popCirculate(): void {+ this._circulate.pop();}}diff --git a/packages/core/src/Observer/Observable.ts b/packages/core/src/Observer/Observable.tsindex 1170760978..e695cdf522 100644--- a/packages/core/src/Observer/Observable.ts+++ b/packages/core/src/Observer/Observable.ts@@ -3,6 +3,19 @@ import { Nullable } from '../Shared';* A class serves as a medium between the observable and its observers*/export class EventState {+ /**+ * An WorkBookObserver can set this property to true to prevent subsequent observers of being notified+ */+ skipNextObservers: boolean | undefined;++ /**+ * This will be populated with the return value of the last function that was executed.+ * If it is the first function in the callback chain it will be the event data.+ */+ lastReturnValue?: unknown;++ isStopPropagation: boolean = false;+/*** Create a new EventState* @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true@@ -25,19 +38,6 @@ export class EventState {return this;}- /**- * An WorkBookObserver can set this property to true to prevent subsequent observers of being notified- */- skipNextObservers: boolean | undefined;-- /**- * This will be populated with the return value of the last function that was executed.- * If it is the first function in the callback chain it will be the event data.- */- lastReturnValue?: unknown;-- isStopPropagation: boolean = false;-stopPropagation() {this.isStopPropagation = true;}@@ -69,7 +69,7 @@ export class Observer<T = void> {* Defines the callback to call when the observer is notified*/public callback: (eventData: T, eventState: EventState) => void- ) {}+ ) { }}/**@@ -90,13 +90,6 @@ export class Observable<T> {| Nullable<(observer: Observer<T>) => void>| undefined;- /**- * Gets the list of observers- */- get observers(): Array<Observer<T>> {- return this._observers;- }-/*** Creates a new observable* @param onObserverAdded defines a callback to call when a new observer is added@@ -109,6 +102,13 @@ export class Observable<T> {}}+ /**+ * Gets the list of observers+ */+ get observers(): Array<Observer<T>> {+ return this._observers;+ }+/*** Create a new WorkBookObserver with the specified callback* @param callback the callback that will be executed for that WorkBookObserver@@ -194,31 +194,6 @@ export class Observable<T> {return false;}- private _deferUnregister(observer: Observer<T>): void {- observer.unregisterOnNextCall = false;- observer._willBeUnregistered = true;- setTimeout(() => {- this._remove(observer);- }, 0);- }-- // This should only be called when not iterating over _observers to avoid callback skipping.- // Removes an observer from the _observer Array.- private _remove(observer: Nullable<Observer<T>>): boolean {- if (!observer) {- return false;- }-- const index = this._observers.indexOf(observer);-- if (index !== -1) {- this._observers.splice(index, 1);- return true;- }-- return false;- }-/*** Moves the observable to the top of the observer list making it get called first when notified* @param observer the observer to move@@ -381,4 +356,29 @@ export class Observable<T> {return result;}++ private _deferUnregister(observer: Observer<T>): void {+ observer.unregisterOnNextCall = false;+ observer._willBeUnregistered = true;+ setTimeout(() => {+ this._remove(observer);+ }, 0);+ }++ // This should only be called when not iterating over _observers to avoid callback skipping.+ // Removes an observer from the _observer Array.+ private _remove(observer: Nullable<Observer<T>>): boolean {+ if (!observer) {+ return false;+ }++ const index = this._observers.indexOf(observer);++ if (index !== -1) {+ this._observers.splice(index, 1);+ return true;+ }++ return false;+ }}diff --git a/packages/core/src/Plugin/PluginManager.ts b/packages/core/src/Plugin/PluginManager.tsindex 35a75f39b1..8bd71e6598 100644--- a/packages/core/src/Plugin/PluginManager.ts+++ b/packages/core/src/Plugin/PluginManager.ts@@ -12,16 +12,6 @@ export class PluginManager {protected _initialized: boolean;- protected _initialize() {- if (this._initialized) {- this._initialized = false;- this._plugins.forEach((plugin: BasePlugin) => {- plugin.onCreate(this._context);- plugin.onMounted(this._context);- });- }- }-constructor(context: ContextBase, plugins: BasePlugin[] = []) {this._context = context;this._plugins = [];@@ -74,4 +64,14 @@ export class PluginManager {}return null;}++ protected _initialize() {+ if (this._initialized) {+ this._initialized = false;+ this._plugins.forEach((plugin: BasePlugin) => {+ plugin.onCreate(this._context);+ plugin.onMounted(this._context);+ });+ }+ }}diff --git a/packages/core/src/Server/ServerSocket.ts b/packages/core/src/Server/ServerSocket.tsindex d8c645ad95..3fbf1373da 100644--- a/packages/core/src/Server/ServerSocket.ts+++ b/packages/core/src/Server/ServerSocket.ts@@ -32,21 +32,32 @@ export class ServerSocket extends ServerBase {initialize() {this.messageQueue = new MessageQueue<IOServerMessage>();this.status = MessageQueueStatus.WAIT;- this.globalSendResolve = () => {};+ this.globalSendResolve = () => { };if (this.config.socketEnable) {this.socket = new IOSocket({ url: this.config.socketUrl });this.socket.on(IOSocketListenType.MESSAGE, (event: MessageEvent) => {this.checkupReceiveMessage(event.data);});- this.socket.on(IOSocketListenType.ERROR, () => {});- this.socket.on(IOSocketListenType.OPEN, () => {});- this.socket.on(IOSocketListenType.CLOSE, () => {});- this.socket.on(IOSocketListenType.RETRY, () => {});- this.socket.on(IOSocketListenType.DESTROY, () => {});+ this.socket.on(IOSocketListenType.ERROR, () => { });+ this.socket.on(IOSocketListenType.OPEN, () => { });+ this.socket.on(IOSocketListenType.CLOSE, () => { });+ this.socket.on(IOSocketListenType.RETRY, () => { });+ this.socket.on(IOSocketListenType.DESTROY, () => { });this.socket.link();}}+ /**+ * zh: 消息添加到发送队列中+ * @param data+ */+ pushMessageQueue(changed: ISheetActionData[]): void {+ if (this.config.socketEnable) {+ this.messageQueue.push(this.packMessage(changed));+ this.sendMessageQueue();+ }+ }+/*** get first message*@@ -89,17 +100,6 @@ export class ServerSocket extends ServerBase {}}- /**- * zh: 消息添加到发送队列中- * @param data- */- pushMessageQueue(changed: ISheetActionData[]): void {- if (this.config.socketEnable) {- this.messageQueue.push(this.packMessage(changed));- this.sendMessageQueue();- }- }-/*** zh: 发送第一条消息* @returnsdiff --git a/packages/core/src/Shared/GroupModel.ts b/packages/core/src/Shared/GroupModel.tsindex 2aa59f9257..49ee14a731 100644--- a/packages/core/src/Shared/GroupModel.ts+++ b/packages/core/src/Shared/GroupModel.ts@@ -1,3 +1,4 @@+// TODOexport interface GroupModel<T> {getGroupModel(): T;}diff --git a/packages/core/src/Shared/IOSocket.ts b/packages/core/src/Shared/IOSocket.tsindex e3dbe5e623..b3244870cc 100644--- a/packages/core/src/Shared/IOSocket.ts+++ b/packages/core/src/Shared/IOSocket.ts@@ -84,6 +84,32 @@ export class IOSocket {this._config = setting;}+ link(): void {+ this._create();+ this._bind();+ }++ send(body: IOSocketSendBody): void {+ this._socket.send(body);+ }++ destroy(): void {+ const listen = this._listens.get(IOSocketListenType.DESTROY);+ if (listen) {+ listen();+ }+ this._clear();+ this._listens.clear();+ }++ on(type: IOSocketListenType, listen: Function): void {+ this._listens.set(type, listen);+ }++ close(): void {+ this._socket && this._socket.close();+ }+private _create(): void {const { _config } = this;this._socket = new WebSocket(_config.url);@@ -193,30 +219,4 @@ export class IOSocket {this._create();this._bind();}-- link(): void {- this._create();- this._bind();- }-- send(body: IOSocketSendBody): void {- this._socket.send(body);- }-- destroy(): void {- const listen = this._listens.get(IOSocketListenType.DESTROY);- if (listen) {- listen();- }- this._clear();- this._listens.clear();- }-- on(type: IOSocketListenType, listen: Function): void {- this._listens.set(type, listen);- }-- close(): void {- this._socket && this._socket.close();- }}diff --git a/packages/core/src/Shared/LRU/LRUMap.ts b/packages/core/src/Shared/LRU/LRUMap.tsindex 935844df6e..13747a1569 100644--- a/packages/core/src/Shared/LRU/LRUMap.ts+++ b/packages/core/src/Shared/LRU/LRUMap.ts@@ -102,6 +102,30 @@ export class LRUMap<K, V> {newest: Entry<K, V> | undefined;+ constructor(entries: Iterable<[K, V]>);+ constructor(limit: number);+ constructor(limit: number, entries: Iterable<[K, V]>);+ constructor(...parameter: any) {+ if (LRUHelper.hasLength(parameter, 1)) {+ if (LRUHelper.isNumber(parameter[0])) {+ const limit = parameter[0];+ this._initialize(limit, undefined);+ return;+ }+ if (LRUHelper.isIterable<[K, V]>(parameter[0])) {+ const entries = parameter[0];+ this._initialize(0, entries);+ return;+ }+ return;+ }+ if (LRUHelper.hasLength(parameter, 2)) {+ const limit = parameter[0];+ const entries = parameter[1];+ this._initialize(limit, entries);+ }+ }+_initialize(limit: number, entries: Iterable<[K, V]> | undefined): void {this.oldest = undefined;this.newest = undefined;@@ -143,30 +167,6 @@ export class LRUMap<K, V> {this.newest = entry;}- constructor(entries: Iterable<[K, V]>);- constructor(limit: number);- constructor(limit: number, entries: Iterable<[K, V]>);- constructor(...parameter: any) {- if (LRUHelper.hasLength(parameter, 1)) {- if (LRUHelper.isNumber(parameter[0])) {- const limit = parameter[0];- this._initialize(limit, undefined);- return;- }- if (LRUHelper.isIterable<[K, V]>(parameter[0])) {- const entries = parameter[0];- this._initialize(0, entries);- return;- }- return;- }- if (LRUHelper.hasLength(parameter, 2)) {- const limit = parameter[0];- const entries = parameter[1];- this._initialize(limit, entries);- }- }-assign(entries: Iterable<[K, V]>): void {let entry;let limit = this.limit || Number.MAX_VALUE;diff --git a/packages/core/src/Shared/Locale.ts b/packages/core/src/Shared/Locale.tsindex dd7ca2b469..701ce1fd18 100644--- a/packages/core/src/Shared/Locale.ts+++ b/packages/core/src/Shared/Locale.ts@@ -54,6 +54,24 @@ const en = {};export class Locale {options: ILocaleOptions;+ /**+ * get value from Locale object and key+ * @param locale - A specified language pack+ * @param key - Specify key+ * @returns Get the translation corresponding to the Key+ *+ * @private+ */+ private static getValue(locale: object, key: string): Nullable<string | object> {+ try {+ return locale[key]+ ? locale[key]+ : key.split('.').reduce((a, b) => a[b], locale);+ } catch (error) {+ console.error('Key %s not found', key);+ }+ }+initialize(locale: Nullable<LocaleType>) {this.options = {// use config first, or get language setting from browser@@ -125,22 +143,4 @@ export class Locale {getCurrentLocale() {return this.options.currentLocale;}-- /**- * get value from Locale object and key- * @param locale - A specified language pack- * @param key - Specify key- * @returns Get the translation corresponding to the Key- *- * @private- */- private static getValue(locale: object, key: string): Nullable<string | object> {- try {- return locale[key]- ? locale[key]- : key.split('.').reduce((a, b) => a[b], locale);- } catch (error) {- console.error('Key %s not found', key);- }- }}diff --git a/packages/core/src/Shared/NameGen.ts b/packages/core/src/Shared/NameGen.tsindex caacde44c3..691691124b 100644--- a/packages/core/src/Shared/NameGen.ts+++ b/packages/core/src/Shared/NameGen.ts@@ -6,6 +6,16 @@ let identity: number = 0;* TODO... 添加到 context 上*/export class NameGen {+ static getSheetName(name?: string): string {+ if (name === undefined) {+ name = NameGen._generateName();+ }+ while (NameGen._checkedName(name)) {+ name = NameGen._generateName();+ }+ return name;+ }+private static _generateName(): string {return `sheet${++identity}`;}@@ -17,14 +27,4 @@ export class NameGen {}return checked;}-- static getSheetName(name?: string): string {- if (name === undefined) {- name = NameGen._generateName();- }- while (NameGen._checkedName(name)) {- name = NameGen._generateName();- }- return name;- }}diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.tsindex 50ce1e667b..9bc29bc0f1 100644--- a/packages/core/src/Shared/ObjectArray.ts+++ b/packages/core/src/Shared/ObjectArray.ts@@ -34,31 +34,6 @@ const define = <T>(value?: T): value is T => value !== undefined && value !== nu* @beta*/export class ObjectArray<T> {- static objectKeys<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {- if (array) {- const keys = Object.keys(array);- const index = keys.indexOf('length');- if (index > -1) {- keys.splice(index, 1);- }- return keys;- }- return [];- }-- static getMaxLength<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {- if (array) {- if (array.length) {- return array.length;- }- const keys: unknown[] = ObjectArray.objectKeys(array);- if (keys.length) {- return Math.max(...(keys as number[])) + 1;- }- }- return 0;- }-private _array: ObjectArrayPrimitiveType<T>;private _length: number;@@ -93,6 +68,31 @@ export class ObjectArray<T> {}}+ static objectKeys<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {+ if (array) {+ const keys = Object.keys(array);+ const index = keys.indexOf('length');+ if (index > -1) {+ keys.splice(index, 1);+ }+ return keys;+ }+ return [];+ }++ static getMaxLength<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {+ if (array) {+ if (array.length) {+ return array.length;+ }+ const keys: unknown[] = ObjectArray.objectKeys(array);+ if (keys.length) {+ return Math.max(...(keys as number[])) + 1;+ }+ }+ return 0;+ }+obtain(index: number, defaultValue: T): T {return this._array[index] ?? defaultValue;}diff --git a/packages/core/src/Shared/RectTree/RectTree.ts b/packages/core/src/Shared/RectTree/RectTree.tsindex 894e1def2a..643e1a6aa0 100644--- a/packages/core/src/Shared/RectTree/RectTree.ts+++ b/packages/core/src/Shared/RectTree/RectTree.ts@@ -7,6 +7,26 @@ const defaultCompareNodeMinY = (a: RectTree.Node, b: RectTree.Node) =>a.minY - b.minY;export class RectTree {+ private _maxEntries: number;++ private _minEntries: number;++ private _data: RectTree.Node;++ private _compareMinX: Compare<RectTree.Node>;++ private _compareMinY: Compare<RectTree.Node>;++ constructor(max: number = 9) {+ // 默认情况下,节点中的最大条目数为 9; 最小节点填充为 40% 以获得最佳性能+ this._maxEntries = Math.max(4, max);+ this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));+ this._data = null as unknown as RectTree.Node;+ this._compareMinX = defaultCompareNodeMinX;+ this._compareMinY = defaultCompareNodeMinY;+ this.clear();+ }+static findItem<T>(item: T, items: T[], equalsFn: Nullable<EqualsFunction<T>>) {if (!equalsFn) {return items.indexOf(item);@@ -39,15 +59,175 @@ export class RectTree {}}- private _maxEntries: number;+ all(): RectTree.Node[] {+ return RectTree.Node.expandNode(this._data, []);+ }- private _minEntries: number;+ load(data: RectTree.Node[]): RectTree {+ if (!(data && data.length)) {+ return this;+ }- private _data: RectTree.Node;+ if (data.length < this._minEntries) {+ for (let i = 0; i < data.length; i++) {+ this.insert(data[i]);+ }+ return this;+ }- private _compareMinX: Compare<RectTree.Node>;+ // 使用 OMT 算法从头开始使用给定数据递归构建树+ let node = this._build(data.slice(), 0, data.length - 1, 0);- private _compareMinY: Compare<RectTree.Node>;+ if (!this._data.childrenNodes.length) {+ // 如果树为空,则按原样保存+ this._data = node;+ } else if (this._data.height === node.height) {+ // 如果树具有相同的高度,则拆分根+ this._splitRoot(this._data, node);+ } else {+ if (this._data.height < node.height) {+ // 如果插入的树更大,则交换树+ const tmpNode = this._data;+ this._data = node;+ node = tmpNode;+ }+ // 将小树插入大树中适当的层次+ this._insert(node, this._data.height - node.height - 1);+ }++ return this;+ }++ clear(): RectTree {+ this._data = RectTree.Node.makeParentNode([]);+ return this;+ }++ remove(+ item: RectTree.Node,+ equals: Nullable<EqualsFunction<RectTree.Node>>+ ): RectTree {+ if (!item) {+ return this;+ }++ let node = this._data;+ const path: RectTree.Node[] = [];+ const indexes: number[] = [];+ const bbox = item;+ let i = 0;+ let goingUp: boolean = false;+ let parent: RectTree.Node = null as unknown as RectTree.Node;++ // 深度优先迭代树遍历+ while (node || path.length) {+ if (!node) {+ // 往上+ node = path.pop() as RectTree.Node;+ parent = path[path.length - 1];+ i = indexes.pop() as number;+ goingUp = true;+ }++ if (node.leaf) {+ // 检查当前节点+ const index = RectTree.findItem(item, node.childrenNodes, equals);+ if (index !== -1) {+ // 找到项目,移除项目并向上压缩树+ node.childrenNodes.splice(index, 1);+ path.push(node);+ this._condense(path);+ return this;+ }+ }++ if (!goingUp && !node.leaf && node.contains(bbox)) {+ // 往下+ path.push(node);+ indexes.push(i as number);+ i = 0;+ parent = node;+ node = node.childrenNodes[0];+ } else if (parent) {+ // 向右走+ i++;+ node = parent.childrenNodes[i];+ goingUp = false;+ } else {+ // 没有发现+ node = null as unknown as RectTree.Node;+ }+ }++ return this;+ }++ insert(item: RectTree.Node): RectTree {+ if (item) {+ this._insert(item, this._data.height - 1);+ }+ return this;+ }++ collides(bbox: RectTree.Node): boolean {+ let node: RectTree.Node = this._data;++ if (!bbox.intersects(node)) {+ return false;+ }++ const nodesToSearch = [];++ while (node) {+ for (let i = 0; i < node.childrenNodes.length; i++) {+ const child = node.childrenNodes[i];+ const childBBox = child;+ if (bbox.intersects(childBBox)) {+ if (node.leaf || bbox.contains(childBBox)) {+ return true;+ }+ nodesToSearch.push(child);+ }+ }+ node = nodesToSearch.pop() as RectTree.Node;+ }++ return false;+ }++ first(bbox: RectTree.Node): RectTree.Node {+ return this.search(bbox)[0];+ }++ search(bbox: RectTree.Node): RectTree.Node[] {+ let node = this._data;+ const result: RectTree.Node[] = [];++ if (!bbox.intersects(node)) {+ return result;+ }++ const nodesToSearch = [];++ while (node) {+ for (let i = 0; i < node.childrenNodes.length; i++) {+ const child = node.childrenNodes[i];+ const childBBox = child;+ if (bbox.intersects(childBBox)) {+ if (node.leaf) {+ result.push(child);+ } else if (bbox.contains(childBBox)) {+ RectTree.Node.expandNode(child, result);+ } else {+ nodesToSearch.push(child);+ }+ }+ }+ node = nodesToSearch.pop() as RectTree.Node;+ }++ return result;+ }private _chooseSplitAxis(node: RectTree.Node, m: number, M: number) {// 按最佳轴对节点子节点进行排序以进行拆分@@ -290,212 +470,12 @@ export class RectTree {}return node;}-- constructor(max: number = 9) {- // 默认情况下,节点中的最大条目数为 9; 最小节点填充为 40% 以获得最佳性能- this._maxEntries = Math.max(4, max);- this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));- this._data = null as unknown as RectTree.Node;- this._compareMinX = defaultCompareNodeMinX;- this._compareMinY = defaultCompareNodeMinY;- this.clear();- }-- all(): RectTree.Node[] {- return RectTree.Node.expandNode(this._data, []);- }-- load(data: RectTree.Node[]): RectTree {- if (!(data && data.length)) {- return this;- }-- if (data.length < this._minEntries) {- for (let i = 0; i < data.length; i++) {- this.insert(data[i]);- }- return this;- }-- // 使用 OMT 算法从头开始使用给定数据递归构建树- let node = this._build(data.slice(), 0, data.length - 1, 0);-- if (!this._data.childrenNodes.length) {- // 如果树为空,则按原样保存- this._data = node;- } else if (this._data.height === node.height) {- // 如果树具有相同的高度,则拆分根- this._splitRoot(this._data, node);- } else {- if (this._data.height < node.height) {- // 如果插入的树更大,则交换树- const tmpNode = this._data;- this._data = node;- node = tmpNode;- }- // 将小树插入大树中适当的层次- this._insert(node, this._data.height - node.height - 1);- }-- return this;- }-- clear(): RectTree {- this._data = RectTree.Node.makeParentNode([]);- return this;- }-- remove(- item: RectTree.Node,- equals: Nullable<EqualsFunction<RectTree.Node>>- ): RectTree {- if (!item) {- return this;- }-- let node = this._data;- const path: RectTree.Node[] = [];- const indexes: number[] = [];- const bbox = item;- let i = 0;- let goingUp: boolean = false;- let parent: RectTree.Node = null as unknown as RectTree.Node;-- // 深度优先迭代树遍历- while (node || path.length) {- if (!node) {- // 往上- node = path.pop() as RectTree.Node;- parent = path[path.length - 1];- i = indexes.pop() as number;- goingUp = true;- }-- if (node.leaf) {- // 检查当前节点- const index = RectTree.findItem(item, node.childrenNodes, equals);- if (index !== -1) {- // 找到项目,移除项目并向上压缩树- node.childrenNodes.splice(index, 1);- path.push(node);- this._condense(path);- return this;- }- }-- if (!goingUp && !node.leaf && node.contains(bbox)) {- // 往下- path.push(node);- indexes.push(i as number);- i = 0;- parent = node;- node = node.childrenNodes[0];- } else if (parent) {- // 向右走- i++;- node = parent.childrenNodes[i];- goingUp = false;- } else {- // 没有发现- node = null as unknown as RectTree.Node;- }- }-- return this;- }-- insert(item: RectTree.Node): RectTree {- if (item) {- this._insert(item, this._data.height - 1);- }- return this;- }-- collides(bbox: RectTree.Node): boolean {- let node: RectTree.Node = this._data;-- if (!bbox.intersects(node)) {- return false;- }-- const nodesToSearch = [];-- while (node) {- for (let i = 0; i < node.childrenNodes.length; i++) {- const child = node.childrenNodes[i];- const childBBox = child;- if (bbox.intersects(childBBox)) {- if (node.leaf || bbox.contains(childBBox)) {- return true;- }- nodesToSearch.push(child);- }- }- node = nodesToSearch.pop() as RectTree.Node;- }-- return false;- }-- first(bbox: RectTree.Node): RectTree.Node {- return this.search(bbox)[0];- }-- search(bbox: RectTree.Node): RectTree.Node[] {- let node = this._data;- const result: RectTree.Node[] = [];-- if (!bbox.intersects(node)) {- return result;- }-- const nodesToSearch = [];-- while (node) {- for (let i = 0; i < node.childrenNodes.length; i++) {- const child = node.childrenNodes[i];- const childBBox = child;- if (bbox.intersects(childBBox)) {- if (node.leaf) {- result.push(child);- } else if (bbox.contains(childBBox)) {- RectTree.Node.expandNode(child, result);- } else {- nodesToSearch.push(child);- }- }- }- node = nodesToSearch.pop() as RectTree.Node;- }-- return result;- }}export type EqualsFunction<T> = (a: T, b: T) => boolean;export namespace RectTree {export class Node {- static makeParentNode(childrenNodes: RectTree.Node[]) {- return new RectTree.Node({ childrenNodes });- }-- static expandNode(- node: RectTree.Node,- result: RectTree.Node[]- ): RectTree.Node[] {- const nodesToSearch: RectTree.Node[] = [];- while (node) {- if (node.leaf) {- result.push(...node.childrenNodes);- } else {- nodesToSearch.push(...node.childrenNodes);- }- node = nodesToSearch.pop() as RectTree.Node;- }- return result;- }-minX: number;range: Range;@@ -530,6 +510,26 @@ export namespace RectTree {this.childrenNodes = childrenNodes;}+ static makeParentNode(childrenNodes: RectTree.Node[]) {+ return new RectTree.Node({ childrenNodes });+ }++ static expandNode(+ node: RectTree.Node,+ result: RectTree.Node[]+ ): RectTree.Node[] {+ const nodesToSearch: RectTree.Node[] = [];+ while (node) {+ if (node.leaf) {+ result.push(...node.childrenNodes);+ } else {+ nodesToSearch.push(...node.childrenNodes);+ }+ node = nodesToSearch.pop() as RectTree.Node;+ }+ return result;+ }+difference(other: RectTree.Node, collect: Nullable<RectTree.Node[]>) {const ret: RectTree.Node[] = collect || [];const addNode = (diff --git a/packages/core/src/Sheets/Domain/Color.ts b/packages/core/src/Sheets/Domain/Color.tsindex d8979019f3..e83598729d 100644--- a/packages/core/src/Sheets/Domain/Color.ts+++ b/packages/core/src/Sheets/Domain/Color.ts@@ -4,6 +4,12 @@ import { ColorBuilder } from './ColorBuilder';import { THEME_COLORS } from '../../Const/THEME_COLOR_MAP';export class Color {+ protected _builder: ColorBuilder;++ constructor(builder: ColorBuilder) {+ this._builder = builder;+ }+static rgbColorToHexValue(color: RgbColor): string {return `#${((1 << 24) +@@ -44,12 +50,6 @@ export class Color {return string;}- protected _builder: ColorBuilder;-- constructor(builder: ColorBuilder) {- this._builder = builder;- }-asRgbColor(): RgbColor {return this._builder.asRgbColor();}diff --git a/packages/core/src/Sheets/Domain/Range.ts b/packages/core/src/Sheets/Domain/Range.tsindex a96bd2947d..6bc4c51eff 100644--- a/packages/core/src/Sheets/Domain/Range.ts+++ b/packages/core/src/Sheets/Domain/Range.ts@@ -81,18 +81,6 @@ type IValueOptionsType = {* @beta*/export class Range {- static foreach(- rangeData: IRangeData,- action: (row: number, column: number) => void- ): void {- const { startRow, startColumn, endRow, endColumn } = rangeData;- for (let i = startRow; i <= endRow; i++) {- for (let j = startColumn; j <= endColumn; j++) {- action(i, j);- }- }- }-private _commandManager: CommandManager;private _context: SheetContext;@@ -120,6 +108,18 @@ export class Range {}}+ static foreach(+ rangeData: IRangeData,+ action: (row: number, column: number) => void+ ): void {+ const { startRow, startColumn, endRow, endColumn } = rangeData;+ for (let i = startRow; i <= endRow; i++) {+ for (let j = startColumn; j <= endColumn; j++) {+ action(i, j);+ }+ }+ }+/*** get current range data*@@ -444,23 +444,6 @@ export class Range {return this.getStrikeThroughs()[0][0];}- /**- *- * @param arg Shorthand for the style that gets- * @returns style value- */- private _getStyles(arg: string) {- return this.getValues().map((row) =>- row.map((cell: Nullable<ICellData>) => {- const styles = this._context.getWorkBook().getStyles();-- // const style = getStyle(styles, cell);- const style = styles && styles.getStyleByCell(cell);- return (style && style[arg]) || DEFAULT_STYLES[arg];- })- );- }-/*** Returns the font size in point size of the cell in the top-left corner of the range.*/@@ -875,74 +858,6 @@ export class Range {return false;}- // isStartColumnBounded() {}- // isStartRowBounded() {}-- private _setStyle(- value: Nullable<string | number | ITextDecoration>,- type: string- ) {- const { _context, _worksheet, _commandManager } = this;-- const { startRow, endRow, startColumn, endColumn } = this._rangeData;-- // string converted to a two-dimensional array- const styleObj = { [type]: value };-- const stylesMatrix = Tools.fillObjectMatrix(- endRow - startRow + 1,- endColumn - startColumn + 1,- styleObj- );-- const setStyle: ISetRangeStyleActionData = {- sheetId: _worksheet.getSheetId(),- actionName: SetRangeStyleAction.NAME,- value: stylesMatrix,- rangeData: this._rangeData,- };-- const command = new Command(- {- WorkBookUnit: _context.getWorkBook(),- },- setStyle- );- _commandManager.invoke(command);- return this;- }-- private _setStyles(- values: Array<Array<Nullable<string | number | ITextDecoration>>>,- type: string- ) {- const { _context, _worksheet, _commandManager } = this;-- const { startRow, endRow, startColumn, endColumn } = this._rangeData;-- const matrix = new ObjectMatrix<IStyleData>();- for (let r = 0; r < endRow - startRow + 1; r++) {- for (let c = 0; c < endColumn - startColumn + 1; c++) {- matrix.setValue(r, c, { [type]: values[r][c] });- }- }- const setStyle: ISetRangeStyleActionData = {- sheetId: _worksheet.getSheetId(),- actionName: ACTION_NAMES.SET_RANGE_STYLE_ACTION,- value: matrix.getData(),- rangeData: this._rangeData,- };-- const command = new Command(- {- WorkBookUnit: _context.getWorkBook(),- },- setStyle- );- _commandManager.invoke(command);- return this;- }-/*** Sets the background color of all cells in the range in CSS notation (such as '#ffffff' or 'white').*@@ -3750,6 +3665,55 @@ export class Range {return rangeMatrix;}+ forEach(action: (row: number, column: number) => void): void {+ Range.foreach(this._rangeData, action);+ }++ /**+ * Randomizes the order of the rows in the given range.+ * TODO:待研究特性+ * 1. 公式内的范围也会变化+ * 2. 并不是所有范围都支持随机处理+ * @returns+ */+ randomize() {+ const { _context, _worksheet, _commandManager, _rangeData } = this;+ const { startRow, startColumn } = _rangeData;+ const cellValue = new ObjectMatrix<ICellData>();++ const value = Tools.randSort(this.getMatrix().toArray());++ value.forEach((row, r) =>+ row.forEach((cell, c) => {+ cell = cell as ICellData;+ cellValue.setValue(r + startRow, c + startColumn, cell || {});+ })+ );++ const setValue: ISetRangeDataActionData = {+ sheetId: _worksheet.getSheetId(),+ actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,+ cellValue: cellValue.getData(),+ };+ const command = new Command(+ {+ WorkBookUnit: _context.getWorkBook(),+ },+ setValue+ );+ _commandManager.invoke(command);+ }++ /**+ * Determine whether a range is legal+ */+ isValid(): boolean {+ if (Object.values(this._rangeData).includes(-1)) {+ return false;+ }+ return true;+ }+/*** en:*@@ -3870,53 +3834,89 @@ export class Range {return [value, range];}- forEach(action: (row: number, column: number) => void): void {- Range.foreach(this._rangeData, action);- }-/**- * Randomizes the order of the rows in the given range.- * TODO:待研究特性- * 1. 公式内的范围也会变化- * 2. 并不是所有范围都支持随机处理- * @returns+ *+ * @param arg Shorthand for the style that gets+ * @returns style value*/- randomize() {- const { _context, _worksheet, _commandManager, _rangeData } = this;- const { startRow, startColumn } = _rangeData;- const cellValue = new ObjectMatrix<ICellData>();-- const value = Tools.randSort(this.getMatrix().toArray());+ private _getStyles(arg: string) {+ return this.getValues().map((row) =>+ row.map((cell: Nullable<ICellData>) => {+ const styles = this._context.getWorkBook().getStyles();- value.forEach((row, r) =>- row.forEach((cell, c) => {- cell = cell as ICellData;- cellValue.setValue(r + startRow, c + startColumn, cell || {});+ // const style = getStyle(styles, cell);+ const style = styles && styles.getStyleByCell(cell);+ return (style && style[arg]) || DEFAULT_STYLES[arg];}));+ }- const setValue: ISetRangeDataActionData = {+ // isStartColumnBounded() {}+ // isStartRowBounded() {}++ private _setStyle(+ value: Nullable<string | number | ITextDecoration>,+ type: string+ ) {+ const { _context, _worksheet, _commandManager } = this;++ const { startRow, endRow, startColumn, endColumn } = this._rangeData;++ // string converted to a two-dimensional array+ const styleObj = { [type]: value };++ const stylesMatrix = Tools.fillObjectMatrix(+ endRow - startRow + 1,+ endColumn - startColumn + 1,+ styleObj+ );++ const setStyle: ISetRangeStyleActionData = {sheetId: _worksheet.getSheetId(),- actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,- cellValue: cellValue.getData(),+ actionName: SetRangeStyleAction.NAME,+ value: stylesMatrix,+ rangeData: this._rangeData,};+const command = new Command({WorkBookUnit: _context.getWorkBook(),},- setValue+ setStyle);_commandManager.invoke(command);+ return this;}- /**- * Determine whether a range is legal- */- isValid(): boolean {- if (Object.values(this._rangeData).includes(-1)) {- return false;+ private _setStyles(+ values: Array<Array<Nullable<string | number | ITextDecoration>>>,+ type: string+ ) {+ const { _context, _worksheet, _commandManager } = this;++ const { startRow, endRow, startColumn, endColumn } = this._rangeData;++ const matrix = new ObjectMatrix<IStyleData>();+ for (let r = 0; r < endRow - startRow + 1; r++) {+ for (let c = 0; c < endColumn - startColumn + 1; c++) {+ matrix.setValue(r, c, { [type]: values[r][c] });+ }}- return true;+ const setStyle: ISetRangeStyleActionData = {+ sheetId: _worksheet.getSheetId(),+ actionName: ACTION_NAMES.SET_RANGE_STYLE_ACTION,+ value: matrix.getData(),+ rangeData: this._rangeData,+ };++ const command = new Command(+ {+ WorkBookUnit: _context.getWorkBook(),+ },+ setStyle+ );+ _commandManager.invoke(command);+ return this;}// /**diff --git a/packages/core/src/Sheets/Domain/RangeList.ts b/packages/core/src/Sheets/Domain/RangeList.tsindex d270433917..4c614a001c 100644--- a/packages/core/src/Sheets/Domain/RangeList.ts+++ b/packages/core/src/Sheets/Domain/RangeList.ts@@ -229,52 +229,6 @@ export class RangeList {return this.clear({ commentsOnly: true });}- /**- * set style- *- * @param value style value- * @param type style type- * @returns This range list, for chaining.- * @internal @preapproved- */- private _setStyle(- value: Nullable<number | string | ITextDecoration | BooleanNumber>,- type: string- ) {- let { _rangeList, _context, _commandManager, _worksheet } = this;-- const setList = _rangeList.map((range) => {- let { startRow, startColumn, endRow, endColumn } = range;-- // string converted to a two-dimensional array- const styleObj: IStyleData = { [type]: value };-- const stylesMatrix = Tools.fillObjectMatrix(- endRow - startRow + 1,- endColumn - startColumn + 1,- styleObj- );-- const setStyle: ISetRangeStyleActionData = {- sheetId: _worksheet.getSheetId(),- value: stylesMatrix,- rangeData: range,- actionName: SetRangeStyleAction.NAME,- };-- return setStyle;- });-- let command = new Command(- {- WorkBookUnit: _context.getWorkBook(),- },- ...setList- );- _commandManager.invoke(command);- return this;- }-/*** Sets the background color for each Range in the range list.*@@ -798,4 +752,50 @@ export class RangeList {_commandManager.invoke(command);return this;}++ /**+ * set style+ *+ * @param value style value+ * @param type style type+ * @returns This range list, for chaining.+ * @internal @preapproved+ */+ private _setStyle(+ value: Nullable<number | string | ITextDecoration | BooleanNumber>,+ type: string+ ) {+ let { _rangeList, _context, _commandManager, _worksheet } = this;++ const setList = _rangeList.map((range) => {+ let { startRow, startColumn, endRow, endColumn } = range;++ // string converted to a two-dimensional array+ const styleObj: IStyleData = { [type]: value };++ const stylesMatrix = Tools.fillObjectMatrix(+ endRow - startRow + 1,+ endColumn - startColumn + 1,+ styleObj+ );++ const setStyle: ISetRangeStyleActionData = {+ sheetId: _worksheet.getSheetId(),+ value: stylesMatrix,+ rangeData: range,+ actionName: SetRangeStyleAction.NAME,+ };++ return setStyle;+ });++ let command = new Command(+ {+ WorkBookUnit: _context.getWorkBook(),+ },+ ...setList+ );+ _commandManager.invoke(command);+ return this;+ }}diff --git a/packages/core/src/Sheets/Domain/Workbook.ts b/packages/core/src/Sheets/Domain/Workbook.tsindex 61b988ce42..2ff5099ae5 100644--- a/packages/core/src/Sheets/Domain/Workbook.ts+++ b/packages/core/src/Sheets/Domain/Workbook.ts@@ -88,145 +88,20 @@ export class Workbook {}/**- * Get Default Sheet- * @private- */- private _getDefaultWorkSheet(): void {- const { _context, _config, _worksheets } = this;- const { sheets, sheetOrder } = _config;-- // One worksheet by default- if (Tools.isEmptyObject(sheets)) {- sheets[DEFAULT_WORKSHEET.id] = Object.assign(DEFAULT_WORKSHEET, {- status: BooleanNumber.TRUE,- });- }-- let firstWorksheet = null;-- for (let sheetId in sheets) {- let config = sheets[sheetId];- config.name = NameGen.getSheetName(config.name);- const worksheet = new Worksheet(_context, config);- _worksheets.set(sheetId, worksheet);- if (!sheetOrder.includes(sheetId)) {- sheetOrder.push(sheetId);- }- if (firstWorksheet == null) {- firstWorksheet = worksheet;- }- }-- if (firstWorksheet) {- firstWorksheet.activate();- }- }-- /**- * Get Default Active Sheet- * @private- */- private _setDefaultActiveSheet(): void {- if (this._worksheets.size > 0) {- this._worksheets.forEach((sheet) => {- sheet.setStatus(BooleanNumber.FALSE);- });- this._worksheets[0].setStatus(BooleanNumber.TRUE);- }- }-- /**- * Get the range array based on the range string and sheet id*- * @privateRemarks- * zh: 根据范围字符串和sheet id取得范围数组- *- * @param txt - range string+ * @param rangeData* @returns- *- * @internal*/- private _getCellRange(txt: IRangeStringData): IGridRange {- let sheetTxt: string = '';- let rangeTxt: string | string[] = '';- if (txt.indexOf('!') > -1) {- const val = txt.split('!');- sheetTxt = val[0];- rangeTxt = val[1];- sheetTxt = sheetTxt.replace(/\\'/g, "'").replace(/''/g, "'");- if (- sheetTxt.substring(0, 1) === "'" &&- sheetTxt.substring(sheetTxt.length - 1, 1) === "'"- ) {- sheetTxt = sheetTxt.substring(1, sheetTxt.length - 1);- }- } else {- rangeTxt = txt;- }- if (rangeTxt.indexOf(':') === -1) {- const row = parseInt(rangeTxt.replace(/[^0-9]/g, ''), 10) - 1;- const col = Tools.ABCatNum(rangeTxt.replace(/[^A-Za-z]/g, ''));-- if (!Number.isNaN(row) && !Number.isNaN(col)) {- const item = {- sheetId: sheetTxt,- rangeData: {- startRow: row,- endRow: row,- startColumn: col,- endColumn: col,- },- };- return item;- }- return DEFAULT_RANGE_ARRAY;- }- rangeTxt = rangeTxt.split(':');-- const row: IRowStartEndData = [0, 0];- const col: IColumnStartEndData = [0, 0];- const maxRow =- this.getSheetBySheetName(sheetTxt)?.getMaxRows() ||- this.getActiveSheet()?.getMaxRows();- const maxCol =- this.getSheetBySheetName(sheetTxt)?.getMaxColumns() ||- this.getActiveSheet()?.getMaxColumns();- row[0] = parseInt(rangeTxt[0].replace(/[^0-9]/g, ''), 10) - 1;- row[1] = parseInt(rangeTxt[1].replace(/[^0-9]/g, ''), 10) - 1;-- if (Number.isNaN(row[0])) {- row[0] = 0;- }-- if (Number.isNaN(row[1])) {- row[1] = maxRow!;- }+ static rangeDataToRangeStringData(rangeData: IRangeData) {+ const { startRow, endRow, startColumn, endColumn } = rangeData;- if (row[0] > row[1]) {- return DEFAULT_RANGE_ARRAY;- }- col[0] = Tools.ABCatNum(rangeTxt[0].replace(/[^A-Za-z]/g, ''));- col[1] = Tools.ABCatNum(rangeTxt[1].replace(/[^A-Za-z]/g, ''));- if (Number.isNaN(col[0])) {- col[0] = 0;- }- if (Number.isNaN(col[1])) {- col[1] = maxCol!;- }- if (col[0] > col[1]) {- return DEFAULT_RANGE_ARRAY;- }+ return `${Tools.chatAtABC(startColumn) + (startRow + 1)}:${Tools.chatAtABC(+ endColumn+ )}${endRow + 1}`;+ }- const item = {- sheetId: this.getSheetBySheetName(sheetTxt)?.getSheetId() || '',- rangeData: {- startRow: row[0],- endRow: row[1],- startColumn: col[0],- endColumn: col[1],- },- };- return item;+ static isIRangeType(range: IRangeType | IRangeType[]): Boolean {+ return typeof range === 'string' || 'startRow' in range || 'row' in range;}getUnitId() {@@ -697,7 +572,7 @@ export class Workbook {** @returns void*/- flush(): void { }+ flush(): void {}setSheetOrder(sheetId: string, order: number): void {// const { _sheetOrder } = this;@@ -847,10 +722,6 @@ export class Workbook {// return new FilterCriteriaBuilder();// }- static isIRangeType(range: IRangeType | IRangeType[]): Boolean {- return typeof range === 'string' || 'startRow' in range || 'row' in range;- }-/*** transform any range type to range data*@@ -912,19 +783,6 @@ export class Workbook {return DEFAULT_RANGE_ARRAY;}- /**- *- * @param rangeData- * @returns- */- static rangeDataToRangeStringData(rangeData: IRangeData) {- const { startRow, endRow, startColumn, endColumn } = rangeData;-- return `${Tools.chatAtABC(startColumn) + (startRow + 1)}:${Tools.chatAtABC(- endColumn- )}${endRow + 1}`;- }-load(config: IWorkbookConfig) {// TODO: new Commandthis._config = config;@@ -934,4 +792,146 @@ export class Workbook {// TODOreturn this._config;}++ /**+ * Get Default Sheet+ * @private+ */+ private _getDefaultWorkSheet(): void {+ const { _context, _config, _worksheets } = this;+ const { sheets, sheetOrder } = _config;++ // One worksheet by default+ if (Tools.isEmptyObject(sheets)) {+ sheets[DEFAULT_WORKSHEET.id] = Object.assign(DEFAULT_WORKSHEET, {+ status: BooleanNumber.TRUE,+ });+ }++ let firstWorksheet = null;++ for (let sheetId in sheets) {+ let config = sheets[sheetId];+ config.name = NameGen.getSheetName(config.name);+ const worksheet = new Worksheet(_context, config);+ _worksheets.set(sheetId, worksheet);+ if (!sheetOrder.includes(sheetId)) {+ sheetOrder.push(sheetId);+ }+ if (firstWorksheet == null) {+ firstWorksheet = worksheet;+ }+ }++ if (firstWorksheet) {+ firstWorksheet.activate();+ }+ }++ /**+ * Get Default Active Sheet+ * @private+ */+ private _setDefaultActiveSheet(): void {+ if (this._worksheets.size > 0) {+ this._worksheets.forEach((sheet) => {+ sheet.setStatus(BooleanNumber.FALSE);+ });+ this._worksheets[0].setStatus(BooleanNumber.TRUE);+ }+ }++ /**+ * Get the range array based on the range string and sheet id+ *+ * @privateRemarks+ * zh: 根据范围字符串和sheet id取得范围数组+ *+ * @param txt - range string+ * @returns+ *+ * @internal+ */+ private _getCellRange(txt: IRangeStringData): IGridRange {+ let sheetTxt: string = '';+ let rangeTxt: string | string[] = '';+ if (txt.indexOf('!') > -1) {+ const val = txt.split('!');+ sheetTxt = val[0];+ rangeTxt = val[1];+ sheetTxt = sheetTxt.replace(/\\'/g, "'").replace(/''/g, "'");+ if (+ sheetTxt.substring(0, 1) === "'" &&+ sheetTxt.substring(sheetTxt.length - 1, 1) === "'"+ ) {+ sheetTxt = sheetTxt.substring(1, sheetTxt.length - 1);+ }+ } else {+ rangeTxt = txt;+ }+ if (rangeTxt.indexOf(':') === -1) {+ const row = parseInt(rangeTxt.replace(/[^0-9]/g, ''), 10) - 1;+ const col = Tools.ABCatNum(rangeTxt.replace(/[^A-Za-z]/g, ''));++ if (!Number.isNaN(row) && !Number.isNaN(col)) {+ const item = {+ sheetId: sheetTxt,+ rangeData: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ },+ };+ return item;+ }+ return DEFAULT_RANGE_ARRAY;+ }+ rangeTxt = rangeTxt.split(':');++ const row: IRowStartEndData = [0, 0];+ const col: IColumnStartEndData = [0, 0];+ const maxRow =+ this.getSheetBySheetName(sheetTxt)?.getMaxRows() ||+ this.getActiveSheet()?.getMaxRows();+ const maxCol =+ this.getSheetBySheetName(sheetTxt)?.getMaxColumns() ||+ this.getActiveSheet()?.getMaxColumns();+ row[0] = parseInt(rangeTxt[0].replace(/[^0-9]/g, ''), 10) - 1;+ row[1] = parseInt(rangeTxt[1].replace(/[^0-9]/g, ''), 10) - 1;++ if (Number.isNaN(row[0])) {+ row[0] = 0;+ }++ if (Number.isNaN(row[1])) {+ row[1] = maxRow!;+ }++ if (row[0] > row[1]) {+ return DEFAULT_RANGE_ARRAY;+ }+ col[0] = Tools.ABCatNum(rangeTxt[0].replace(/[^A-Za-z]/g, ''));+ col[1] = Tools.ABCatNum(rangeTxt[1].replace(/[^A-Za-z]/g, ''));+ if (Number.isNaN(col[0])) {+ col[0] = 0;+ }+ if (Number.isNaN(col[1])) {+ col[1] = maxCol!;+ }+ if (col[0] > col[1]) {+ return DEFAULT_RANGE_ARRAY;+ }++ const item = {+ sheetId: this.getSheetBySheetName(sheetTxt)?.getSheetId() || '',+ rangeData: {+ startRow: row[0],+ endRow: row[1],+ startColumn: col[0],+ endColumn: col[1],+ },+ };+ return item;+ }}diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.tsindex ca6adad469..ec65ab0f50 100644--- a/packages/core/src/Sheets/Domain/Worksheet.ts+++ b/packages/core/src/Sheets/Domain/Worksheet.ts@@ -107,11 +107,6 @@ export class Worksheet {// protected _columnStatusGroup: StructGroup;- private _initialize(): void {- // this._selection = new Selection(this);- this._merges = new Merges(this, this._config.mergeData);- }-constructor(context: SheetContext);constructor(context: SheetContext, config: Partial<IWorksheetConfig>);constructor(...argument: any) {@@ -2244,6 +2239,11 @@ export class Worksheet {return this;}+ private _initialize(): void {+ // this._selection = new Selection(this);+ this._merges = new Merges(this, this._config.mergeData);+ }+// /**// * Collapse All Row// * @returns WorkSheet Instance