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.

fix: fix memory leak on dispose sheet unit (#1900)

Wenzhao Hu4a5eca1927dd
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index e6b9ec3a07..6d6d19399b 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -90,6 +90,11 @@ univer.registerPlugin(UniverSheetsFindReplacePlugin);
// create univer sheet instance
univer.createUniverSheet(DEFAULT_WORKBOOK_DATA_DEMO);
+// Uncomment the following lines to test if the document is disposed correctly without memory leaks.
+// setTimeout(() => {
+// univer.__getInjector().get(IUniverInstanceService).disposeDocument(DEFAULT_WORKBOOK_DATA_DEMO.id);
+// }, 5000);
+
// sheet condition formatting
univer.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index 0795090342..1616238b03 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -98,9 +98,16 @@ export interface IUniverInstanceService {
export const IUniverInstanceService = createIdentifier<IUniverInstanceService>('univer.current');
export class UniverInstanceService extends Disposable implements IUniverInstanceService {
- private _focused: DocumentDataModel | Workbook | SlideDataModel | null = null;
private readonly _focused$ = new BehaviorSubject<Nullable<string>>(null);
readonly focused$ = this._focused$.asObservable();
+ get focused(): Nullable<Workbook | DocumentDataModel | SlideDataModel> {
+ const id = this._focused$.getValue();
+ if (!id) {
+ return null;
+ }
+
+ return this.getUniverSheetInstance(id) || this.getUniverDocInstance(id) || this.getUniverSlideInstance(id);
+ }
private readonly _currentSheet$ = new BehaviorSubject<Nullable<Workbook>>(null);
readonly currentSheet$ = this._currentSheet$.asObservable();
@@ -229,11 +236,12 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
this._currentDoc$.next(this.getUniverDocInstance(id) || null);
}
- getCurrentUniverSheetInstance(): Workbook {
+ getCurrentUniverSheetInstance(): Nullable<Workbook> {
const sheet = this._currentSheet$.getValue();
if (!sheet) {
- throw new Error('No current sheet!');
+ return null;
}
+
return sheet;
}
@@ -256,29 +264,25 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
}
focusUniverInstance(id: string | null): void {
- if (id) {
- this._focused =
- this.getUniverSheetInstance(id) ||
- this.getUniverDocInstance(id) ||
- this.getUniverSlideInstance(id) ||
- null;
- }
-
this._focused$.next(id);
- [FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE].forEach((k) => this._contextService.setContextValue(k, false));
-
- if (this._focused instanceof Workbook) {
+ if (this.focused instanceof Workbook) {
+ this._contextService.setContextValue(FOCUSING_DOC, false);
this._contextService.setContextValue(FOCUSING_SHEET, true);
- } else if (this._focused instanceof DocumentDataModel) {
+ this._contextService.setContextValue(FOCUSING_SLIDE, false);
+ } else if (this.focused instanceof DocumentDataModel) {
this._contextService.setContextValue(FOCUSING_DOC, true);
- } else if (this._focused instanceof SlideDataModel) {
+ this._contextService.setContextValue(FOCUSING_SHEET, false);
+ this._contextService.setContextValue(FOCUSING_SLIDE, false);
+ } else if (this.focused instanceof SlideDataModel) {
+ this._contextService.setContextValue(FOCUSING_DOC, false);
+ this._contextService.setContextValue(FOCUSING_SHEET, false);
this._contextService.setContextValue(FOCUSING_SLIDE, true);
}
}
getFocusedUniverInstance(): Nullable<Workbook | DocumentDataModel | SlideDataModel> {
- return this._focused;
+ return this.focused;
}
getDocumentType(unitId: string): UniverInstanceType {
@@ -312,7 +316,8 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
const index = this._sheets.indexOf(sheet);
this._sheets.splice(index, 1);
this._sheetDisposed$.next(sheet);
- // this.focusUniverInstance(null);
+ this.setCurrentUniverSheetInstance('');
+ this.focusUniverInstance(null);
return true;
}
diff --git a/packages/engine-render/src/render-manager.service.ts b/packages/engine-render/src/render-manager.service.ts
index 232f75e921..e020d8b335 100644
--- a/packages/engine-render/src/render-manager.service.ts
+++ b/packages/engine-render/src/render-manager.service.ts
@@ -35,7 +35,7 @@ export interface IRenderManagerService {
createRenderWithParent(unitId: string, parentUnitId: string): IRender;
createRender(unitId: string): IRender;
addItem(unitId: string, item: IRender): void;
- removeItem(unitId: string): void;
+ removeRender(unitId: string): void;
setCurrent(unitId: string): void;
getRenderById(unitId: string): Nullable<IRender>;
getRenderAll(): Map<string, IRender>;
@@ -163,7 +163,7 @@ export class RenderManagerService implements IRenderManagerService {
this._renderMap.set(unitId, item);
}
- removeItem(unitId: string) {
+ removeRender(unitId: string) {
const item = this._renderMap.get(unitId);
if (item != null) {
this._disposeItem(item);
diff --git a/packages/rpc/src/services/remote-instance/remote-instance.service.ts b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
index fa54dae53d..c99a6308a7 100644
--- a/packages/rpc/src/services/remote-instance/remote-instance.service.ts
+++ b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
@@ -23,7 +23,7 @@ export interface IRemoteSyncMutationOptions extends IExecutionOptions {
fromSync?: boolean;
}
-export const RemoteSyncServiceName = 'univer.remote-sync-service';
+export const RemoteSyncServiceName = 'rpc.remote-sync.service';
/**
* This service is provided by the primary Univer.
*
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
index 1ab3dac715..b7a350d7dc 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
@@ -26,6 +26,9 @@ import { ConditionalFormattingIcon, ConditionalFormattingRuleModel, ConditionalF
import type { IConditionalFormattingCellData } from '@univerjs/sheets-conditional-formatting';
+/**
+ * @todo RenderUnit
+ */
@OnLifecycle(LifecycleStages.Rendered, RenderController)
export class RenderController extends Disposable {
constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@@ -72,14 +75,18 @@ export class RenderController extends Disposable {
// After the conditional formatting is marked dirty to drive a rendering, to trigger the window within the conditional formatting recalculation
this.disposeWithMe(this._conditionalFormattingViewModel.markDirty$.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return false;
+
const worksheet = workbook.getActiveSheet();
return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
})).subscribe(markDirtySkeleton));
// Sort and delete does not mark dirty.
this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return false;
+
const worksheet = workbook.getActiveSheet();
return v.filter((item) => ['sort', 'delete'].includes(item.type) && item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
})).subscribe(markDirtySkeleton));
@@ -87,7 +94,9 @@ export class RenderController extends Disposable {
// Once the calculation is complete, a view update is triggered
// This rendering does not trigger conditional formatting recalculation,because the rule is not mark dirty
this.disposeWithMe(this._conditionalFormattingService.ruleComputeStatus$.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return false;
+
const worksheet = workbook.getActiveSheet();
return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
})).subscribe(markDirtySkeleton));
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
index 33699d5e18..500f751a13 100644
--- a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
+++ b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
@@ -27,47 +27,44 @@ import { AddConditionalRuleMutation, ConditionalFormattingRuleModel, DeleteCondi
import { CF_MENU_OPERATION, OpenConditionalFormattingOperator } from '../commands/operations/open-conditional-formatting-panel';
+const commandList = [SetWorksheetActiveOperation.id, AddConditionalRuleMutation.id, SetConditionalRuleMutation.id, DeleteConditionalRuleMutation.id, MoveConditionalRuleMutation.id];
+
export const FactoryManageConditionalFormattingRule = (componentManager: ComponentManager) => {
const key = 'conditional-formatting-menu-icon';
componentManager.register(key, Conditions);
- return (_accessor: IAccessor) => {
- const localeService = _accessor.get(LocaleService);
- const selectionManagerService = _accessor.get(SelectionManagerService);
- const commandService = _accessor.get(ICommandService);
- const univerInstanceService = _accessor.get(IUniverInstanceService);
- const conditionalFormattingRuleModel = _accessor.get(ConditionalFormattingRuleModel);
-
- const commandList = [SetWorksheetActiveOperation.id, AddConditionalRuleMutation.id, SetConditionalRuleMutation.id, DeleteConditionalRuleMutation.id, MoveConditionalRuleMutation.id];
-
- const clearRangeEnable$ = new Observable<boolean>((subscriber) =>
- merge(
- selectionManagerService.selectionMoveEnd$,
- new Observable<null>((commandSubscribe) => {
- const disposable = commandService.onCommandExecuted((commandInfo) => {
- const { id, params } = commandInfo;
- const unitId = univerInstanceService.getCurrentUniverSheetInstance()!.getUnitId();
- if (commandList.includes(id) && (params as { unitId: string }).unitId === unitId) {
- commandSubscribe.next(null);
- }
- });
- return () => disposable.dispose();
- })
- ).pipe(debounceTime(16)).subscribe(() => {
- const ranges = selectionManagerService.getSelections()?.map((selection) => selection.range) || [];
- const unitId = univerInstanceService.getCurrentUniverSheetInstance()!.getUnitId();
- const subUnitId = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet().getSheetId();
- const allRule = conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId) || [];
- const ruleList = allRule.filter((rule) => rule.ranges.some((ruleRange) => ranges.some((range) => Rectangle.intersects(range, ruleRange))));
- subscriber.next(!!ruleList.length);
+ return (accessor: IAccessor) => {
+ const localeService = accessor.get(LocaleService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const commandService = accessor.get(ICommandService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const conditionalFormattingRuleModel = accessor.get(ConditionalFormattingRuleModel);
+ const clearRangeEnable$ = new Observable<boolean>((subscriber) => merge(
+ selectionManagerService.selectionMoveEnd$,
+ new Observable<null>((commandSubscribe) => {
+ const disposable = commandService.onCommandExecuted((commandInfo) => {
+ const { id, params } = commandInfo;
+ const unitId = univerInstanceService.getCurrentUniverSheetInstance()?.getUnitId();
+ if (commandList.includes(id) && (params as { unitId: string }).unitId === unitId) {
+ commandSubscribe.next(null);
+ }
+ });
+ return () => disposable.dispose();
})
- );
+ ).pipe(debounceTime(16)).subscribe(() => {
+ const ranges = selectionManagerService.getSelections()?.map((selection) => selection.range) || [];
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+ const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), workbook.getActiveSheet().getSheetId()) || [];
+ const ruleList = allRule.filter((rule) => rule.ranges.some((ruleRange) => ranges.some((range) => Rectangle.intersects(range, ruleRange))));
+ subscriber.next(!!ruleList.length);
+ }));
const clearSheetEnable$ = new Observable<boolean>((subscriber) =>
merge(
selectionManagerService.selectionMoveEnd$,
new Observable<null>((commandSubscribe) => {
const disposable = commandService.onCommandExecuted((commandInfo) => {
const { id, params } = commandInfo;
- const unitId = univerInstanceService.getCurrentUniverSheetInstance()!.getUnitId();
+ const unitId = univerInstanceService.getCurrentUniverSheetInstance()?.getUnitId();
if (commandList.includes(id) && (params as { unitId: string }).unitId === unitId) {
commandSubscribe.next(null);
}
@@ -75,54 +72,14 @@ export const FactoryManageConditionalFormattingRule = (componentManager: Compone
return () => disposable.dispose();
})
).pipe(debounceTime(16)).subscribe(() => {
- const unitId = univerInstanceService.getCurrentUniverSheetInstance()!.getUnitId();
- const subUnitId = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet().getSheetId();
- const allRule = conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId) || [];
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+ const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), workbook.getActiveSheet().getSheetId()) || [];
subscriber.next(!!allRule.length);
})
);
const selections$ = new Observable((subscriber) => {
- const commonSelections = [
- {
- label: localeService.t('sheet.cf.ruleType.highlightCell'),
- value: CF_MENU_OPERATION.highlightCell,
- },
- {
- label: localeService.t('sheet.cf.panel.rankAndAverage'),
- value: CF_MENU_OPERATION.rank,
- },
- {
- label: localeService.t('sheet.cf.ruleType.formula'),
- value: CF_MENU_OPERATION.formula,
- },
- {
- label: localeService.t('sheet.cf.ruleType.colorScale'),
- value: CF_MENU_OPERATION.colorScale,
- },
- {
- label: localeService.t('sheet.cf.ruleType.dataBar'),
- value: CF_MENU_OPERATION.dataBar,
- }, {
- label: localeService.t('sheet.cf.ruleType.iconSet'),
- value: CF_MENU_OPERATION.icon,
- },
- {
- label: localeService.t('sheet.cf.menu.manageConditionalFormatting'),
- value: CF_MENU_OPERATION.viewRule,
- }, {
- label: localeService.t('sheet.cf.menu.createConditionalFormatting'),
- value: CF_MENU_OPERATION.createRule,
- },
- {
- label: localeService.t('sheet.cf.menu.clearRangeRules'),
- value: CF_MENU_OPERATION.clearRangeRules,
- disabled: !clearRangeEnable$,
- },
- {
- label: localeService.t('sheet.cf.menu.clearWorkSheetRules'),
- value: CF_MENU_OPERATION.clearWorkSheetRules,
- },
- ];
+ const commonSelections = getCommonSelection(localeService);
clearRangeEnable$.subscribe((v) => {
const item = commonSelections.find((item) => item.value === CF_MENU_OPERATION.clearRangeRules);
if (item) {
@@ -139,7 +96,6 @@ export const FactoryManageConditionalFormattingRule = (componentManager: Compone
});
subscriber.next(commonSelections);
});
-
return {
id: OpenConditionalFormattingOperator.id,
type: MenuItemType.SELECTOR,
@@ -148,7 +104,51 @@ export const FactoryManageConditionalFormattingRule = (componentManager: Compone
icon: key,
tooltip: localeService.t('sheet.cf.title'),
selections: selections$,
- hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.SHEET),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
} as IMenuSelectorItem;
};
};
+
+function getCommonSelection(localeService: LocaleService) {
+ return [
+ {
+ label: localeService.t('sheet.cf.ruleType.highlightCell'),
+ value: CF_MENU_OPERATION.highlightCell,
+ },
+ {
+ label: localeService.t('sheet.cf.panel.rankAndAverage'),
+ value: CF_MENU_OPERATION.rank,
+ },
+ {
+ label: localeService.t('sheet.cf.ruleType.formula'),
+ value: CF_MENU_OPERATION.formula,
+ },
+ {
+ label: localeService.t('sheet.cf.ruleType.colorScale'),
+ value: CF_MENU_OPERATION.colorScale,
+ },
+ {
+ label: localeService.t('sheet.cf.ruleType.dataBar'),
+ value: CF_MENU_OPERATION.dataBar,
+ }, {
+ label: localeService.t('sheet.cf.ruleType.iconSet'),
+ value: CF_MENU_OPERATION.icon,
+ },
+ {
+ label: localeService.t('sheet.cf.menu.manageConditionalFormatting'),
+ value: CF_MENU_OPERATION.viewRule,
+ }, {
+ label: localeService.t('sheet.cf.menu.createConditionalFormatting'),
+ value: CF_MENU_OPERATION.createRule,
+ },
+ {
+ label: localeService.t('sheet.cf.menu.clearRangeRules'),
+ value: CF_MENU_OPERATION.clearRangeRules,
+ disabled: false,
+ },
+ {
+ label: localeService.t('sheet.cf.menu.clearWorkSheetRules'),
+ value: CF_MENU_OPERATION.clearWorkSheetRules,
+ },
+ ];
+}
diff --git a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
index 2981268d77..9d0f332af7 100644
--- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
@@ -41,6 +41,9 @@ const INVALID_MARK = {
},
};
+/**
+ * @todo RenderUnit
+ */
@OnLifecycle(LifecycleStages.Rendered, DataValidationRenderController)
export class DataValidationRenderController extends RxDisposable {
constructor(
@@ -169,7 +172,9 @@ export class DataValidationRenderController extends RxDisposable {
private _initSkeletonChange() {
const markSkeletonDirty = () => {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ unitId, sheetId: subUnitId });
diff --git a/packages/sheets-data-validation/src/controllers/dv.controller.ts b/packages/sheets-data-validation/src/controllers/dv.controller.ts
index 6afad2e2ee..f676ca54d0 100644
--- a/packages/sheets-data-validation/src/controllers/dv.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv.controller.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
+import type { Workbook } from '@univerjs/core';
+import { DisposableCollection, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable, toDisposable } from '@univerjs/core';
import { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';
import { Inject, Injector } from '@wendellhu/redi';
import { DataValidationSingle } from '@univerjs/icons';
@@ -76,9 +77,14 @@ export class DataValidationController extends RxDisposable {
}
private _initInstanceChange() {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ // TODO@wzhudev: sheet added and sheet dispose event
+ }
+
+ private _initOnWorkbook(workbook: Workbook): void {
+ const disposeCollection = new DisposableCollection();
+
this._sheetDataValidationService.switchCurrent(workbook.getUnitId(), workbook.getActiveSheet().getSheetId());
- this.disposeWithMe(
+ disposeCollection.add(toDisposable(
workbook.activeSheet$.subscribe((worksheet) => {
if (worksheet) {
const unitId = workbook.getUnitId();
@@ -86,7 +92,7 @@ export class DataValidationController extends RxDisposable {
this._sheetDataValidationService.switchCurrent(unitId, subUnitId);
}
})
- );
+ ));
}
private _initCommandInterceptor() {
diff --git a/packages/sheets-data-validation/src/validators/list-multiple-validator.ts b/packages/sheets-data-validation/src/validators/list-multiple-validator.ts
index 6e950992fa..a4024824a8 100644
--- a/packages/sheets-data-validation/src/validators/list-multiple-validator.ts
+++ b/packages/sheets-data-validation/src/validators/list-multiple-validator.ts
@@ -85,7 +85,9 @@ export class ListMultipleValidator extends BaseDataValidator {
getList(rule: IDataValidationRule, propUnitId?: string, propSubUnitId?: string) {
const { formula1 = '' } = rule;
const univerInstanceService = this.injector.get(IUniverInstanceService);
- const workbook = (propUnitId ? univerInstanceService.getUniverSheetInstance(propUnitId) : undefined) ?? univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = (propUnitId ? univerInstanceService.getUniverSheetInstance(propUnitId) : undefined) ?? univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return [];
+
const worksheet = (propSubUnitId ? workbook.getSheetBySheetId(propSubUnitId) : undefined) ?? workbook.getActiveSheet();
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
diff --git a/packages/sheets-data-validation/src/validators/list-validator.ts b/packages/sheets-data-validation/src/validators/list-validator.ts
index b6d49a9325..318edfa45f 100644
--- a/packages/sheets-data-validation/src/validators/list-validator.ts
+++ b/packages/sheets-data-validation/src/validators/list-validator.ts
@@ -85,11 +85,15 @@ export class ListValidator extends BaseDataValidator {
getList(rule: IDataValidationRule, currentUnitId?: string, currentSubUnitId?: string) {
const { formula1 = '' } = rule;
const univerInstanceService = this.injector.get(IUniverInstanceService);
- const workbook = (currentUnitId ? univerInstanceService.getUniverSheetInstance(currentUnitId) : undefined) ?? univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = (currentUnitId ? univerInstanceService.getUniverSheetInstance(currentUnitId) : undefined) ?? univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return [];
+
const worksheet = (currentSubUnitId ? workbook.getSheetBySheetId(currentSubUnitId) : undefined) ?? workbook.getActiveSheet();
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
- return isReferenceString(formula1) ? getSheetRangeValueSet(deserializeRangeWithSheet(formula1), this._univerInstanceService, unitId, subUnitId) : deserializeListOptions(formula1);
+ return isReferenceString(formula1)
+ ? getSheetRangeValueSet(deserializeRangeWithSheet(formula1), this._univerInstanceService, unitId, subUnitId)
+ : deserializeListOptions(formula1);
}
getListWithColor(rule: IDataValidationRule, currentUnitId?: string, currentSubUnitId?: string) {
diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.ts
index f60cfcb839..a5ec95c948 100644
--- a/packages/sheets-numfmt/src/menu/menu.ts
+++ b/packages/sheets-numfmt/src/menu/menu.ts
@@ -29,6 +29,7 @@ import type { IAccessor } from '@wendellhu/redi';
import { merge, Observable } from 'rxjs';
import { FormulaDataModel } from '@univerjs/engine-formula';
+import { deriveStateFromActiveSheet$ } from '@univerjs/sheets-ui';
import { MENU_OPTIONS } from '../base/const/MENU-OPTIONS';
import { AddDecimalCommand } from '../commands/commands/add-decimal.command';
import { SetCurrencyCommand } from '../commands/commands/set-currency.command';
@@ -120,7 +121,7 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
const localeService = _accessor.get(LocaleService);
const selectionManagerService = _accessor.get(SelectionManagerService);
- const value$ = new Observable((subscribe) =>
+ const value$ = deriveStateFromActiveSheet$(univerInstanceService, '', ({ workbook, worksheet }) => new Observable((subscribe) =>
merge(
selectionManagerService.selectionMoveEnd$,
new Observable<null>((commandSubscribe) => {
@@ -135,8 +136,6 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
).subscribe(() => {
const selections = selectionManagerService.getSelections();
if (selections && selections[0]) {
- const workbook = univerInstanceService.getCurrentUniverSheetInstance()!;
- const worksheet = workbook.getActiveSheet();
const range = selections[0].range;
const row = range.startRow;
const col = range.startColumn;
@@ -157,13 +156,13 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
value = localeService.t('sheet.numfmt.moreFmt');
}
}
+
subscribe.next(value);
}
})
- );
+ ));
return {
- // icon: 'MoreDownSingle',
label: moreTypeKey,
id: OpenNumfmtPanelOperator.id,
tooltip: 'sheet.numfmt.title',
diff --git a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
index abfccd929c..2402e86ad6 100644
--- a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
@@ -21,6 +21,9 @@ import { IRenderManagerService, Vector2 } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
+/**
+ * @todo RenderUnit
+ */
@OnLifecycle(LifecycleStages.Rendered, CellCustomRenderController)
export class CellCustomRenderController extends Disposable {
private _enterActiveRender: Nullable<{
@@ -46,8 +49,6 @@ export class CellCustomRenderController extends Disposable {
const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());
if (currentRender && currentRender.mainComponent) {
- disposableCollection.dispose();
-
const spreadsheet = currentRender.mainComponent as Spreadsheet;
const getActiveRender = (evt: IPointerEvent | IMouseEvent) => {
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton!;
@@ -159,6 +160,8 @@ export class CellCustomRenderController extends Disposable {
moveDisposable && disposableCollection.add(moveDisposable);
}
}
+
+ disposableCollection.dispose();
});
this.disposeWithMe(disposableCollection);
diff --git a/packages/sheets-ui/src/controllers/contextmenu/contextmenu.controller.ts b/packages/sheets-ui/src/controllers/contextmenu/contextmenu.controller.ts
index 462b68873a..7bb1ec085c 100644
--- a/packages/sheets-ui/src/controllers/contextmenu/contextmenu.controller.ts
+++ b/packages/sheets-ui/src/controllers/contextmenu/contextmenu.controller.ts
@@ -35,6 +35,8 @@ import { getSheetObject } from '../utils/component-tools';
* This controller subscribe to context menu events in
* sheet rendering views and invoke context menu at a correct position
* and with correct menu type.
+ *
+ * @todo RenderUnit
*/
@OnLifecycle(LifecycleStages.Rendered, SheetContextMenuController)
export class SheetContextMenuController extends Disposable {
@@ -48,10 +50,9 @@ export class SheetContextMenuController extends Disposable {
) {
super();
this._univerInstanceService.currentSheet$.subscribe((workbook) => {
- if (workbook == null) {
- throw new Error('workbook is null');
+ if (workbook) {
+ this._addListeners();
}
- this._addListeners();
});
}
diff --git a/packages/sheets-ui/src/controllers/menu/menu-util.ts b/packages/sheets-ui/src/controllers/menu/menu-util.ts
new file mode 100644
index 0000000000..6a64a2da10
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/menu/menu-util.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 type { IUniverInstanceService, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { Observable } from 'rxjs';
+import { map, of, switchMap } from 'rxjs';
+
+interface IActive {
+ workbook: Workbook;
+ worksheet: Worksheet;
+}
+
+function getActiveSheet$(univerInstanceService: IUniverInstanceService): Observable<Nullable<IActive>> {
+ return univerInstanceService.currentSheet$.pipe(switchMap((workbook) =>
+ workbook
+ ? workbook.activeSheet$.pipe(map((worksheet) => {
+ if (!worksheet) return null;
+ return { workbook, worksheet };
+ }))
+ : of(null)));
+}
+
+export function deriveStateFromActiveSheet$<T>(univerInstanceService: IUniverInstanceService, defaultValue: T, callback: (active: IActive) => Observable<T>) {
+ return getActiveSheet$(univerInstanceService).pipe(switchMap((active) => {
+ if (!active) return of(defaultValue);
+ return callback(active);
+ }));
+}
diff --git a/packages/sheets-ui/src/controllers/menu/menu.ts b/packages/sheets-ui/src/controllers/menu/menu.ts
index d04778f62f..887341d4e1 100644
--- a/packages/sheets-ui/src/controllers/menu/menu.ts
+++ b/packages/sheets-ui/src/controllers/menu/menu.ts
@@ -103,6 +103,7 @@ import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../../compone
import { FONT_SIZE_COMPONENT } from '../../components/font-size';
import { MENU_ITEM_INPUT_COMPONENT } from '../../components/menu-item-input';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
+import { deriveStateFromActiveSheet$ } from './menu-util';
export enum SheetMenuPosition {
ROW_HEADER_CONTEXT_MENU = 'rowHeaderContextMenu',
@@ -156,12 +157,11 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
tooltip: 'toolbar.bold',
positions: [MenuPosition.TOOLBAR_START],
disabled$: getCurrentSheetDisabled$(accessor),
- activated$: new Observable<boolean>((subscriber) => {
+ activated$: deriveStateFromActiveSheet$(univerInstanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let isBold = FontWeight.NORMAL;
if (primary != null) {
@@ -174,33 +174,34 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
if (
(id === SetTextSelectionsOperation.id || id === SetInlineFormatCommand.id) &&
- contextService.getContextValue(EDITOR_ACTIVATED) &&
- contextService.getContextValue(FOCUSING_SHEET)
+ contextService.getContextValue(EDITOR_ACTIVATED) &&
+ contextService.getContextValue(FOCUSING_SHEET)
) {
const textRun = getFontStyleAtCursor(accessor);
-
if (textRun == null) {
return;
}
const bl = textRun.ts?.bl;
-
subscriber.next(bl === BooleanNumber.TRUE);
}
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
- let isBold = FontWeight.NORMAL;
+ if (!worksheet) {
+ subscriber.next(false);
+ return;
+ }
+ let isBold = FontWeight.NORMAL;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
isBold = range?.getFontWeight();
}
-
subscriber.next(isBold === FontWeight.BOLD);
+
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -220,12 +221,11 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
tooltip: 'toolbar.italic',
positions: [MenuPosition.TOOLBAR_START],
disabled$: getCurrentSheetDisabled$(accessor),
- activated$: new Observable<boolean>((subscriber) => {
+ activated$: deriveStateFromActiveSheet$(univerInstanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let isItalic = FontItalic.NORMAL;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -237,23 +237,18 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
if (
(id === SetTextSelectionsOperation.id || id === SetInlineFormatCommand.id) &&
- contextService.getContextValue(EDITOR_ACTIVATED) &&
- contextService.getContextValue(FOCUSING_SHEET)
+ contextService.getContextValue(EDITOR_ACTIVATED) &&
+ contextService.getContextValue(FOCUSING_SHEET)
) {
const textRun = getFontStyleAtCursor(accessor);
-
- if (textRun == null) {
- return;
- }
+ if (textRun == null) return;
const it = textRun.ts?.it;
-
subscriber.next(it === BooleanNumber.TRUE);
}
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let isItalic = FontItalic.NORMAL;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -262,7 +257,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
subscriber.next(isItalic === FontItalic.ITALIC);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -282,12 +277,11 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
tooltip: 'toolbar.underline',
positions: [MenuPosition.TOOLBAR_START],
disabled$: getCurrentSheetDisabled$(accessor),
- activated$: new Observable<boolean>((subscriber) => {
+ activated$: deriveStateFromActiveSheet$(univerInstanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let isUnderline;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -299,23 +293,18 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
if (
(id === SetTextSelectionsOperation.id || id === SetInlineFormatCommand.id) &&
- contextService.getContextValue(EDITOR_ACTIVATED) &&
- contextService.getContextValue(FOCUSING_SHEET)
+ contextService.getContextValue(EDITOR_ACTIVATED) &&
+ contextService.getContextValue(FOCUSING_SHEET)
) {
const textRun = getFontStyleAtCursor(accessor);
-
- if (textRun == null) {
- return;
- }
+ if (textRun == null) return;
const ul = textRun.ts?.ul;
-
subscriber.next(ul?.s === BooleanNumber.TRUE);
}
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let isUnderline;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -324,7 +313,8 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
subscriber.next(!!(isUnderline && isUnderline.s));
return disposable.dispose;
- }),
+ })),
+
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -344,12 +334,11 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
tooltip: 'toolbar.strikethrough',
positions: [MenuPosition.TOOLBAR_START],
disabled$: getCurrentSheetDisabled$(accessor),
- activated$: new Observable<boolean>((subscriber) => {
+ activated$: deriveStateFromActiveSheet$(univerInstanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let st;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -361,8 +350,8 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
if (
(id === SetTextSelectionsOperation.id || id === SetInlineFormatCommand.id) &&
- contextService.getContextValue(EDITOR_ACTIVATED) &&
- contextService.getContextValue(FOCUSING_SHEET)
+ contextService.getContextValue(EDITOR_ACTIVATED) &&
+ contextService.getContextValue(FOCUSING_SHEET)
) {
const textRun = getFontStyleAtCursor(accessor);
@@ -377,7 +366,6 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let st;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -386,7 +374,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
subscriber.next(!!(st && st.s));
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -395,6 +383,8 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SelectionManagerService);
+ const defaultValue = FONT_FAMILY_LIST[0].value;
+
return {
id: SetRangeFontFamilyCommand.id,
tooltip: 'toolbar.font',
@@ -410,9 +400,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
value: item.value,
})),
disabled$: getCurrentSheetDisabled$(accessor),
- value$: new Observable((subscriber) => {
- const defaultValue = FONT_FAMILY_LIST[0].value;
-
+ value$: deriveStateFromActiveSheet$(univerInstanceService, defaultValue, ({ worksheet }) => new Observable((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id !== SetRangeValuesMutation.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
@@ -420,7 +408,6 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
}
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ff;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -431,7 +418,6 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ff;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -440,7 +426,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
subscriber.next(ff ?? defaultValue);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -451,6 +437,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
const selectionManagerService = accessor.get(SelectionManagerService);
const contextService = accessor.get(IContextService);
const disabled$ = getCurrentSheetDisabled$(accessor);
+ const DEFAULT_SIZE = 11;
return {
id: SetRangeFontSizeCommand.id,
@@ -468,13 +455,11 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
positions: [MenuPosition.TOOLBAR_START],
selections: FONT_SIZE_LIST,
disabled$,
- value$: new Observable((subscriber) => {
- const DEFAULT_SIZE = 11;
+ value$: deriveStateFromActiveSheet$(univerInstanceService, DEFAULT_SIZE, ({ worksheet }) => new Observable((subscriber) => {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let fs;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -500,7 +485,6 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let fs;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -509,7 +493,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
subscriber.next(fs ?? DEFAULT_SIZE);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
};
}
@@ -639,7 +623,7 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
group: MenuGroup.TOOLBAR_LAYOUT,
type: MenuItemType.SELECTOR,
selections: HORIZONTAL_ALIGN_CHILDREN,
- value$: new Observable<HorizontalAlign>((subscriber) => {
+ value$: deriveStateFromActiveSheet$(univerInstanceService, HorizontalAlign.LEFT, ({ worksheet }) => new Observable<HorizontalAlign>((subscriber) => {
const disposable = accessor.get(ICommandService).onCommandExecuted((c) => {
const id = c.id;
if (id !== SetHorizontalTextAlignCommand.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
@@ -647,7 +631,6 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
}
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ha;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -658,7 +641,6 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ha;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -668,7 +650,7 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
subscriber.next(ha ?? HorizontalAlign.LEFT);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
disabled$: getCurrentSheetDisabled$(accessor),
};
@@ -704,7 +686,7 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
type: MenuItemType.SELECTOR,
positions: [MenuPosition.TOOLBAR_START],
selections: VERTICAL_ALIGN_CHILDREN,
- value$: new Observable<VerticalAlign>((subscriber) => {
+ value$: deriveStateFromActiveSheet$(univerInstanceService, VerticalAlign.TOP, ({ worksheet }) => new Observable<VerticalAlign>((subscriber) => {
const disposable = accessor.get(ICommandService).onCommandExecuted((c) => {
const id = c.id;
if (id !== SetVerticalTextAlignCommand.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
@@ -712,7 +694,6 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
}
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let va;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -723,7 +704,6 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let va;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -733,7 +713,7 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
subscriber.next(va ?? VerticalAlign.TOP);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
disabled$: getCurrentSheetDisabled$(accessor),
};
@@ -769,7 +749,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
type: MenuItemType.SELECTOR,
positions: [MenuPosition.TOOLBAR_START],
selections: TEXT_WRAP_CHILDREN,
- value$: new Observable((subscriber) => {
+ value$: deriveStateFromActiveSheet$<WrapStrategy>(univerInstanceService, WrapStrategy.OVERFLOW, ({ worksheet }) => new Observable((subscriber) => {
const disposable = accessor.get(ICommandService).onCommandExecuted((c) => {
const id = c.id;
if (id !== SetTextWrapCommand.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
@@ -777,7 +757,6 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
}
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ws;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -788,7 +767,6 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let ws;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -798,7 +776,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
subscriber.next(ws ?? WrapStrategy.OVERFLOW);
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
disabled$: getCurrentSheetDisabled$(accessor),
};
@@ -849,7 +827,7 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
type: MenuItemType.SELECTOR,
selections: TEXT_ROTATE_CHILDREN,
positions: [MenuPosition.TOOLBAR_START],
- value$: new Observable<number | string>((subscriber) => {
+ value$: deriveStateFromActiveSheet$(univerInstanceService, 0, ({ worksheet }) => new Observable<number | string>((subscriber) => {
const disposable = accessor.get(ICommandService).onCommandExecuted((c) => {
const id = c.id;
if (id !== SetTextRotationCommand.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
@@ -857,7 +835,6 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
}
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let tr;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -872,7 +849,6 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
});
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
let tr;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -886,7 +862,7 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
}
return disposable.dispose;
- }),
+ })),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
disabled$: getCurrentSheetDisabled$(accessor),
};
@@ -1103,26 +1079,8 @@ export function HideColMenuItemFactory(): IMenuButtonItem {
export function ShowRowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SelectionManagerService);
-
- function hasHiddenRowsInSelections(): boolean {
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
- const rowRanges = selectionManagerService
- .getSelections()
- ?.map((s) => s.range)
- .filter((r) => r.rangeType === RANGE_TYPE.ROW);
-
- return !!rowRanges?.some((range) => {
- for (let r = range.startRow; r <= range.endRow; r++) {
- if (!worksheet.getRowVisible(r)) {
- return true;
- }
- }
-
- return false;
- });
- }
-
const commandService = accessor.get(ICommandService);
+ const affectedCommands = [SetSelectionsOperation, SetRowHiddenMutation, SetRowVisibleMutation].map((c) => c.id);
return {
id: SetSelectedRowsVisibleCommand.id,
@@ -1130,51 +1088,35 @@ export function ShowRowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
type: MenuItemType.BUTTON,
positions: [SheetMenuPosition.ROW_HEADER_CONTEXT_MENU],
title: 'rightClick.showHideRow',
- hidden$: new Observable((subscriber) => {
- const disposable = commandService.onCommandExecuted((c) => {
- if (
- c.id === SetSelectionsOperation.id ||
- c.id === SetRowHiddenMutation.id ||
- c.id === SetRowVisibleMutation.id
- ) {
- subscriber.next(!hasHiddenRowsInSelections());
- }
+ hidden$: deriveStateFromActiveSheet$(univerInstanceService, true, ({ worksheet }) => new Observable((subscriber) => {
+ function hasHiddenRowsInSelections(): boolean {
+ const rowRanges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
+ return !!rowRanges?.some((range) => {
+ for (let r = range.startRow; r <= range.endRow; r++) {
+ if (!worksheet.getRowVisible(r)) return true;
+ }
+
+ return false;
+ });
+ }
+
+
+ const disposable = commandService.onCommandExecuted((command) => {
+ if (affectedCommands.findIndex((c) => c === command.id) !== -1) subscriber.next(!hasHiddenRowsInSelections());
});
// it only shows when selected area has hidden rows
subscriber.next(!hasHiddenRowsInSelections());
return () => disposable.dispose();
- }),
+ })),
};
}
export function ShowColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SelectionManagerService);
-
- function hasHiddenColsInSelections(): boolean {
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
- const colRanges = selectionManagerService
- .getSelections()
- ?.map((s) => s.range)
- .filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
-
- if (!colRanges || colRanges.length === 0) {
- return false;
- }
-
- return !!colRanges.some((range) => {
- for (let r = range.startColumn; r <= range.endColumn; r++) {
- if (!worksheet.getColVisible(r)) {
- return true;
- }
- }
-
- return false;
- });
- }
-
const commandService = accessor.get(ICommandService);
+ const affectedCommands = [SetSelectionsOperation, SetColHiddenMutation, SetColVisibleMutation].map((c) => c.id);
return {
id: SetSelectedColsVisibleCommand.id,
@@ -1182,20 +1124,27 @@ export function ShowColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
type: MenuItemType.BUTTON,
positions: [SheetMenuPosition.COL_HEADER_CONTEXT_MENU],
title: 'rightClick.showHideColumn',
- hidden$: new Observable((subscriber) => {
- const disposable = commandService.onCommandExecuted((c) => {
- if (
- c.id === SetSelectionsOperation.id ||
- c.id === SetColHiddenMutation.id ||
- c.id === SetColVisibleMutation.id
- ) {
- subscriber.next(!hasHiddenColsInSelections());
- }
+ hidden$: deriveStateFromActiveSheet$(univerInstanceService, true, ({ worksheet }) => new Observable((subscriber) => {
+ function hasHiddenColsInSelections(): boolean {
+ const colRanges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
+ if (!colRanges || colRanges.length === 0) return false;
+
+ return !!colRanges.some((range) => {
+ for (let r = range.startColumn; r <= range.endColumn; r++) {
+ if (!worksheet.getColVisible(r)) return true;
+ }
+
+ return false;
+ });
+ }
+
+ const disposable = commandService.onCommandExecuted((commandInfo) => {
+ if (affectedCommands.findIndex((c) => c === commandInfo.id) !== -1) subscriber.next(!hasHiddenColsInSelections());
});
subscriber.next(!hasHiddenColsInSelections());
return () => disposable.dispose();
- }),
+ })),
};
}
@@ -1219,16 +1168,11 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
max: 1000,
},
},
- value$: new Observable((subscriber) => {
+ value$: deriveStateFromActiveSheet$(univerInstanceService, 0, ({ worksheet }) => new Observable((subscriber) => {
function update() {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
- let rowHeight;
- if (primary != null) {
- rowHeight = worksheet.getRowHeight(primary.startRow);
- }
-
- subscriber.next(rowHeight ?? 0);
+ const rowHeight = primary ? worksheet.getRowHeight(primary.startRow) : 0;
+ subscriber.next(rowHeight);
}
const disposable = commandService.onCommandExecuted((c) => {
@@ -1240,7 +1184,7 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
update();
return disposable.dispose;
- }),
+ })),
};
}
@@ -1264,11 +1208,9 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
max: 1000,
},
},
- value$: new Observable((subscriber) => {
+ value$: deriveStateFromActiveSheet$(univerInstanceService, 0, ({ worksheet }) => new Observable((subscriber) => {
function update() {
const primary = selectionManagerService.getLast()?.primary;
- const worksheet = univerInstanceService.getCurrentUniverSheetInstance()!.getActiveSheet();
-
let colWidth: number = 0;
if (primary != null) {
colWidth = worksheet.getColumnWidth(primary.startColumn);
@@ -1286,29 +1228,23 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
update();
return disposable.dispose;
- }),
+ })),
};
}
function getFontStyleAtCursor(accessor: IAccessor) {
const univerInstanceService = accessor.get(IUniverInstanceService);
const textSelectionService = accessor.get(TextSelectionManagerService);
+
const editorDataModel = univerInstanceService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
const activeTextRange = textSelectionService.getActiveRange();
- if (editorDataModel == null || activeTextRange == null) {
- return;
- }
+ if (editorDataModel == null || activeTextRange == null) return null;
const textRuns = editorDataModel.getBody()?.textRuns;
-
- if (textRuns == null) {
- return;
- }
+ if (textRuns == null) return;
const { startOffset } = activeTextRange;
-
const textRun = textRuns.find(({ st, ed }) => startOffset >= st && startOffset <= ed);
-
return textRun;
}
diff --git a/packages/sheets-ui/src/controllers/selection.controller.ts b/packages/sheets-ui/src/controllers/selection.controller.ts
index c8ccbc257d..427334a18a 100644
--- a/packages/sheets-ui/src/controllers/selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/selection.controller.ts
@@ -393,7 +393,9 @@ export class SelectionController extends Disposable {
}
private _move(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+
const unitId = workbook.getUnitId();
const sheetId = workbook.getActiveSheet().getSheetId();
const current = this._selectionManagerService.getCurrent();
diff --git a/packages/sheets-ui/src/controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
index aae5b3dccb..0e8578e864 100644
--- a/packages/sheets-ui/src/controllers/sheet-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
@@ -17,12 +17,12 @@
import type { ICommandInfo } from '@univerjs/core';
import {
CommandType,
- Disposable,
ICommandService,
IContextService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
+ RxDisposable,
} from '@univerjs/core';
import type { Rect, SpreadsheetColumnHeader, SpreadsheetRowHeader } from '@univerjs/engine-render';
import { IRenderManagerService, RENDER_RAW_FORMULA_KEY, Spreadsheet } from '@univerjs/engine-render';
@@ -33,7 +33,7 @@ import {
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
-import { distinctUntilChanged } from 'rxjs';
+import { distinctUntilChanged, takeUntil } from 'rxjs';
import { SHEET_VIEW_KEY } from '../common/keys';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
@@ -42,8 +42,11 @@ interface ISetWorksheetMutationParams {
subUnitId: string;
}
+/**
+ * @todo RenderUnit. This should be merged with `SheetCanvasView`.
+ */
@OnLifecycle(LifecycleStages.Ready, SheetRenderController)
-export class SheetRenderController extends Disposable {
+export class SheetRenderController extends RxDisposable {
constructor(
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@IContextService private readonly _contextService: IContextService,
@@ -58,6 +61,7 @@ export class SheetRenderController extends Disposable {
private _init() {
this._initialRenderRefresh();
+ this._initSheetDisposeListener();
this._initCommandListener();
this._initContextListener();
}
@@ -65,33 +69,21 @@ export class SheetRenderController extends Disposable {
private _initialRenderRefresh(): void {
this.disposeWithMe(
this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- return;
- }
+ if (!param) return null;
const { skeleton: spreadsheetSkeleton, unitId, sheetId } = param;
-
const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
-
const worksheet = workbook?.getSheetBySheetId(sheetId);
-
- if (workbook == null || worksheet == null) {
- return;
- }
+ if (workbook == null || worksheet == null) return;
const currentRender = this._renderManagerService.getRenderById(unitId);
-
- if (currentRender == null) {
- return;
- }
+ if (currentRender == null) return;
const { mainComponent, components } = currentRender;
-
const spreadsheet = mainComponent as Spreadsheet;
const spreadsheetRowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetRowHeader;
const spreadsheetColumnHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
const spreadsheetLeftTopPlaceholder = components.get(SHEET_VIEW_KEY.LEFT_TOP) as Rect;
-
const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;
spreadsheet?.updateSkeleton(spreadsheetSkeleton);
@@ -105,17 +97,29 @@ export class SheetRenderController extends Disposable {
);
}
+ private _initSheetDisposeListener(): void {
+ this._univerInstanceService.sheetDisposed$
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((workbook) => {
+ const unitId = workbook.getUnitId();
+
+ this._sheetSkeletonManagerService.removeSkeleton({ unitId });
+ });
+ }
+
private _initCommandListener(): void {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
- const unitId = workbook.getUnitId();
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+ const unitId = workbook.getUnitId();
if (COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id)) {
const worksheet = workbook.getActiveSheet();
const sheetId = worksheet.getSheetId();
const params = command.params;
const { unitId, subUnitId } = params as ISetWorksheetMutationParams;
+
if (!(unitId === workbook.getUnitId() && subUnitId === worksheet.getSheetId())) {
return;
}
@@ -150,14 +154,15 @@ export class SheetRenderController extends Disposable {
}
private _initContextListener(): void {
- this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY).pipe(
- distinctUntilChanged()
- ).subscribe(() => {
- this._renderManagerService.getRenderAll().forEach((renderer) => {
- if (renderer.mainComponent instanceof Spreadsheet) {
- renderer.mainComponent.makeForceDirty(true);
- }
+ // If we toggle the raw formula, we need to refresh all spreadsheets.
+ this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY)
+ .pipe(distinctUntilChanged(), takeUntil(this.dispose$))
+ .subscribe(() => {
+ this._renderManagerService.getRenderAll().forEach((renderer) => {
+ if (renderer.mainComponent instanceof Spreadsheet) {
+ renderer.mainComponent.makeForceDirty(true);
+ }
+ });
});
- });
}
}
diff --git a/packages/sheets-ui/src/controllers/utils/component-tools.ts b/packages/sheets-ui/src/controllers/utils/component-tools.ts
index 44c47c23ff..b37a24e4f3 100644
--- a/packages/sheets-ui/src/controllers/utils/component-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/component-tools.ts
@@ -43,15 +43,12 @@ export function getSheetObject(
univerInstanceService: IUniverInstanceService,
renderManagerService: IRenderManagerService
): Nullable<ISheetObjectParam> {
- const workbook = univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return null;
const unitId = workbook.getUnitId();
-
const currentRender = renderManagerService.getRenderById(unitId);
-
- if (currentRender == null) {
- return;
- }
+ if (currentRender == null) return null;
const { components, mainComponent, scene, engine } = currentRender;
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index a0a7f54467..3bc5141798 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -23,6 +23,7 @@ export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from './comman
export { SetCellEditVisibleArrowOperation, SetCellEditVisibleOperation } from './commands/operations/cell-edit.operation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
export { ScrollController } from './controllers/scroll.controller';
+export { deriveStateFromActiveSheet$ } from './controllers/menu/menu-util';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export {
ResetScrollCommand,
diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts
index 2bce7657e4..a7bc713907 100644
--- a/packages/sheets-ui/src/services/hover-manager.service.ts
+++ b/packages/sheets-ui/src/services/hover-manager.service.ts
@@ -52,20 +52,19 @@ export class HoverManagerService {
) { }
private _calcActiveCell() {
- if (!this._lastPosition) {
- return;
- }
+ if (!this._lastPosition) return;
+
const { offsetX, offsetY } = this._lastPosition;
- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (!workbook) return;
+
const worksheet = workbook.getActiveSheet();
const skeletonParam = this._sheetSkeletonManagerService.getCurrent();
const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());
const scrollInfo = this._scrollManagerService.getCurrentScroll();
- if (!skeletonParam || !scrollInfo || !currentRender) {
- return;
- }
+ if (!skeletonParam || !scrollInfo || !currentRender) return;
const { scene } = currentRender;
diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
index 32277603d8..4766238936 100644
--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
@@ -32,7 +32,7 @@ export interface ISheetSkeletonManagerParam {
export interface ISheetSkeletonManagerSearch {
unitId: string;
sheetId: string;
- commandId?: string;
+ commandId?: string; // WTF: why?
}
/**
@@ -57,7 +57,6 @@ export class SheetSkeletonManagerService implements IDisposable {
* CurrentSkeletonBefore for pre-triggered logic during registration
*/
private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<ISheetSkeletonManagerParam>>(null);
-
readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
constructor(
@@ -80,6 +79,15 @@ export class SheetSkeletonManagerService implements IDisposable {
this._setCurrent(searchParam);
}
+ removeSkeleton(searchParam: Pick<ISheetSkeletonManagerSearch, 'unitId'>) {
+ const index = this._sheetSkeletonParam.findIndex((param) => param.unitId === searchParam.unitId);
+ if (index !== -1) {
+ this._sheetSkeletonParam.splice(index, 1);
+ this._currentSkeletonBefore$.next(null);
+ this._currentSkeleton$.next(null);
+ }
+ }
+
private _compareSearch(param1: Nullable<ISheetSkeletonManagerSearch>, param2: Nullable<ISheetSkeletonManagerSearch>) {
if (param1 == null || param2 == null) {
return false;
@@ -119,9 +127,7 @@ export class SheetSkeletonManagerService implements IDisposable {
this._currentSkeleton = searchParam;
const nextParam = this.getCurrent();
-
this._currentSkeletonBefore$.next(nextParam);
-
this._currentSkeleton$.next(nextParam);
}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 143f0aa6d9..89ae211348 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -34,13 +34,11 @@ enum ArrowDirection {
Up,
}
-// eslint-disable-next-line max-lines-per-function
export function FormulaBar() {
const [iconStyle, setIconStyle] = useState<string>(styles.formulaGrey);
const [arrowDirection, setArrowDirection] = useState<ArrowDirection>(ArrowDirection.Down);
const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
-
const editorBridgeService = useDependency(IEditorBridgeService);
const INITIAL_SNAPSHOT = {
@@ -75,10 +73,12 @@ export function FormulaBar() {
};
useEffect(() => {
- editorBridgeService.visible$.subscribe((visibleInfo) => {
+ const subscription = editorBridgeService.visible$.subscribe((visibleInfo) => {
setIconStyle(visibleInfo.visible ? styles.formulaActive : styles.formulaGrey);
});
- }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+
+ return () => subscription.unsubscribe();
+ }, [editorBridgeService.visible$]);
function resizeCallBack(editor: Nullable<HTMLDivElement>) {
if (editor == null) {
diff --git a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
index 0e720321fb..357640fe7c 100644
--- a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
@@ -77,12 +77,6 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
};
const forceUpdate = useUpdate();
- const sheetObject = getSheetObject(univerInstanceService, renderManagerService);
-
- if (sheetObject == null) {
- return null;
- }
- const { scene } = sheetObject;
useEffect(() => {
const endCommands = [
@@ -149,6 +143,11 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
if (anchor.col < 0 || anchor.row < 0) {
return null;
}
+
+ const sheetObject = getSheetObject(univerInstanceService, renderManagerService);
+ if (!sheetObject) return null;
+
+ const { scene } = sheetObject;
const skeleton = sheetSkeletonManagerService.getCurrent()?.skeleton;
const viewport = selectionRenderService.getViewPort();
const scaleX = scene?.scaleX;
diff --git a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
index e889f422bc..74e614e3f7 100644
--- a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
@@ -34,10 +34,10 @@ export const SheetBar = () => {
const [rightScrollState, setRightScrollState] = useState(true);
const commandService = useDependency(ICommandService);
- const sheetbarService = useDependency(ISheetBarService);
+ const sheetBarService = useDependency(ISheetBarService);
useEffect(() => {
- const subscription = sheetbarService.scroll$.subscribe((state: IScrollState) => {
+ const subscription = sheetBarService.scroll$.subscribe((state: IScrollState) => {
updateScrollButtonState(state);
});
@@ -56,16 +56,16 @@ export const SheetBar = () => {
const addSheet = () => {
commandService.executeCommand(InsertSheetCommand.id);
setTimeout(() => {
- sheetbarService.setAddSheet(0);
+ sheetBarService.setAddSheet(0);
}, 0);
};
const handleScrollLeft = () => {
- sheetbarService.setScrollX(-SCROLL_WIDTH);
+ sheetBarService.setScrollX(-SCROLL_WIDTH);
};
const handleScrollRight = () => {
- sheetbarService.setScrollX(SCROLL_WIDTH);
+ sheetBarService.setScrollX(SCROLL_WIDTH);
};
return (
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
index 526c7eaec4..1f9b02b635 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-menu/SheetBarMenu.tsx
@@ -29,7 +29,8 @@ import {
SetWorksheetShowCommand,
} from '@univerjs/sheets';
import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useEffect, useState } from 'react';
+import React, { useCallback, useEffect, useState } from 'react';
+import { useObservable } from '@univerjs/ui';
import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { SheetBarButton } from '../sheet-bar-button/SheetBarButton';
@@ -56,11 +57,11 @@ export function SheetBarMenu(props: ISheetBarMenuProps) {
const univerInstanceService = useDependency(IUniverInstanceService);
const commandService = useDependency(ICommandService);
const sheetBarService = useDependency(ISheetBarService);
- const workbook = univerInstanceService.getCurrentUniverSheetInstance()!;
+ const workbook = useObservable(univerInstanceService.currentSheet$);
const handleClick = (item: ISheetBarMenuItem) => {
const { sheetId } = item;
- if (!sheetId) return;
+ if (!sheetId || !workbook) return;
if (item.hidden) {
commandService.executeCommand(SetWorksheetShowCommand.id, {
@@ -76,25 +77,23 @@ export function SheetBarMenu(props: ISheetBarMenuProps) {
setVisible(false);
};
- useEffect(() => {
- statusInit();
+ const statusInit = useCallback(() => {
+ if (!workbook) return;
- const _disposables = new DisposableCollection();
-
- _disposables.add(setupStatusUpdate());
- _disposables.add(
- sheetBarService.registerSheetBarMenuHandler({
- handleSheetBarMenu,
- })
- );
+ const sheets = workbook.getSheets();
+ const activeSheet = workbook.getActiveSheet();
+ const worksheetMenuItems = sheets.map((sheet, index) => ({
+ label: sheet.getName(),
+ index: `${index}`,
+ sheetId: sheet.getSheetId(),
+ hidden: sheet.isSheetHidden() === BooleanNumber.TRUE,
+ selected: activeSheet === sheet,
+ }));
- return () => {
- // Clean up disposable when the component unmounts
- _disposables.dispose();
- };
- }, []);
+ setMenu(worksheetMenuItems);
+ }, [workbook]);
- const setupStatusUpdate = () =>
+ const setupStatusUpdate = useCallback(() =>
commandService.onCommandExecuted((commandInfo: ICommandInfo) => {
switch (commandInfo.id) {
case SetWorksheetHideMutation.id:
@@ -108,21 +107,7 @@ export function SheetBarMenu(props: ISheetBarMenuProps) {
default:
break;
}
- });
-
- const statusInit = () => {
- const sheets = workbook.getSheets();
- const activeSheet = workbook.getActiveSheet();
- const worksheetMenuItems = sheets.map((sheet, index) => ({
- label: sheet.getName(),
- index: `${index}`,
- sheetId: sheet.getSheetId(),
- hidden: sheet.isSheetHidden() === BooleanNumber.TRUE,
- selected: activeSheet === sheet,
- }));
-
- setMenu(worksheetMenuItems);
- };
+ }), [commandService, statusInit]);
function handleSheetBarMenu() {
setVisible(true);
@@ -132,6 +117,16 @@ export function SheetBarMenu(props: ISheetBarMenuProps) {
setVisible(visible);
};
+ useEffect(() => {
+ statusInit();
+
+ const disposables = new DisposableCollection();
+ disposables.add(setupStatusUpdate());
+ disposables.add(sheetBarService.registerSheetBarMenuHandler({ handleSheetBarMenu }));
+
+ return () => disposables.dispose();
+ }, [setupStatusUpdate, sheetBarService, statusInit, workbook]);
+
return (
<Dropdown
placement="topLeft"
@@ -150,16 +145,10 @@ export function SheetBarMenu(props: ISheetBarMenuProps) {
>
<span className={styles.sheetBarMenuItemIcon}>
{item.selected
- ? (
- <CheckMarkSingle />
- )
+ ? <CheckMarkSingle />
: item.hidden
- ? (
- <EyelashSingle />
- )
- : (
- <CheckMarkSingle />
- )}
+ ? <EyelashSingle />
+ : <CheckMarkSingle />}
</span>
<span className={styles.sheetBarMenuItemLabel}>{item.label}</span>
</li>
diff --git a/packages/sheets-ui/src/views/sheet-canvas-view.ts b/packages/sheets-ui/src/views/sheet-canvas-view.ts
index 80f5b90ee8..ff667a3488 100644
--- a/packages/sheets-ui/src/views/sheet-canvas-view.ts
+++ b/packages/sheets-ui/src/views/sheet-canvas-view.ts
@@ -30,7 +30,7 @@ import {
Viewport,
} from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, takeUntil } from 'rxjs';
import { SetScrollRelativeCommand } from '../commands/commands/set-scroll.command';
import {
@@ -39,15 +39,15 @@ import {
SHEET_VIEW_KEY,
VIEWPORT_KEY,
} from '../common/keys';
-import { ISelectionRenderService } from '../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
+/**
+ * @todo RenderUnit
+ */
@OnLifecycle(LifecycleStages.Ready, SheetCanvasView)
export class SheetCanvasView extends RxDisposable {
private _scene!: Scene;
- private _currentWorkbook!: Workbook;
-
private readonly _fps$ = new BehaviorSubject<string>('');
readonly fps$ = this._fps$.asObservable();
@@ -56,8 +56,6 @@ export class SheetCanvasView extends RxDisposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ISelectionRenderService
- private readonly _selectionRenderService: ISelectionRenderService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
super();
@@ -73,31 +71,28 @@ export class SheetCanvasView extends RxDisposable {
}
private _init() {
- this._univerInstanceService.currentSheet$.subscribe((workbook) => {
- this._create(workbook);
- });
+ this._univerInstanceService.currentSheet$.pipe(takeUntil(this.dispose$)).subscribe((workbook) => this._create(workbook));
+ this._univerInstanceService.sheetDisposed$.pipe(takeUntil(this.dispose$)).subscribe((workbook) => this._dispose(workbook));
+ this._univerInstanceService.getAllUniverSheetsInstance().forEach((workbook) => this._create(workbook));
+ }
- this._univerInstanceService.getAllUniverSheetsInstance().forEach((workbook) => {
- this._create(workbook);
- });
+ private _dispose(workbook: Workbook) {
+ const unitId = workbook.getUnitId();
+ this._renderManagerService.removeRender(unitId);
}
private _create(workbook: Nullable<Workbook>) {
- if (workbook == null) {
+ if (!workbook) {
return;
- // throw new Error('workbook is null');
}
const unitId = workbook.getUnitId();
if (!this._renderManagerService.has(unitId)) {
- this._currentWorkbook = workbook;
- this._addNewRender();
+ this._addNewRender(workbook);
}
}
- private _addNewRender() {
- const workbook = this._currentWorkbook;
-
+ private _addNewRender(workbook: Workbook) {
const unitId = workbook.getUnitId();
const container = workbook.getContainer();
@@ -129,7 +124,7 @@ export class SheetCanvasView extends RxDisposable {
scene.addLayer(new Layer(scene, [], 0), new Layer(scene, [], 2));
if (currentRender != null) {
- this._addComponent(currentRender);
+ this._addComponent(currentRender, workbook);
}
const should = workbook.getShouldRenderLoopImmediately();
@@ -144,18 +139,16 @@ export class SheetCanvasView extends RxDisposable {
this._renderManagerService.setCurrent(unitId);
}
- private _addComponent(currentRender: IRender) {
+ private _addComponent(currentRender: IRender, workbook: Workbook) {
const scene = this._scene;
- const workbook = this._currentWorkbook;
-
const worksheet = workbook.getActiveSheet();
const unitId = workbook.getUnitId();
const sheetId = worksheet.getSheetId();
- const viewMain = this._addViewport(worksheet);
+ const _viewMain = this._addViewport(worksheet);
const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN);
const spreadsheetRowHeader = new SpreadsheetRowHeader(SHEET_VIEW_KEY.ROW);
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index 5d9e267874..d9d16320a1 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -14,7 +14,10 @@
* limitations under the License.
*/
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { IUniverInstanceService } from '@univerjs/core';
import React from 'react';
+import { useObservable } from '@univerjs/ui';
import { CountBar } from '../count-bar/CountBar';
import { EditorContainer } from '../editor-container/EditorContainer';
@@ -25,6 +28,10 @@ import { StatusBar } from '../status-bar/StatusBar';
import styles from './index.module.less';
export function RenderSheetFooter() {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = useObservable(univerInstanceService.currentSheet$);
+ if (!workbook) return null;
+
return (
<section className={styles.sheetContainer} data-range-selector>
<SheetBar />
@@ -35,12 +42,20 @@ export function RenderSheetFooter() {
}
export function RenderSheetHeader() {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = useObservable(univerInstanceService.currentSheet$);
+ if (!workbook) return null;
+
return (
<FormulaBar />
);
}
export function RenderSheetContent() {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = useObservable(univerInstanceService.currentSheet$);
+ if (!workbook) return null;
+
return (
<>
<EditorContainer />
diff --git a/packages/sheets/src/basics/const/command-listener-const.ts b/packages/sheets/src/basics/const/command-listener-const.ts
index c5d76d62f4..c26c39a723 100644
--- a/packages/sheets/src/basics/const/command-listener-const.ts
+++ b/packages/sheets/src/basics/const/command-listener-const.ts
@@ -31,6 +31,9 @@ import {
} from '../../commands/mutations/set-worksheet-row-height.mutation';
import { SetWorksheetActiveOperation } from '../../commands/operations/set-worksheet-active.operation';
+/**
+ * Mutations those will trigger the skeleton change.
+ */
export const COMMAND_LISTENER_SKELETON_CHANGE = [
SetWorksheetRowHeightMutation.id,
SetWorksheetRowIsAutoHeightMutation.id,
diff --git a/packages/sheets/src/services/permission/sheet-permission.service.ts b/packages/sheets/src/services/permission/sheet-permission.service.ts
index fe19217182..98c62b9f7f 100644
--- a/packages/sheets/src/services/permission/sheet-permission.service.ts
+++ b/packages/sheets/src/services/permission/sheet-permission.service.ts
@@ -14,27 +14,33 @@
* limitations under the License.
*/
-import type { PermissionService } from '@univerjs/core';
+import type { PermissionService, Workbook } from '@univerjs/core';
import {
- Disposable,
+ DisposableCollection,
getTypeFromPermissionItemList,
IPermissionService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
+ PermissionStatus,
+ RxDisposable,
toDisposable,
UniverEditablePermissionPoint,
} from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
import { Inject } from '@wendellhu/redi';
-import { map } from 'rxjs/operators';
+import { map, takeUntil } from 'rxjs/operators';
+import { of } from 'rxjs';
import { SetRangeValuesCommand } from '../../commands/commands/set-range-values.command';
import { INTERCEPTOR_POINT } from '../sheet-interceptor/interceptor-const';
import { SheetInterceptorService } from '../sheet-interceptor/sheet-interceptor.service';
import { SheetEditablePermission } from './permission-point';
@OnLifecycle(LifecycleStages.Ready, SheetPermissionService)
-export class SheetPermissionService extends Disposable {
+export class SheetPermissionService extends RxDisposable {
+ private _disposableByUnit = new Map<string, IDisposable>();
+
constructor(
@Inject(IPermissionService) private _permissionService: PermissionService,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@@ -49,30 +55,41 @@ export class SheetPermissionService extends Disposable {
const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
if (!workbook) return;
+ this._interceptWorkbook(workbook);
+ this._univerInstanceService.sheetAdded$.pipe(takeUntil(this.dispose$)).subscribe((workbook) => this._interceptWorkbook(workbook));
+ this._univerInstanceService.sheetDisposed$.pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
+ const unitId = workbook.getUnitId();
+ this._disposableByUnit.get(unitId)?.dispose();
+ this._disposableByUnit.delete(unitId);
+ });
+ }
+
+ private _interceptWorkbook(workbook: Workbook): void {
+ const disposableCollection = new DisposableCollection();
const unitId = workbook.getUnitId();
workbook.getSheets().forEach((worksheet) => {
const subUnitId = worksheet.getSheetId();
const sheetPermission = new SheetEditablePermission(unitId, subUnitId);
this._permissionService.addPermissionPoint(workbook.getUnitId(), sheetPermission);
});
- this.disposeWithMe(
- toDisposable(
- workbook.sheetCreated$.subscribe((worksheet) => {
- const subUnitId = worksheet.getSheetId();
- const sheetPermission = new SheetEditablePermission(unitId, subUnitId);
- this._permissionService.addPermissionPoint(workbook.getUnitId(), sheetPermission);
- })
- )
- );
- this.disposeWithMe(
- toDisposable(
- workbook.sheetDisposed$.subscribe((worksheet) => {
- const subUnitId = worksheet.getSheetId();
- const sheetPermission = new SheetEditablePermission(unitId, subUnitId);
- this._permissionService.deletePermissionPoint(workbook.getUnitId(), sheetPermission.id);
- })
- )
- );
+
+ disposableCollection.add(toDisposable(
+ workbook.sheetCreated$.subscribe((worksheet) => {
+ const subUnitId = worksheet.getSheetId();
+ const sheetPermission = new SheetEditablePermission(unitId, subUnitId);
+ this._permissionService.addPermissionPoint(workbook.getUnitId(), sheetPermission);
+ })
+ ));
+
+ disposableCollection.add(toDisposable(
+ workbook.sheetDisposed$.subscribe((worksheet) => {
+ const subUnitId = worksheet.getSheetId();
+ const sheetPermission = new SheetEditablePermission(unitId, subUnitId);
+ this._permissionService.deletePermissionPoint(workbook.getUnitId(), sheetPermission.id);
+ })
+ ));
+
+ this._disposableByUnit.set(unitId, disposableCollection);
}
private _interceptCommandPermission() {
@@ -102,7 +119,7 @@ export class SheetPermissionService extends Disposable {
getEditable$(unitId?: string, sheetId?: string) {
const workbook = this._univerInstanceService.getCurrentUniverSheetInstance()!;
if (!workbook) {
- throw new Error('[SheetPermissionService]: trying to get permission from a non-existing sheet.');
+ return of({ value: false, status: PermissionStatus.INIT });
}
const _unitId = unitId || workbook.getUnitId();
diff --git a/packages/sheets/src/services/permission/tool.ts b/packages/sheets/src/services/permission/tool.ts
index ced3fee7d5..7b456b8922 100644
--- a/packages/sheets/src/services/permission/tool.ts
+++ b/packages/sheets/src/services/permission/tool.ts
@@ -16,7 +16,7 @@
import { IUniverInstanceService } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { Observable } from 'rxjs';
+import { map } from 'rxjs';
import { SheetPermissionService } from './sheet-permission.service';
@@ -27,12 +27,5 @@ export function getCurrentSheetDisabled$(accessor: IAccessor) {
const unitId = univerInstanceService.getCurrentUniverSheetInstance()?.getUnitId();
const sheetId = univerInstanceService.getCurrentUniverSheetInstance()?.getActiveSheet().getSheetId();
- return new Observable<boolean>((subscriber) => {
- const permission$ = sheetPermissionService.getEditable$(unitId, sheetId)?.subscribe((e) => {
- subscriber.next(!e.value);
- });
- return () => {
- permission$?.unsubscribe();
- };
- });
+ return sheetPermissionService.getEditable$(unitId, sheetId)?.pipe(map((e) => !e.value));
}
diff --git a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
index 20ed257965..17c2fcda25 100644
--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
@@ -60,20 +60,12 @@ export class SheetInterceptorService extends Disposable {
// When a workbook is created or a worksheet is added after when workbook is created,
// `SheetInterceptorService` inject interceptors to worksheet instances to it.
- this.disposeWithMe(
- toDisposable(
- this._univerInstanceService.sheetAdded$.subscribe((workbook) => {
- this._interceptWorkbook(workbook);
- })
- )
- );
- this.disposeWithMe(
- toDisposable(
- this._univerInstanceService.sheetDisposed$.subscribe((workbook) =>
- this._disposeWorkbookInterceptor(workbook)
- )
- )
- );
+ this.disposeWithMe(this._univerInstanceService.sheetAdded$.subscribe((workbook) => {
+ this._interceptWorkbook(workbook);
+ }));
+ this.disposeWithMe(this._univerInstanceService.sheetDisposed$.subscribe((workbook) =>
+ this._disposeWorkbookInterceptor(workbook)
+ ));
// register default viewModel interceptor
this.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
@@ -160,6 +152,8 @@ export class SheetInterceptorService extends Disposable {
const interceptViewModel = (worksheet: Worksheet): void => {
const subUnitId = worksheet.getSheetId();
worksheet.__interceptViewModel((viewModel) => {
+ const disposableId = getWorksheetDisposableID(unitId, worksheet);
+
const sheetDisposables = new DisposableCollection();
const cellInterceptorDisposable = viewModel.registerCellContentInterceptor({
getCell(row: number, col: number): Nullable<ICellData> {
@@ -176,8 +170,11 @@ export class SheetInterceptorService extends Disposable {
);
},
});
+
sheetDisposables.add(cellInterceptorDisposable);
- self._worksheetDisposables.set(getWorksheetDisposableID(unitId, worksheet), sheetDisposables);
+ sheetDisposables.add(toDisposable(() => self._workbookDisposables.delete(disposableId)));
+
+ self._worksheetDisposables.set(disposableId, sheetDisposables);
});
};
@@ -185,18 +182,13 @@ export class SheetInterceptorService extends Disposable {
// worksheet creation event to intercept newly created worksheet.
workbook.getSheets().forEach((worksheet) => interceptViewModel(worksheet));
disposables.add(toDisposable(workbook.sheetCreated$.subscribe((worksheet) => interceptViewModel(worksheet))));
- disposables.add(
- toDisposable(
- workbook.sheetDisposed$.subscribe((worksheet) => this._disposeSheetInterceptor(unitId, worksheet))
- )
- );
// Dispose all underlying interceptors when workbook is disposed.
- disposables.add(
- toDisposable(() =>
- workbook.getSheets().forEach((worksheet) => this._disposeSheetInterceptor(unitId, worksheet))
- )
- );
+ disposables.add(toDisposable(() => workbook.getSheets().forEach((worksheet) => this._disposeSheetInterceptor(unitId, worksheet))));
+ // Dispose interceptor when a worksheet is destroyed.
+ disposables.add(toDisposable(workbook.sheetDisposed$.subscribe((worksheet) => this._disposeSheetInterceptor(unitId, worksheet))));
+
+ this._workbookDisposables.set(unitId, disposables);
}
private _disposeWorkbookInterceptor(workbook: Workbook): void {
diff --git a/packages/ui/src/components/hooks/observable.ts b/packages/ui/src/components/hooks/observable.ts
index ae2d96b7c4..8a353e9e1b 100644
--- a/packages/ui/src/components/hooks/observable.ts
+++ b/packages/ui/src/components/hooks/observable.ts
@@ -57,9 +57,12 @@ export function useObservable<T>(observable: Nullable<ObservableOrFn<T>>, defaul
const depsRef = useRef<any[] | undefined>(deps ?? undefined);
const initializedRef = useRef<boolean>(false);
- const [value, setValue] = useState<T | undefined>(() => {
- let innerDefaultValue: T | undefined = defaultValue;
+ // This state is only for trigger React to re-render. We do not use `setValue` directly because it may cause
+ // memory leaking.
+ const [_, setRenderCounter] = useState<number>(0);
+ const valueRef = useRef((() => {
+ let innerDefaultValue: T | undefined;
if (observable) {
const sub = unwrap(observable).subscribe((value) => {
initializedRef.current = true;
@@ -69,8 +72,9 @@ export function useObservable<T>(observable: Nullable<ObservableOrFn<T>>, defaul
sub.unsubscribe();
}
- return innerDefaultValue;
- });
+ return innerDefaultValue ?? defaultValue;
+ })());
+
const shouldResubscribe = (() => {
if (typeof depsRef.current !== 'undefined') {
@@ -86,19 +90,23 @@ export function useObservable<T>(observable: Nullable<ObservableOrFn<T>>, defaul
return observableRef.current !== observable;
})();
+ // Subscribe on first rendering and re-subscribe when deps change.
if ((!subscriptionRef.current || shouldResubscribe) && observable) {
observableRef.current = unwrap(observable);
subscriptionRef.current?.unsubscribe();
subscriptionRef.current = observableRef.current.subscribe((value) => {
- setValue(value);
+ valueRef.current = value;
+ setRenderCounter((prev) => prev + 1);
});
}
+ useEffect(() => () => {
+ subscriptionRef.current?.unsubscribe();
+ subscriptionRef.current = null;
+ }, []);
+
if (shouldHaveSyncValue && !initializedRef.current) {
throw new Error('[useObservable]: expect shouldHaveSyncValue but not getting a sync value!');
}
-
- useEffect(() => () => subscriptionRef.current?.unsubscribe(), []);
-
- return value;
+ return valueRef.current;
}
diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.ts
index 6809524baa..f7c63b811e 100644
--- a/packages/ui/src/services/editor/editor.service.ts
+++ b/packages/ui/src/services/editor/editor.service.ts
@@ -651,7 +651,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos
return;
}
- this._renderManagerService.removeItem(editorUnitId);
+ this._renderManagerService.removeRender(editorUnitId);
editor.documentDataModel.dispose();
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index c301b3e082..76bfc9f4f1 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -89,9 +89,6 @@ export class UniverUIPlugin extends Plugin {
override onStarting(_injector: Injector): void {
this._initDependencies(_injector);
- }
-
- override onReady(): void {
this._initUI();
}
diff --git a/packages/ui/src/views/App.tsx b/packages/ui/src/views/App.tsx
index 664ca0121a..e6464564f8 100644
--- a/packages/ui/src/views/App.tsx
+++ b/packages/ui/src/views/App.tsx
@@ -111,9 +111,7 @@ export function App(props: IUniverAppProps) {
<section className={styles.appContainerContent}>
<header>
- {header && (
- <ComponentContainer components={headerComponents} />
- )}
+ {header && <ComponentContainer components={headerComponents} />}
</header>
<section
diff --git a/packages/ui/src/views/components/ComponentContainer.tsx b/packages/ui/src/views/components/ComponentContainer.tsx
index 26767be367..348011f79c 100644
--- a/packages/ui/src/views/components/ComponentContainer.tsx
+++ b/packages/ui/src/views/components/ComponentContainer.tsx
@@ -19,7 +19,6 @@ import React from 'react';
export function ComponentContainer(props: { components?: Set<() => ComponentType> }) {
const { components } = props;
-
if (!components) return null;
return Array.from(components.values()).map((component, index) =>