diff --git a/packages/core/src/sheets/__tests__/worksheet.spec.ts b/packages/core/src/sheets/__tests__/worksheet.spec.ts index c26175296f2..8f34d73d373 100644 --- a/packages/core/src/sheets/__tests__/worksheet.spec.ts +++ b/packages/core/src/sheets/__tests__/worksheet.spec.ts @@ -33,7 +33,7 @@ describe('test worksheet', () => { function prepare(workbookData?: IWorkbookData) { const testBed = createCoreTestBed(workbookData); univer = testBed.univer; - worksheet = testBed.sheet.getActiveSheet(); + worksheet = testBed.sheet.getActiveSheet()!; } afterEach(() => { diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts index 97bd280bbe8..3824fd1fcbc 100644 --- a/packages/core/src/sheets/workbook.ts +++ b/packages/core/src/sheets/workbook.ts @@ -20,15 +20,9 @@ import { BehaviorSubject, Subject } from 'rxjs'; import { ILogService } from '../services/log/log.service'; import type { Nullable } from '../shared'; import { Tools } from '../shared'; -import { DEFAULT_RANGE_ARRAY } from '../types/const'; import { BooleanNumber } from '../types/enum'; import type { - IColumnStartEndData, - IGridRange, - IRangeArrayData, - IRangeStringData, IRangeType, - IRowStartEndData, IWorkbookData, IWorksheetData, } from '../types/interfaces'; @@ -211,26 +205,25 @@ export class Workbook extends UnitModel { + getActiveSheet(): Nullable { return this._activeSheet; } /** - * Get the active sheet. If there is no active sheet, the first sheet would + * If there is no active sheet, the first sheet would * be set active. + * @returns */ - getActiveSheet(): Worksheet { - const currentActive = this.getRawActiveSheet(); + ensureActiveSheet() { + const currentActive = this.getActiveSheet(); if (currentActive) { return currentActive; } - - /** - * If the first sheet is hidden, we should set the first unhidden sheet to be active. - */ + /** + * If the first sheet is hidden, we should set the first unhidden sheet to be active. + */ const sheetOrder = this._snapshot.sheetOrder; for (let i = 0, len = sheetOrder.length; i < len; i++) { const worksheet = this._worksheets.get(sheetOrder[i]); @@ -335,68 +328,6 @@ export class Workbook extends UnitModel s.getConfig().id); } - /** - * transform any range type to range data - * - * @remarks - * e.g., - * "A1:B1", "Sheet2!A1:B1" - * - * or - * - * { - * row:[0,1], - * column:[0,1] - * } - * - * or - * - * { - * startRow:0 , - * startColumn:0, - * endRow:1, - * endColumn:1, - * } - * - * to - * - * { - * startRow:0 , - * startColumn:0, - * endRow:1, - * endColumn:1, - * } - * - * IRangeType[] is to prevent type detection - * - * @param range support all range types - * - * @returns range data - */ - transformRangeType(range: IRangeType | IRangeType[]): IGridRange { - if (typeof range === 'string') { - const gridRange = this._getCellRange(range); - return gridRange; - } - if (typeof range !== 'string' && 'row' in range) { - const rangeArrayData = range as IRangeArrayData; - return { - sheetId: '', - range: { - startRow: rangeArrayData.row[0], - startColumn: rangeArrayData.column[0], - endRow: rangeArrayData.row[1], - endColumn: rangeArrayData.column[1], - }, - }; - // ref : https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-the-in-operator - } - if (typeof range !== 'string' && 'startRow' in range) { - return { sheetId: '', range }; - } - return DEFAULT_RANGE_ARRAY; - } - load(config: IWorkbookData) { // TODO: new Command this._snapshot = config; @@ -440,88 +371,6 @@ export class Workbook extends UnitModel -1) { - const val = txt.split('!'); - sheetTxt = val[0]; - rangeTxt = val[1]; - sheetTxt = sheetTxt.replace(/\\'/g, "'").replace(/''/g, "'"); - if (sheetTxt.substring(0, 1) === "'" && sheetTxt.substring(sheetTxt.length - 1, 1) === "'") { - sheetTxt = sheetTxt.substring(1, sheetTxt.length - 1); - } - } else { - rangeTxt = txt; - } - if (rangeTxt.indexOf(':') === -1) { - const row = Number.parseInt(rangeTxt.replace(/[^0-9]/g, ''), 10) - 1; - const col = Tools.ABCatNum(rangeTxt.replace(/[^A-Za-z]/g, '')); - - if (!Number.isNaN(row) && !Number.isNaN(col)) { - const item = { - sheetId: sheetTxt, - range: { - startRow: row, - endRow: row, - startColumn: col, - endColumn: col, - }, - }; - return item; - } - return DEFAULT_RANGE_ARRAY; - } - rangeTxt = rangeTxt.split(':'); - - const row: IRowStartEndData = [0, 0]; - const col: IColumnStartEndData = [0, 0]; - const maxRow = this.getSheetBySheetName(sheetTxt)?.getMaxRows() || this.getActiveSheet()?.getMaxRows(); - const maxCol = this.getSheetBySheetName(sheetTxt)?.getMaxColumns() || this.getActiveSheet()?.getMaxColumns(); - row[0] = Number.parseInt(rangeTxt[0].replace(/[^0-9]/g, ''), 10) - 1; - row[1] = Number.parseInt(rangeTxt[1].replace(/[^0-9]/g, ''), 10) - 1; - - if (Number.isNaN(row[0])) { - row[0] = 0; - } - - if (Number.isNaN(row[1])) { - row[1] = maxRow!; - } - - if (row[0] > row[1]) { - return DEFAULT_RANGE_ARRAY; - } - col[0] = Tools.ABCatNum(rangeTxt[0].replace(/[^A-Za-z]/g, '')); - col[1] = Tools.ABCatNum(rangeTxt[1].replace(/[^A-Za-z]/g, '')); - if (Number.isNaN(col[0])) { - col[0] = 0; - } - if (Number.isNaN(col[1])) { - col[1] = maxCol!; - } - if (col[0] > col[1]) { - return DEFAULT_RANGE_ARRAY; - } - - const item = { - sheetId: this.getSheetBySheetName(sheetTxt)?.getSheetId() || '', - range: { - startRow: row[0], - endRow: row[1], - startColumn: col[0], - endColumn: col[1], - }, - }; - return item; - } - // FIXME: now we always create worksheet from DEFAULT_WORKSHEET? /** @@ -554,5 +403,8 @@ export class Workbook extends UnitModel(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } const snapshot = resourceLoaderService.saveWorkbook(workbook); const gitHash = process.env.GIT_COMMIT_HASH; const gitBranch = process.env.GIT_REF_NAME; diff --git a/packages/debugger/src/commands/operations/sidebar.operation.ts b/packages/debugger/src/commands/operations/sidebar.operation.ts index 652fa52db31..1fde407d81c 100644 --- a/packages/debugger/src/commands/operations/sidebar.operation.ts +++ b/packages/debugger/src/commands/operations/sidebar.operation.ts @@ -35,7 +35,7 @@ export const SidebarOperation: ICommand = { switch (params.value) { case 'open': editorService.setOperationSheetUnitId(unit.getUnitId()); - editorService.setOperationSheetSubUnitId(unit.getActiveSheet().getSheetId()); + editorService.setOperationSheetSubUnitId(unit.getActiveSheet()?.getSheetId()); sidebarService.open({ header: { title: 'debugger.sidebar.title' }, children: { title: 'Sidebar Content', label: TEST_EDITOR_CONTAINER_COMPONENT }, diff --git a/packages/debugger/src/views/test-editor/TestTextEditor.tsx b/packages/debugger/src/views/test-editor/TestTextEditor.tsx index eeef91157fc..da9c97e4782 100644 --- a/packages/debugger/src/views/test-editor/TestTextEditor.tsx +++ b/packages/debugger/src/views/test-editor/TestTextEditor.tsx @@ -47,7 +47,7 @@ export const TestEditorContainer = () => { const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()?.getSheetId(); const [readonly, setReadonly] = useState(false); diff --git a/packages/drawing-ui/src/controllers/utils.ts b/packages/drawing-ui/src/controllers/utils.ts index bb303a9983f..a9581b57d9e 100644 --- a/packages/drawing-ui/src/controllers/utils.ts +++ b/packages/drawing-ui/src/controllers/utils.ts @@ -66,7 +66,7 @@ export function getCurrentUnitInfo(currentUniverService: IUniverInstanceService) let subUnitId: Nullable; if (current.type === UniverInstanceType.UNIVER_SHEET) { - subUnitId = (current as Workbook).getActiveSheet().getSheetId(); + subUnitId = (current as Workbook).getActiveSheet()?.getSheetId(); } else if (current.type === UniverInstanceType.UNIVER_DOC) { subUnitId = unitId; } else if (current.type === UniverInstanceType.UNIVER_SLIDE) { diff --git a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts index 16ee928c99a..b0c6808d6ee 100644 --- a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts +++ b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts @@ -267,7 +267,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies? const sheetData: ISheetData = {}; const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()!.getSheetId(); workbook.getSheets().forEach((sheet) => { const sheetConfig = sheet.getConfig(); sheetData[sheet.getSheetId()] = { diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts index c037bd31ac6..e0280fa28c2 100644 --- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts +++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts @@ -216,7 +216,7 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies const sheetData: ISheetData = {}; const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()!.getSheetId(); workbook.getSheets().forEach((sheet) => { const sheetConfig = sheet.getConfig(); sheetData[sheet.getSheetId()] = { diff --git a/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts index 9456b18aafa..e6e7783d7c4 100644 --- a/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts +++ b/packages/facade/src/apis/sheets/__tests__/f-sheet-hooks.spec.ts @@ -148,7 +148,7 @@ describe('Test FSheetHooks', () => { }); // Trigger the Observable to emit a new value - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); hoverCurrentPosition$.next({ location: { workbook, worksheet, unitId, subUnitId, row: 0, col: 0 }, position: { startX: 0, endX: 1, startY: 0, endY: 1 } }); @@ -160,7 +160,7 @@ describe('Test FSheetHooks', () => { }); // Trigger the Observable to emit a new value - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); hoverCurrentCell$.next({ location: { workbook, worksheet, unitId, subUnitId, row: 0, col: 0 }, position: { startX: 0, endX: 1, startY: 0, endY: 1 } }); @@ -172,7 +172,7 @@ describe('Test FSheetHooks', () => { }); // Trigger the Observable to emit a new value - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); dragCurrentCell$.next({ location: { workbook, worksheet, unitId, subUnitId, row: 0, col: 0 }, position: { startX: 0, endX: 1, startY: 0, endY: 1 }, dataTransfer: new MockDataTransfer() }); @@ -184,7 +184,7 @@ describe('Test FSheetHooks', () => { }); // Trigger the Observable to emit a new value - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); dragEndCell$.next({ location: { workbook, worksheet, unitId, subUnitId, row: 0, col: 0 }, position: { startX: 0, endX: 1, startY: 0, endY: 1 }, dataTransfer: new MockDataTransfer() }); diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts index f502e78a818..06d2f25ed53 100644 --- a/packages/facade/src/apis/sheets/f-workbook.ts +++ b/packages/facade/src/apis/sheets/f-workbook.ts @@ -111,8 +111,12 @@ export class FWorkbook { unitId: this.id, subUnitId: this._workbook.getSheets()[this._workbook.getSheets().length - 1].getSheetId(), }); + const worksheet = this._workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } - return this._injector.createInstance(FWorksheet, this._workbook, this._workbook.getActiveSheet()); + return this._injector.createInstance(FWorksheet, this._workbook, worksheet); } /** @@ -172,8 +176,12 @@ export class FWorkbook { unitId, subUnitId, }); + const worksheet = this._workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } - return this._injector.createInstance(FWorksheet, this._workbook, this._workbook.getActiveSheet()); + return this._injector.createInstance(FWorksheet, this._workbook, worksheet); } /** diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx index 0828eb7aaab..9076e31bd39 100644 --- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx +++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx @@ -34,7 +34,7 @@ const TextInput = (props: { id: string; type: CFValueType | 'none';value: number const { type, className, onChange, id, value } = props; const univerInstanceService = useDependency(IUniverInstanceService); const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); const formulaInitValue = useMemo(() => { return String(value).startsWith('=') ? String(value) : '='; }, [value]); diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx index d738c2789f6..15632d70608 100644 --- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx +++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx @@ -34,7 +34,7 @@ const InputText = (props: { disabled?: boolean; id: string; className: string; t const { onChange, className, value, type, id, disabled = false } = props; const univerInstanceService = useDependency(IUniverInstanceService); const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); const _value = useRef(value); const config = useMemo(() => { if ([CFValueType.percentile, CFValueType.percent].includes(type)) { diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx index 377968d1467..7535b04f6d4 100644 --- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx +++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx @@ -74,7 +74,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
{ const TextInput = (props: { id: number; type: CFValueType; value: number | string;onChange: (v: number | string) => void; error?: string }) => { const univerInstanceService = useDependency(IUniverInstanceService); const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); const className = useMemo(() => { if (props.error) { return styles.errorInput; diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx index 17d39e9927c..adaad4748d0 100644 --- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx +++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx @@ -48,7 +48,7 @@ interface IRuleEditProps { } const getUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); -const getSubUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); +const getSubUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); export const RuleEdit = (props: IRuleEditProps) => { const localeService = useDependency(LocaleService); @@ -185,6 +185,9 @@ export const RuleEdit = (props: IRuleEditProps) => { const beforeSubmitResult = interceptorManager.fetchThroughInterceptors(interceptorManager.getInterceptPoints().beforeSubmit)(true, null); const getRanges = () => { const worksheet = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } const ranges = rangeResult.current.map((range) => setEndForRange(range, worksheet.getRowCount(), worksheet.getColumnCount())); const result = ranges.filter((range) => !(Number.isNaN(range.startRow) || Number.isNaN(range.startColumn))); return result; @@ -197,6 +200,9 @@ export const RuleEdit = (props: IRuleEditProps) => { // When you switch the child table, you need to fetch it again here, instead of using the const unitId = getUnitId(univerInstanceService); const subUnitId = getSubUnitId(univerInstanceService); + if (!unitId || !subUnitId) { + throw new Error('No active sheet found'); + } let rule = {} as IConditionFormattingRule; if (props.rule && props.rule.cfId) { rule = { ...props.rule, ranges, rule: result }; diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx index 3dd179b982e..ff062386cfc 100644 --- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx +++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx @@ -118,6 +118,10 @@ export const RuleList = (props: IRuleListProps) => { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + const subUnitId = worksheet.getSheetId(); const [currentRuleRanges, currentRuleRangesSet] = useState([]); @@ -162,7 +166,7 @@ export const RuleList = (props: IRuleListProps) => { const { startRow, startColumn, endRow, endColumn } = range; for (let row = startRow; row <= endRow; row++) { for (let col = startColumn; col <= endColumn; col++) { - const permission = (worksheet.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0]; + const permission = (worksheet?.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0]; if (permission?.[UnitAction.Edit] === false || permission?.[UnitAction.View] === false) { return true; } @@ -269,7 +273,10 @@ export const RuleList = (props: IRuleListProps) => { const handleDelete = (rule: IConditionFormattingRule) => { const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); + if (!unitId || !subUnitId) { + throw new Error('No active sheet found'); + } commandService.executeCommand(DeleteCfCommand.id, { unitId, subUnitId, cfId: rule.cfId } as IDeleteCfCommandParams); }; @@ -280,7 +287,11 @@ export const RuleList = (props: IRuleListProps) => { const handleDragStop = (_layout: unknown, from: { y: number }, to: { y: number }) => { draggingIdSet(-1); const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); + if (!unitId || !subUnitId) { + throw new Error('No active sheet found'); + } + const getSaveIndex = (index: number) => { const length = ruleList.length; return Math.min(length - 1, Math.max(0, index)); diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts index eebebbb4f8e..40598942c36 100644 --- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts +++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts @@ -52,7 +52,11 @@ export class ConditionalFormattingAutoFillController extends Disposable { mapFunc: (row: number, col: number) => ({ row: number; col: number }) ) => { const unitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); + if (!unitId || !subUnitId) { + return; + } + const sourceRange = { startRow: sourceStartCell.row, startColumn: sourceStartCell.col, @@ -143,7 +147,7 @@ export class ConditionalFormattingAutoFillController extends Disposable { const generalApplyFunc = (sourceRange: IDiscreteRange, targetRange: IDiscreteRange) => { const unitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)?.getUnitId(); - const subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet().getSheetId(); + const subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet()?.getSheetId(); const matrixMap: Map> = new Map(); const redos: IMutationInfo[] = []; diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts index d614949272c..c0bbb3fb0e2 100644 --- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts +++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts @@ -49,6 +49,10 @@ export class ConditionalFormattingClearController extends Disposable { } const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return defaultV; + } + const allRules = this._conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), worksheet.getSheetId()); if (!allRules || !allRules.length) { return defaultV; diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts index b0cb07d7b34..b99239ad146 100644 --- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts +++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts @@ -115,6 +115,7 @@ export class ConditionalFormattingCopyPasteController extends Disposable { }); } + // eslint-disable-next-line max-lines-per-function private _generateConditionalFormattingMutations( pastedRange: IDiscreteRange, copyInfo: { @@ -126,6 +127,8 @@ export class ConditionalFormattingCopyPasteController extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const sheet = workbook.getActiveSheet(); const unitId = workbook.getUnitId(); + if (!sheet) return { redos: [], undos: [] }; + const subUnitId = sheet.getSheetId(); if (copyInfo.copyType === COPY_TYPE.CUT) { // This do not need to deal with clipping. diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts index 64bdac2db48..45035eaea4a 100644 --- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts +++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts @@ -72,7 +72,7 @@ export class SheetsCfRefRangeController extends Disposable { const { unitId, subUnitId, rule } = option; const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); - if (option.unitId !== workbook.getUnitId() || option.subUnitId !== worksheet.getSheetId()) { + if (option.unitId !== workbook.getUnitId() || option.subUnitId !== worksheet?.getSheetId()) { return; } switch (option.type) { 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 68ec8857fdc..46aea63dfcb 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 @@ -53,6 +53,8 @@ export class SheetsCfRenderController extends Disposable { if (!workbook) return false; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0; })).subscribe(markDirtySkeleton)); @@ -62,6 +64,8 @@ export class SheetsCfRenderController extends Disposable { if (!workbook) return false; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + return v.filter((item) => ['sort', 'delete'].includes(item.type) && item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0; })).subscribe(markDirtySkeleton)); @@ -72,6 +76,8 @@ export class SheetsCfRenderController extends Disposable { if (!workbook) return false; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + 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 c04c39bc776..9f086d5ccf1 100644 --- a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts +++ b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts @@ -33,6 +33,7 @@ const commandList = [SetWorksheetActiveOperation.id, AddConditionalRuleMutation. type ICellPermission = Record & { ruleId?: string; ranges?: IRange[] }; +// eslint-disable-next-line max-lines-per-function export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMenuSelectorItem => { const commonSelections = [ { @@ -97,7 +98,10 @@ export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMe const ranges = selectionManagerService.getSelections()?.map((selection) => selection.range) || []; const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET); if (!workbook) return; - const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), workbook.getActiveSheet().getSheetId()) || []; + const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + + const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), worksheet.getSheetId()) || []; const ruleList = allRule.filter((rule) => rule.ranges.some((ruleRange) => ranges.some((range) => Rectangle.intersects(range, ruleRange)))); subscriber.next(!!ruleList.length); })); @@ -118,7 +122,9 @@ export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMe const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET); if (!workbook) return; const worksheet = workbook.getActiveSheet(); - const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), workbook.getActiveSheet().getSheetId()) || []; + if (!worksheet) return; + + const allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), worksheet.getSheetId()) || []; const hasNotPermission = allRule.some((rule) => { const ranges = rule.ranges; return ranges.some((range) => { diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts index 4c3adcc08a7..7ac68828553 100644 --- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts +++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts @@ -169,6 +169,11 @@ export class ConditionalFormattingService extends Disposable { const params = commandInfo.params as IRemoveSheetCommandParams; const unitId = params.unitId || getUnitId(this._univerInstanceService); const subUnitId = params.subUnitId || getSubUnitId(this._univerInstanceService); + + if (!subUnitId) { + return { redos: [], undos: [] }; + } + const ruleList = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId); if (!ruleList) { return { redos: [], undos: [] }; @@ -402,4 +407,4 @@ export class ConditionalFormattingService extends Disposable { } const getUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); -const getSubUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); +const getSubUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); diff --git a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts b/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts index 2672b1376ea..9abead2456f 100644 --- a/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts +++ b/packages/sheets-data-validation/src/controllers/dv-alert.controller.ts @@ -44,6 +44,8 @@ export class DataValidationAlertController extends Disposable { if (cellPos) { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col); if (cellData?.dataValidation?.validStatus === DataValidationStatus.INVALID) { 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 4886c472569..a58b34b0f36 100644 --- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts +++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts @@ -150,6 +150,8 @@ export class SheetsDataValidationRenderController extends RxDisposable { } const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const activeDropdown = this._dropdownManagerService.activeDropdown; const currLoc = activeDropdown?.location; if ( @@ -184,7 +186,9 @@ export class SheetsDataValidationRenderController extends RxDisposable { if (!workbook) return; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) return; + const skeleton = this._renderManagerService.getRenderById(unitId) ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId) ?.skeleton; diff --git a/packages/sheets-data-validation/src/controllers/dv.controller.ts b/packages/sheets-data-validation/src/controllers/dv.controller.ts index 18923080a72..c0165c4a862 100644 --- a/packages/sheets-data-validation/src/controllers/dv.controller.ts +++ b/packages/sheets-data-validation/src/controllers/dv.controller.ts @@ -83,7 +83,12 @@ export class DataValidationController extends RxDisposable { if (!workbook) { return; } - this._sheetDataValidationService.switchCurrent(workbook.getUnitId(), workbook.getActiveSheet().getSheetId()); + const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return; + } + + this._sheetDataValidationService.switchCurrent(workbook.getUnitId(), worksheet.getSheetId()); disposableCollection.add(toDisposable( workbook.activeSheet$.subscribe((worksheet) => { if (worksheet) { @@ -105,6 +110,10 @@ export class DataValidationController extends RxDisposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + const subUnitId = worksheet.getSheetId(); const selections = this._selectionManagerService.getSelectionRanges(); diff --git a/packages/sheets-data-validation/src/validators/list-validator.ts b/packages/sheets-data-validation/src/validators/list-validator.ts index ddb9a0b7ede..331fe613a06 100644 --- a/packages/sheets-data-validation/src/validators/list-validator.ts +++ b/packages/sheets-data-validation/src/validators/list-validator.ts @@ -160,6 +160,8 @@ export class ListValidator extends BaseDataValidator { if (!workbook) return []; const worksheet = (currentSubUnitId ? workbook.getSheetBySheetId(currentSubUnitId) : undefined) ?? workbook.getActiveSheet(); + if (!worksheet) return []; + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const results = this.formulaService.getRuleFormulaResultSync(unitId, subUnitId, rule.uid); @@ -170,10 +172,11 @@ export class ListValidator extends BaseDataValidator { const { formula1 = '' } = rule; const univerInstanceService = this.injector.get(IUniverInstanceService); const workbook = (currentUnitId ? univerInstanceService.getUniverSheetInstance(currentUnitId) : undefined) ?? univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET); - if (!workbook) { - return []; - } + if (!workbook) return []; + const worksheet = (currentSubUnitId ? workbook.getSheetBySheetId(currentSubUnitId) : undefined) ?? workbook.getActiveSheet(); + if (!worksheet) return []; + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const results = await this.formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid); diff --git a/packages/sheets-data-validation/src/validators/util.ts b/packages/sheets-data-validation/src/validators/util.ts index d9bc5a4f894..081629c4924 100644 --- a/packages/sheets-data-validation/src/validators/util.ts +++ b/packages/sheets-data-validation/src/validators/util.ts @@ -24,7 +24,7 @@ export function getSheetRangeValueSet(grid: IUnitRangeName, univerInstanceServic const workbook = univerInstanceService.getUniverSheetInstance(unitId) ?? univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getSheetBySheetName(grid.sheetName) ?? workbook.getSheetBySheetId(currSubUnitId) ?? workbook.getActiveSheet(); Range.foreach(grid.range, (row, col) => { - const data = worksheet.getCellRaw(row, col); + const data = worksheet?.getCellRaw(row, col); if (!data) { return; } diff --git a/packages/sheets-data-validation/src/views/list/index.tsx b/packages/sheets-data-validation/src/views/list/index.tsx index e1a4d799f79..1ef5bfaf062 100644 --- a/packages/sheets-data-validation/src/views/list/index.tsx +++ b/packages/sheets-data-validation/src/views/list/index.tsx @@ -104,7 +104,7 @@ function DataValidationListWithWorkbook(props: { workbook: Workbook }) { const { startRow, startColumn, endRow, endColumn } = range; for (let row = startRow; row <= endRow; row++) { for (let col = startColumn; col <= endColumn; col++) { - const permission = (worksheet.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0]; + const permission = (worksheet?.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0]; if (permission?.[UnitAction.Edit] === false || permission?.[UnitAction.View] === false) { return true; } diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts index 416d3c0034f..0004def04b5 100644 --- a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts +++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts @@ -83,7 +83,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende if (!skeletonParams) return of(null); const { unit: workbook, unitId } = this._context; - const worksheetId = workbook.getActiveSheet().getSheetId(); + const worksheetId = workbook.getActiveSheet()?.getSheetId() || ''; const filterModel = this._sheetsFilterService.getFilterModel(unitId, worksheetId) ?? undefined; const getParams = (): ISheetsFilterRenderParams => ({ unitId, diff --git a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts b/packages/sheets-filter/src/controllers/sheets-filter.controller.ts index 0027d854f8b..6adcf064b75 100644 --- a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts +++ b/packages/sheets-filter/src/controllers/sheets-filter.controller.ts @@ -53,6 +53,7 @@ export class SheetsFilterController extends Disposable { ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command))); } + // eslint-disable-next-line max-lines-per-function private _initInterceptors(): void { this.disposeWithMe(this._sheetInterceptorService.interceptCommand({ getMutations: (command) => this._getUpdateFilter(command), diff --git a/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts b/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts index 4a5a97fcc6e..1a9a255c5fc 100644 --- a/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts +++ b/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts @@ -37,6 +37,7 @@ describe('Test "Filter Interceptor"', () => { get = testBed.get; sheetsFilterService = testBed.sheetsFilterService; commandService = testBed.commandService; + univer.__getInjector(); }); afterEach(() => { diff --git a/packages/sheets-filter/src/services/sheet-filter.service.ts b/packages/sheets-filter/src/services/sheet-filter.service.ts index 54ebe9861e4..2a64ae0cf6d 100644 --- a/packages/sheets-filter/src/services/sheet-filter.service.ts +++ b/packages/sheets-filter/src/services/sheet-filter.service.ts @@ -135,8 +135,8 @@ export class SheetsFilterService extends Disposable { return; } - // Use getRawActiveSheet to avoid automatically activating the next sheet when deleting the sheet, causing the sheet switching in ActiveWorksheetController to be invalid. - const activeSheet = workbook.getRawActiveSheet(); + // Use getActiveSheet to avoid automatically activating the next sheet when deleting the sheet, causing the sheet switching in ActiveWorksheetController to be invalid. + const activeSheet = workbook.getActiveSheet(); if (!activeSheet) { this._activeFilterModel$.next(null); return; diff --git a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts index ef1bf1f1e5e..477bbe04543 100644 --- a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts +++ b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts @@ -210,7 +210,7 @@ describe('test "hitCell" method', () => { beforeEach(() => { const testBed = createTestBed(); univer = testBed.univer; - worksheet = testBed.sheet.getActiveSheet(); + worksheet = testBed.sheet.getActiveSheet()!; }); afterEach(() => { diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts index dcd862e5762..6397b64f9da 100644 --- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts +++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts @@ -217,6 +217,10 @@ export class SheetFindModel extends FindModel { ) .subscribe(() => { const activeSheet = this._workbook.getActiveSheet(); + if (!activeSheet) { + return; + } + const activeSheetId = activeSheet.getSheetId(); if (!this._matchesByWorksheet.has(activeSheetId)) { return; @@ -280,6 +284,7 @@ export class SheetFindModel extends FindModel { const checkShouldFindInSelections = (): boolean => { const currentWorksheet = this._workbook.getActiveSheet(); + if (!currentWorksheet) return false; const currentSelections = this._selectionManagerService.getSelections(); const shouldFindInSelections = currentSelections?.some((selection) => !isSelectionSingleCell(selection, currentWorksheet)) ?? false; return shouldFindInSelections; @@ -291,6 +296,8 @@ export class SheetFindModel extends FindModel { const performFindInWorksheet = (): IFindComplete => { const currentWorksheet = this._workbook.getActiveSheet(); + if (!currentWorksheet) return { results: [] }; + const lastMatch = this.currentMatch; // temporarily store the last match to restore the position after the model changes findBySelections = checkShouldFindInSelections(); @@ -476,6 +483,10 @@ export class SheetFindModel extends FindModel { const searchBackgroundColor = this._themeService.getCurrentTheme().gold400; const color = new ColorKit(searchBackgroundColor).toRgb(); const worksheet = this._workbook.getActiveSheet(); + if (!worksheet) { + return; + } + const activeSheetId = worksheet.getSheetId(); const highlightShapes = matches.filter((match) => match.range.subUnitId === activeSheetId).map((find, index) => { const { startColumn, startRow, endColumn, endRow } = find.range.range; @@ -533,7 +544,7 @@ export class SheetFindModel extends FindModel { private _focusMatch(match: ISheetCellMatch): void { const subUnitId = match.range.subUnitId; - if (subUnitId !== this._workbook.getActiveSheet().getSheetId()) { + if (subUnitId !== this._workbook.getActiveSheet()?.getSheetId()) { this._commandService.syncExecuteCommand(SetWorksheetActivateCommand.id, { unitId: this._workbook.getUnitId(), subUnitId } as ISetWorksheetActivateCommandParams, { fromFindReplace: true } @@ -585,7 +596,7 @@ export class SheetFindModel extends FindModel { } if (!noFocus) this._focusMatch(match); - if (this._workbook.getActiveSheet().getSheetId() === match.range.subUnitId) { + if (this._workbook.getActiveSheet()?.getSheetId() === match.range.subUnitId) { this._updateCurrentHighlightShape(this._activeHighlightIndex); } @@ -618,7 +629,7 @@ export class SheetFindModel extends FindModel { } if (!noFocus) this._focusMatch(match); - if (this._workbook.getActiveSheet().getSheetId() === match.range.subUnitId) { + if (this._workbook.getActiveSheet()?.getSheetId() === match.range.subUnitId) { this._updateCurrentHighlightShape(this._activeHighlightIndex); } @@ -660,7 +671,11 @@ export class SheetFindModel extends FindModel { return this._findPreviousMatchByRange(this._matches, selections[0].range); } - const currentSheetId = this._workbook.getActiveSheet().getSheetId(); + const currentSheetId = this._workbook.getActiveSheet()?.getSheetId(); + if (!currentSheetId) { + return null; + } + const worksheetThatHasMatch = this._findPreviousWorksheetThatHasAMatch(currentSheetId, loop); if (!worksheetThatHasMatch) { return null; @@ -699,7 +714,11 @@ export class SheetFindModel extends FindModel { return this._findNextMatchByRange(this._matches, selections[0].range, stayIfOnMatch); } - const currentSheetId = this._workbook.getActiveSheet().getSheetId(); + const currentSheetId = this._workbook.getActiveSheet()?.getSheetId(); + if (!currentSheetId) { + return null; + } + const worksheetThatHasMatch = this._findNextWorksheetThatHasAMatch(currentSheetId, loop); if (!worksheetThatHasMatch) { return null; diff --git a/packages/sheets-formula/src/controllers/formula-alert.controller.ts b/packages/sheets-formula/src/controllers/formula-alert.controller.ts index 18387436c37..994fab2901b 100644 --- a/packages/sheets-formula/src/controllers/formula-alert.controller.ts +++ b/packages/sheets-formula/src/controllers/formula-alert.controller.ts @@ -59,6 +59,8 @@ export class FormulaAlertController extends Disposable { if (cellPos) { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col); if (cellData) { diff --git a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts index 79883262109..d9cbb0ed3e4 100644 --- a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts +++ b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts @@ -93,7 +93,13 @@ export class FormulaClipboardController extends Disposable { const matrix = data; const workbook = this._currentUniverSheet.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!unitId || !subUnitId) { + return { + undos: [], + redos: [], + }; + } return this._injector.invoke((accessor) => getSetCellFormulaMutations( unitId, diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts index 5f77e080b3f..68a6338c797 100644 --- a/packages/sheets-formula/src/controllers/prompt.controller.ts +++ b/packages/sheets-formula/src/controllers/prompt.controller.ts @@ -1142,7 +1142,7 @@ export class PromptController extends Disposable { return { unitId: workbook.getUnitId(), - sheetId: worksheet.getSheetId(), + sheetId: worksheet?.getSheetId() || '', skeleton, }; } diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts index e978084cdcb..2504cbbbc6f 100644 --- a/packages/sheets-formula/src/controllers/update-formula.controller.ts +++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts @@ -467,6 +467,8 @@ export class UpdateFormulaController extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return null; + const sheetId = worksheet.getSheetId(); const from = { @@ -505,6 +507,8 @@ export class UpdateFormulaController extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return null; + const sheetId = worksheet.getSheetId(); const from = { @@ -1438,7 +1442,7 @@ export class UpdateFormulaController extends Disposable { private _getCurrentSheetInfo() { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()?.getSheetId() || ''; return { unitId, diff --git a/packages/sheets-formula/src/services/formula-ref-range.service.ts b/packages/sheets-formula/src/services/formula-ref-range.service.ts index 295b4dd264a..0e6036ae76b 100644 --- a/packages/sheets-formula/src/services/formula-ref-range.service.ts +++ b/packages/sheets-formula/src/services/formula-ref-range.service.ts @@ -46,7 +46,7 @@ export class FormulaRefRangeService extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); const unitId = workbook.getUnitId(); - const subUnitId = worksheet.getSheetId(); + const subUnitId = worksheet?.getSheetId(); const transformSequenceNodes = sequenceNodes?.map((node) => { if (typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE) { diff --git a/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts index 99d46fcc944..e17c764d3f1 100644 --- a/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts +++ b/packages/sheets-hyper-link-ui/src/controllers/remove-sheet.controller.ts @@ -43,7 +43,10 @@ export class SheetsHyperLinkRemoveSheetController extends Disposable { return { redos: [], undos: [] }; } const unitId = workbook.getUnitId(); - const subUnitId = params.subUnitId || workbook.getActiveSheet().getSheetId(); + const subUnitId = params.subUnitId || workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) { + return { redos: [], undos: [] }; + } const links = this._hyperLinkModel.getSubUnit(unitId, subUnitId); const redos = links.map((link) => ({ diff --git a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts index 7f10e898f1f..eeedc455ee2 100644 --- a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts +++ b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts @@ -38,7 +38,12 @@ export class SheetsHyperLinkRenderController extends Disposable implements IRend const markSkeletonDirty = () => { const workbook = this._context.unit; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) { + // TODO@zhangw: handle this case + console.warn('No active sheet found'); + return; + } const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ sheetId: subUnitId }); const currentRender = this._renderManagerService.getRenderById(unitId); diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts index 6cfddc320e9..84c15fd1adb 100644 --- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts +++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts @@ -239,6 +239,9 @@ export class SheetsHyperLinkResolverService { return false; } const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } if (worksheet.getSheetId() === subUnitId) { return worksheet; diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx index b224bc60928..9d40084d5ac 100644 --- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx +++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx @@ -177,7 +177,7 @@ export const CellLinkEdit = () => { return; } if (!range.sheetName) { - range.sheetName = workbook.getActiveSheet().getName(); + range.sheetName = workbook.getActiveSheet()?.getName() || ''; } const newPayload = serializeRangeToRefString(range); setPayload(newPayload); diff --git a/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts index f8aadc5aa83..70ecae49df4 100644 --- a/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts +++ b/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts @@ -53,7 +53,7 @@ describe('test cell-content', () => { }, }; const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; testBed.get(SheetsNumfmtCellContentController); const value = worksheet.getCell(0, 0); expect(value).toEqual({ v: 0, t: 2 }); diff --git a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts index 06adf8d50a6..9b92adadef2 100644 --- a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts +++ b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts @@ -54,7 +54,7 @@ describe('test editor', () => { testBed.get(NumfmtEditorController); testBed.get(SheetsNumfmtCellContentController); workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - worksheet = workbook.getActiveSheet(); + worksheet = workbook.getActiveSheet()!; }); it('before edit with currency', () => { diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts index 02ca42a9f84..617c1fad6ee 100644 --- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts +++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts @@ -107,6 +107,9 @@ export class NumfmtController extends Disposable implements INumfmtController { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const sheet = workbook.getActiveSheet(); + if (!sheet) { + return false; + } const cellValue = sheet.getCellRaw(range.startRow, range.startColumn); const numfmtValue = numfmtService.getValue( diff --git a/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts index 7ced6736347..b1870d24c34 100644 --- a/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts +++ b/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts @@ -203,7 +203,13 @@ export class NumfmtEditorController extends Disposable { case SetRangeValuesCommand.id: { const workbook = self._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) { + return { + redos: [], + undos: [], + }; + } const list = self._collectEffectMutation.getEffects(); if (!list.length) { return { diff --git a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts index 89111a8f023..f0d461176a3 100644 --- a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts +++ b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts @@ -70,7 +70,13 @@ export class SheetsThreadCommentRenderController extends Disposable { if (!workbook) return; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) { + // TODO@zhangw: handle this case + console.warn('No active sheet found'); + return; + } + const currentRender = this._renderManagerService.getRenderById(unitId); const skeleton = currentRender?.with(SheetSkeletonManagerService).getOrCreateSkeleton({ sheetId: subUnitId }); diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts index f0c61363312..16f5c797508 100644 --- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts +++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts @@ -44,7 +44,10 @@ export class ThreadCommentRemoveSheetsController extends Disposable { return { redos: [], undos: [] }; } const unitId = workbook.getUnitId(); - const subUnitId = params.subUnitId || workbook.getActiveSheet().getSheetId(); + const subUnitId = params.subUnitId || workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) { + return { redos: [], undos: [] }; + } const { commentMap } = this._threadCommentModel.ensureMap(unitId, subUnitId); const ids = Array.from(Object.keys(commentMap)); diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts index b57813c658c..cf2e7557abb 100644 --- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts +++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts @@ -148,7 +148,7 @@ export class SheetsThreadCommentController extends Disposable { if (currentUnitId !== unitId) { return; } - const currentSheetId = currentUnit.getActiveSheet().getSheetId(); + const currentSheetId = currentUnit.getActiveSheet()?.getSheetId(); if (currentSheetId !== subUnitId) { await this._commandService.executeCommand(SetWorksheetActiveOperation.id, { unitId, diff --git a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx index 6bb0b5bcfde..7fd0bc89227 100644 --- a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx +++ b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx @@ -38,7 +38,7 @@ export const SheetsThreadCommentPanel = () => { const unitId = workbook.getUnitId(); const commandService = useDependency(ICommandService); const subUnitId$ = useMemo(() => workbook.activeSheet$.pipe(map((i) => i?.getSheetId())), [workbook.activeSheet$]); - const subUnitId = useObservable(subUnitId$, workbook.getActiveSheet().getSheetId()); + const subUnitId = useObservable(subUnitId$, workbook.getActiveSheet()?.getSheetId()); const activeShapeId = useRef(); const panelService = useDependency(ThreadCommentPanelService); const activeCommentId = useObservable(panelService.activeCommentId$); diff --git a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts index 690ecbe32a8..575caf337d0 100644 --- a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts +++ b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts @@ -352,6 +352,7 @@ describe('Test add worksheet merge commands', () => { const univerInstanceService = get(IUniverInstanceService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) throw new Error('No active sheet found'); const mergeData = worksheet.getConfig().mergeData; expect(mergeData.length).toBe(0); expect(await commandService.executeCommand(AddWorksheetMergeAllCommand.id)).toBeTruthy(); @@ -447,6 +448,7 @@ describe('Test add worksheet merge commands', () => { const univerInstanceService = get(IUniverInstanceService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) throw new Error('No active sheet found'); const mergeData = worksheet.getConfig().mergeData; expect(mergeData.length).toBe(0); expect(await commandService.executeCommand(AddWorksheetMergeAllCommand.id)).toBeTruthy(); diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts index 5d5fcaf4f8e..604766fa1a3 100644 --- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts +++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts @@ -575,7 +575,7 @@ describe('Test auto fill rules in controller', () => { endColumn: 7, } ); - expect(workbook.getActiveSheet().getMergeData().length).toBe(2); + expect(workbook.getActiveSheet()?.getMergeData().length).toBe(2); expect(selectionManagerService.getLast()?.primary).toEqual(expect.objectContaining({ startRow: 0, startColumn: 5, diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts index c53bc49e7eb..cda3d17c504 100644 --- a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts +++ b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts @@ -88,7 +88,7 @@ describe('Test commands used for change selections', () => { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); - return worksheet.getConfig().freeze; + return worksheet?.getConfig().freeze; }; function disposeTestBed() { @@ -155,22 +155,22 @@ describe('Test commands used for change selections', () => { it('xSplit or ySplit must bigger than 0 if row or column was set', async () => { select(2, 2, 2, 2, 2, 2, false, false); scrollTo(2, 2); - let config: IFreeze; + let config: IFreeze | undefined; await commandService.executeCommand(SetColumnFrozenCommand.id); config = getFreeze(); expect(config?.startRow === -1 && config.startColumn === 2).toBeTruthy(); - expect(config.xSplit).toBe(1); + expect(config?.xSplit).toBe(1); await commandService.executeCommand(SetRowFrozenCommand.id); config = getFreeze(); expect(config?.startRow === 2 && config.startColumn === -1).toBeTruthy(); - expect(config.ySplit).toBe(1); + expect(config?.ySplit).toBe(1); await commandService.executeCommand(SetSelectionFrozenCommand.id); config = getFreeze(); expect(config?.startRow === 2 && config.startColumn === 2).toBeTruthy(); - expect(config.ySplit).toBe(1); - expect(config.xSplit).toBe(1); + expect(config?.ySplit).toBe(1); + expect(config?.xSplit).toBe(1); }); it('Should cancel all freeze', async () => { diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts index e2160398061..2d8e0659208 100644 --- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts +++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts @@ -115,14 +115,14 @@ describe('Test commands used for change selections', () => { function getRowCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowCount(); } function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } diff --git a/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts b/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts index 74918555daa..d55d1384f08 100644 --- a/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts +++ b/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts @@ -152,6 +152,11 @@ export const DeleteWorksheetProtectionFormSheetBarCommand: ICommand = { const workbook = univerInstanceService.getCurrentUnitForType(UniverType.UNIVER_SHEET)!; const worksheet = workbook?.getActiveSheet(); const unitId = workbook.getUnitId(); + + if (!worksheet) { + return false; + } + const subUnitId = worksheet.getSheetId(); const rule = worksheetProtectionRuleModel.getRule(unitId, subUnitId); diff --git a/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts b/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts index 0356ac0d3b1..b355740872e 100644 --- a/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts +++ b/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts @@ -97,7 +97,7 @@ export class ActiveWorksheetController extends Disposable { return; } - const activeSheet = workbook.getActiveSheet().getSheetId(); + const activeSheet = workbook.getActiveSheet()?.getSheetId(); if (activeSheet !== subUnitId) { return; } @@ -140,7 +140,7 @@ export class ActiveWorksheetController extends Disposable { } // The deleted sheet is not the currently active sheet, we don't have to do things. - const activeSheet = workbook.getRawActiveSheet(); + const activeSheet = workbook.getActiveSheet(); if (activeSheet) { return; } diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts index 3a0d056a08a..e76bfc6ab71 100644 --- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts +++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts @@ -336,7 +336,9 @@ export class AutoFillController extends Disposable { if (!workbook) return; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) return; + this._autoFillService.direction = direction; const accessor = { get: this._injector.get.bind(this._injector), @@ -540,10 +542,15 @@ export class AutoFillController extends Disposable { // endRow: copyEndRow, // endColumn: copyEndColumn, // } = source; - const currentCellDatas = this._univerInstanceService + const worksheet = this._univerInstanceService .getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)! - .getActiveSheet() - .getCellMatrix(); + .getActiveSheet(); + + if (!worksheet) { + throw new Error('No active sheet found'); + } + + const currentCellDatas = worksheet.getCellMatrix(); const rules = this._autoFillService.getRules(); const copyData: ICopyDataPiece[] = []; const isVertical = direction === Direction.DOWN || direction === Direction.UP; @@ -611,7 +618,13 @@ export class AutoFillController extends Disposable { } private _getMergeApplyData(source: IRange, target: IRange, direction: Direction, csLen: number) { - const mergeData = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getMergeData(); + const worksheet = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + + if (!worksheet) { + throw new Error('No active sheet found'); + } + + const mergeData = worksheet.getMergeData(); const applyMergeRanges = []; for (let i = source.startRow; i <= source.endRow; i++) { for (let j = source.startColumn; j <= source.endColumn; j++) { @@ -683,10 +696,15 @@ export class AutoFillController extends Disposable { private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) { const { source, target } = location; // cache original data of apply range - const currentCellDatas = this._univerInstanceService + const worksheet = this._univerInstanceService .getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)! - .getActiveSheet() - .getCellMatrix(); + .getActiveSheet(); + + if (!worksheet) { + throw new Error('No active sheet found'); + } + + const currentCellDatas = worksheet.getCellMatrix(); // cache the original data in currentCellDatas in apply range for later use / refill const applyData: Nullable[][] = []; target.rows.forEach((i) => { diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.ts index 9e0b9d3aff9..ae9b9887819 100644 --- a/packages/sheets-ui/src/controllers/auto-height.controller.ts +++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts @@ -57,7 +57,14 @@ export class AutoHeightController extends Disposable { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + + if (!subUnitId) { + return { + redos: [], + undos: [], + }; + } const sheetSkeletonService = this._renderManagerService.getRenderById(unitId)!.with(SheetSkeletonManagerService); const { skeleton } = sheetSkeletonService.getCurrent()!; 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 5abda1fbd81..a4166db18a6 100644 --- a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts +++ b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts @@ -60,6 +60,11 @@ export class CellCustomRenderController extends Disposable implements IRenderMod const { offsetX, offsetY } = evt; const scene = currentRender.scene; const worksheet = workbook.getActiveSheet(); + + if (!worksheet) { + return; + } + const activeViewport = scene.getActiveViewportByCoord( Vector2.FromArray([offsetX, offsetY]) ); @@ -107,7 +112,8 @@ export class CellCustomRenderController extends Disposable implements IRenderMod const row = cellIndex.actualRow; const col = cellIndex.actualCol; const sortedRenders = renders.sort(sortRules); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = worksheet.getSheetId(); + const info: ICellRenderContext = { data: cellData, style: skeleton.getsStyles().getStyleByCell(cellData), diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts index e40e0a454e0..9d3ddb66cfd 100644 --- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts +++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts @@ -673,10 +673,16 @@ export class SheetClipboardController extends RxDisposable { onPasteColumns(pasteTo, colProperties, payload) { const workbook = self._currentUniverSheet.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + + if (!unitId || !subUnitId) { + throw new Error('Cannot find unitId or subUnitId'); + } + const redoMutations: IMutationInfo[] = []; const undoMutations: IMutationInfo[] = []; const currentSheet = self._getWorksheet(unitId, subUnitId); + const { range } = pasteTo; // if the range is outside ot the worksheet's boundary, we should add rows const maxColumn = currentSheet!.getMaxColumns(); diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts index 2d51322a88c..00295f39e35 100644 --- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts +++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts @@ -89,7 +89,7 @@ describe('Test EndEditController', () => { contextService = get(IContextService); lexerTreeBuilder = new LexerTreeBuilder(); - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const config = worksheet.getConfig(); spreadsheetSkeleton = new SpreadsheetSkeleton( worksheet, diff --git a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts index b237e11ad5e..f32b8769b26 100644 --- a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts +++ b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts @@ -45,6 +45,9 @@ export class ForceStringAlertRenderController extends Disposable implements IRen if (cellPos) { const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + + if (!worksheet) return; + const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col); if (cellData?.t === CellValueType.FORCE_STRING && cellData.v && isRealNum(cellData.v)) { diff --git a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts index e5383c3ae21..c6d3a1051a9 100644 --- a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts +++ b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts @@ -70,7 +70,7 @@ export class FormatPainterController extends Disposable { const { rangeWithCoord } = selections[selections.length - 1]; this._commandService.executeCommand(ApplyFormatPainterCommand.id, { unitId: this._univerInstanceService.getFocusedUnit()?.getUnitId() || '', - subUnitId: (this._univerInstanceService.getFocusedUnit() as Workbook).getActiveSheet().getSheetId(), + subUnitId: (this._univerInstanceService.getFocusedUnit() as Workbook).getActiveSheet()?.getSheetId() || '', range: { startRow: rangeWithCoord.startRow, startColumn: rangeWithCoord.startColumn, @@ -115,8 +115,9 @@ export class FormatPainterController extends Disposable { const { startRow, endRow, startColumn, endColumn } = range; const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook?.getActiveSheet(); + if (!worksheet) return null; const cellData = worksheet.getCellMatrix(); - const mergeData = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getMergeData(); + const mergeData = worksheet.getMergeData(); const styles = workbook.getStyles(); const stylesMatrix = new ObjectMatrix(); diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts index c7e0773de33..0f9b2e63a38 100644 --- a/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts +++ b/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts @@ -89,21 +89,21 @@ describe('Test row col menu items', () => { function getRowCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowCount(); } function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } async function selectRow(rowStart: number, rowEnd: number): Promise { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const endColumn = getColCount() - 1; return commandService.executeCommand(SetSelectionsOperation.id, { unitId: workbook.getUnitId(), @@ -131,7 +131,7 @@ describe('Test row col menu items', () => { async function selectColumn(columnStart: number, columnEnd: number): Promise { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; const endRow = getRowCount() - 1; return commandService.executeCommand(SetSelectionsOperation.id, { unitId: workbook.getUnitId(), diff --git a/packages/sheets-ui/src/controllers/menu/menu-util.ts b/packages/sheets-ui/src/controllers/menu/menu-util.ts index cb208c95ec0..7e39e5766a4 100644 --- a/packages/sheets-ui/src/controllers/menu/menu-util.ts +++ b/packages/sheets-ui/src/controllers/menu/menu-util.ts @@ -66,6 +66,10 @@ export function getCurrentRangeDisable$(accessor: IAccessor, permissionTypes: IP } const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return of(true); + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -133,6 +137,10 @@ export function getCommentDisable$(accessor: IAccessor, permissionTypes: IPermis } const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return of(true); + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -191,6 +199,10 @@ export function getBaseRangeMenuHidden$(accessor: IAccessor) { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return true; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -227,6 +239,10 @@ export function getInsertAfterMenuHidden$(accessor: IAccessor, type: 'row' | 'co const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return true; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -269,6 +285,10 @@ export function getInsertBeforeMenuHidden$(accessor: IAccessor, type: 'row' | 'c const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return true; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -311,6 +331,10 @@ export function getDeleteMenuHidden$(accessor: IAccessor, type: 'row' | 'col') { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return true; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); @@ -356,6 +380,10 @@ export function getCellMenuHidden$(accessor: IAccessor, type: 'row' | 'col') { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return true; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); diff --git a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts index 7692ddbd67b..cd6870f937f 100644 --- a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts +++ b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts @@ -35,6 +35,10 @@ export function getAddPermissionHidden$(accessor: IAccessor) { ).pipe( map(() => { const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const subUnitRuleList = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId); @@ -72,6 +76,10 @@ export function getEditPermissionHidden$(accessor: IAccessor) { ).pipe( map(() => { const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const subUnitRuleList = rangeRuleModel.getSubunitRuleList(unitId, subUnitId); diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts index 4a0e4ca93c9..5d468814883 100644 --- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts +++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts @@ -60,6 +60,10 @@ export class SheetPermissionInterceptorClipboardController extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } + const { startRow, endRow, startColumn, endColumn } = targetRange; let hasPermission = true; diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts index 7d951c3d695..d6edbf7d730 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts @@ -74,7 +74,8 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende const sheetObject = this._getSheetObject(); const { scene, engine } = sheetObject; const unitId = this._context.unitId; - const sheetId = this._context.unit.getActiveSheet().getSheetId(); + const sheetId = this._context.unit.getActiveSheet()?.getSheetId(); + if (!sheetId) return; this._commandService.executeCommand(SetActivateCellEditOperation.id, { scene, @@ -203,6 +204,8 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende const selectionWithStyle = this._selectionManagerService.getSelections(); const { unitId, sheetId, sheetName } = this._getCurrentUnitIdAndSheetId(); + if (!sheetId || !sheetName) return; + const ranges = selectionWithStyle?.map((value: ISelectionWithStyle) => { return { range: value.range, unitId, sheetId, sheetName }; }); @@ -221,6 +224,8 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende const { unitId, sheetId, sheetName } = this._getCurrentUnitIdAndSheetId(); + if (!sheetId || !sheetName) return; + const ranges = selectionWithStyle.map((value: ISelectionWithStyle) => { return { range: value.range, unitId, sheetId, sheetName }; }); @@ -233,8 +238,8 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende const worksheet = workbook.getActiveSheet(); return { unitId: workbook.getUnitId(), - sheetId: worksheet.getSheetId(), - sheetName: worksheet.getName(), + sheetId: worksheet?.getSheetId(), + sheetName: worksheet?.getName(), }; } diff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts index 620c64eddec..9c1eec6247f 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts @@ -583,6 +583,8 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const oldFreeze = worksheet.getConfig()?.freeze; let xSplit = oldFreeze?.xSplit || 0; let ySplit = oldFreeze?.ySplit || 0; @@ -1072,6 +1074,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM private _refreshCurrent() { const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; const freeze = worksheet.getConfig().freeze; @@ -1124,6 +1127,9 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM const workbook = this._context.unit; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return empty; + } const subUnitId = worksheet.getSheetId(); this._refreshFreeze( @@ -1354,7 +1360,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM const worksheet = workbook.getActiveSheet(); const params = command.params as ISetFrozenMutationParams; const { unitId, subUnitId } = params; - if (!(unitId === workbook.getUnitId() && subUnitId === worksheet.getSheetId())) { + if (!(unitId === workbook.getUnitId() && subUnitId === worksheet?.getSheetId())) { return; } diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts index 3a58fabd654..e16c0cc40c3 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts @@ -243,6 +243,9 @@ export class HeaderMenuRenderController extends Disposable implements IRenderMod private _getSelectionOnColumn(column: number): ISetSelectionsOperationParams { const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active worksheet'); + } return { unitId: workbook.getUnitId(), diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts index 50ae157b9e4..1e4257f0859 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts @@ -316,6 +316,8 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM skeleton; const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const zoomRatio = worksheet.getZoomRatio() || 1; scene?.setScaleValue(zoomRatio, zoomRatio); scene?.transformByState({ @@ -413,6 +415,8 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM if (skeleton == null) return false; const worksheet = this._context.unit.getActiveSheet(); + if (!worksheet) return false; + const { startColumn: freezeStartColumn, startRow: freezeStartRow, diff --git a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts index 67d35df7ea1..858d9f61474 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts @@ -74,6 +74,9 @@ export class SelectionRenderController extends Disposable implements IRenderModu private _init() { const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet'); + } const sheetObject = this._getSheetObject(); this._initViewMainListener(sheetObject); @@ -136,6 +139,10 @@ export class SelectionRenderController extends Disposable implements IRenderModu let worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return []; + } + const selections = []; for (let i = 0; i < valueArray.length; i++) { @@ -366,6 +373,9 @@ export class SelectionRenderController extends Disposable implements IRenderModu const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return; + } this._definedNamesService.setCurrentRange({ range: lastSelection.range, @@ -393,7 +403,9 @@ export class SelectionRenderController extends Disposable implements IRenderModu if (!workbook) return; const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()?.getSheetId(); + if (!sheetId) return; + const current = this._selectionManagerService.getCurrent(); if (selectionDataWithStyleList == null || selectionDataWithStyleList.length === 0) { @@ -425,7 +437,7 @@ export class SelectionRenderController extends Disposable implements IRenderModu const params = command.params as ISetZoomRatioOperationParams; const { unitId, subUnitId } = params; - if (!(unitId === workbook.getUnitId() && subUnitId === worksheet.getSheetId())) { + if (!(unitId === workbook.getUnitId() && subUnitId === worksheet?.getSheetId())) { return; } diff --git a/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts index dace4df2c2e..d3b687bb92e 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts @@ -67,7 +67,12 @@ export class SheetRenderController extends RxDisposable implements IRenderModule this._initRerenderScheduler(); this._initCommandListener(); - const sheetId = this._context.unit.getActiveSheet().getSheetId(); + const worksheet = this._context.unit.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + + const sheetId = worksheet.getSheetId(); this._sheetSkeletonManagerService.setCurrent({ sheetId }); const should = workbook.getShouldRenderLoopImmediately(); if (should) { @@ -79,6 +84,10 @@ export class SheetRenderController extends RxDisposable implements IRenderModule const { scene, components } = this._context; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN); this._addViewport(worksheet); @@ -273,6 +282,8 @@ export class SheetRenderController extends RxDisposable implements IRenderModule const unitId = workbook.getUnitId(); if (COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id) || this._sheetRenderService.checkMutationShouldTriggerRerender(command.id)) { const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const sheetId = worksheet.getSheetId(); const params = command.params; const { unitId, subUnitId } = params as ISetWorksheetMutationParams; diff --git a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts index 37efcb1d959..fa817499c6a 100644 --- a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts +++ b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts @@ -67,6 +67,8 @@ export class SheetsZoomRenderController extends Disposable implements IRenderMod const workbook = this._context.unit; const sheet = workbook.getActiveSheet(); + if (!sheet) return; + const currentRatio = sheet.getZoomRatio(); let nextRatio = +Number.parseFloat(`${currentRatio + ratioDelta}`).toFixed(1); nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio; @@ -90,6 +92,8 @@ export class SheetsZoomRenderController extends Disposable implements IRenderMod const workbook = this._context.unit; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const zoomRatio = worksheet.getZoomRatio() || 1; // viewport.resize --> setScrollInfo this._updateViewZoom(zoomRatio); diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts index bb2f144f34f..c006251812f 100644 --- a/packages/sheets-ui/src/controllers/status-bar.controller.ts +++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts @@ -132,7 +132,11 @@ export class StatusBarController extends Disposable { return this._clearResult(); } const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); + const sheetId = workbook.getActiveSheet()?.getSheetId(); + if (!sheetId) { + return this._clearResult(); + } + const sheetData: ISheetData = {}; const arrayFormulaMatrixCell = this._formulaDataModel.getArrayFormulaCellData(); diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts index 5b1bff50ab6..dd42ea36871 100644 --- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts +++ b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts @@ -275,7 +275,7 @@ export class AutoFillService extends Disposable implements IAutoFillService { source, target, unitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(), - subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(), + subUnitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(), } = this.autoFillLocation || {}; const direction = this.direction; if (!source || !target || unitId !== triggerUnitId || subUnitId !== triggerSubUnitId) { diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts index 82820cde880..2f08d0c59b8 100644 --- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts +++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts @@ -104,6 +104,14 @@ export class SheetCanvasPopManagerService extends Disposable { attachPopupToObject(targetObject: BaseObject, popup: ICanvasPopup): IDisposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return { + dispose: () => { + // empty + }, + }; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({ @@ -153,6 +161,10 @@ export class SheetCanvasPopManagerService extends Disposable { attachPopupToCell(row: number, col: number, popup: ICanvasPopup, viewport?: Viewport): Nullable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return null; + } + const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({ diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts index 5eb09a20000..9a74e41b50f 100644 --- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts +++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts @@ -159,6 +159,9 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return false; + } const copyContent = this.generateCopyContent(workbook.getUnitId(), worksheet.getSheetId(), selection.range); if (!copyContent) { @@ -333,7 +336,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard private async _pastePlainText(text: string, pasteType: string): Promise { const target = this._getPastingTarget(); - if (!target.selection) { + if (!target.subUnitId || !target.selection) { return false; } const accessor = { @@ -731,7 +734,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard const selection = this._selectionManagerService.getLast(); return { unitId: workbook.getUnitId(), - subUnitId: worksheet.getSheetId(), + subUnitId: worksheet?.getSheetId(), selection, }; } @@ -785,7 +788,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard ): IPasteTarget | null { const target = this._getPastingTarget(); const { selection, unitId, subUnitId } = target; - if (!selection) { + if (!subUnitId || !selection) { return null; } const accessor = { @@ -915,7 +918,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard private _getPastedRange(cellMatrix: ObjectMatrix) { const target = this._getPastingTarget(); const { selection, unitId, subUnitId } = target; - if (!selection) { + if (!subUnitId || !selection) { return null; } const accessor = { diff --git a/packages/sheets-ui/src/services/drag-manager.service.ts b/packages/sheets-ui/src/services/drag-manager.service.ts index 934cce752e7..de5720a8f89 100644 --- a/packages/sheets-ui/src/services/drag-manager.service.ts +++ b/packages/sheets-ui/src/services/drag-manager.service.ts @@ -75,6 +75,7 @@ export class DragManagerService extends Disposable { } const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; // const skeletonParam = this._sheetSkeletonManagerService.getCurrent(); const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId()); const skeletonParam = currentRender?.with(SheetSkeletonManagerService)?.getCurrent(); diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts index 78c4fce70c9..8985d42dcad 100644 --- a/packages/sheets-ui/src/services/editor-bridge.service.ts +++ b/packages/sheets-ui/src/services/editor-bridge.service.ts @@ -213,6 +213,8 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; + const location = { workbook, worksheet, diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts index 783e2574864..38c6ed142e4 100644 --- a/packages/sheets-ui/src/services/hover-manager.service.ts +++ b/packages/sheets-ui/src/services/hover-manager.service.ts @@ -80,6 +80,11 @@ export class HoverManagerService extends Disposable { } const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + this._currentCell$.next(null); + return; + } + const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId()); const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getUnitSkeleton(workbook.getUnitId(), worksheet.getSheetId()); const scrollInfo = this._scrollManagerService.getCurrentScrollInfo(); diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts index 81d9000906a..95dd6acd3fe 100644 --- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts +++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts @@ -58,7 +58,8 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe addShape(selection: ISelectionWithStyle, exits: string[] = [], zIndex: number = DEFAULT_Z_INDEX): string | null { const workbook = this._currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const subUnitId = workbook.getActiveSheet().getSheetId(); + const subUnitId = workbook.getActiveSheet()?.getSheetId(); + if (!subUnitId) return null; const id = Tools.generateRandomId(); this._shapeMap.set(id, { selection, @@ -74,7 +75,7 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe refreshShapes() { const currentUnitId = this._currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId(); - const currentSubUnitId = this._currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + const currentSubUnitId = this._currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); this._shapeMap.forEach((shape) => { const { unitId, subUnitId, selection, control: oldControl, zIndex } = shape; diff --git a/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts b/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts index 0fa6e840cc9..aa579a23df3 100644 --- a/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts +++ b/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts @@ -199,7 +199,7 @@ describe('Test indirect', () => { const workbook = testBed.sheet; - const worksheet = workbook?.getActiveSheet(); + const worksheet = workbook?.getActiveSheet()!; const config = worksheet.getConfig(); diff --git a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx index 8c1c41d6c06..553c798c9a6 100644 --- a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx +++ b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx @@ -36,7 +36,8 @@ export function ZoomSlider() { const univerInstanceService = useDependency(IUniverInstanceService); const getCurrentZoom = useCallback(() => { - const currentZoom = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getZoomRatio() * 100 || 100; + const worksheet = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const currentZoom = (worksheet && (worksheet.getZoomRatio() * 100)) || 100; return Math.round(currentZoom); }, [univerInstanceService]); diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx index 515f4c3d5b3..53f6e8bceb2 100644 --- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx +++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx @@ -118,7 +118,10 @@ export const DefinedNameContainer = () => { }; const getInertFormulaOrRefString = () => { - const sheetName = workbook.getActiveSheet().getName(); + const sheetName = workbook.getActiveSheet()?.getName(); + if (!sheetName) { + return ''; + } const selections = selectionManagerService.getSelections(); if (selections == null) { diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx index 12197b1c0af..a77a30e4f4f 100644 --- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx +++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx @@ -68,8 +68,6 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => { const unitId = workbook.getUnitId(); - const sheetId = workbook.getActiveSheet().getSheetId(); - const [nameValue, setNameValue] = useState(name); const [formulaOrRefStringValue, setFormulaOrRefStringValue] = useState(formulaOrRefString); diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx index 41960cc4dea..49999d01597 100644 --- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx +++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx @@ -60,6 +60,7 @@ export function FormulaBar() { ).subscribe(() => { const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return; const subUnitId = worksheet.getSheetId(); const range = selectionManager.getLast()?.range; if (!range) return; diff --git a/packages/sheets-ui/src/views/permission/panel-list/index.tsx b/packages/sheets-ui/src/views/permission/panel-list/index.tsx index 6812bec8a4a..70a5c4f4d03 100644 --- a/packages/sheets-ui/src/views/permission/panel-list/index.tsx +++ b/packages/sheets-ui/src/views/permission/panel-list/index.tsx @@ -249,6 +249,9 @@ export const SheetPermissionPanelList = () => { onMouseMove={() => { const { subUnitId, unitType } = rule; const activeSheet = workbook.getActiveSheet(); + if (!activeSheet) { + return false; + } const activeSubUnitId = activeSheet.getSheetId(); if (subUnitId !== activeSubUnitId) { return false; diff --git a/packages/sheets-ui/src/views/permission/permission-dialog/index.tsx b/packages/sheets-ui/src/views/permission/permission-dialog/index.tsx index d51f4d955d7..0bd445e5eab 100644 --- a/packages/sheets-ui/src/views/permission/permission-dialog/index.tsx +++ b/packages/sheets-ui/src/views/permission/permission-dialog/index.tsx @@ -45,6 +45,10 @@ export const SheetPermissionDialog = () => { const permissionService = useDependency(IPermissionService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + const [collaborators, setCollaborators] = useState([]); const commandService = useDependency(ICommandService); const [loading, setLoading] = useState(() => { @@ -108,6 +112,9 @@ export const SheetPermissionDialog = () => { const handleChangeActionPermission = async () => { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook?.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } const unitId = workbook.getUnitId(); const subUnitId = worksheet.getSheetId(); const pointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId); diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx index 74ad2dd2cb7..e20f9e4aff3 100644 --- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx +++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx @@ -74,7 +74,7 @@ export function SheetBarTabs() { const permissionService = useDependency(IPermissionService); const statusInit = useCallback(() => { - const currentSubUnitId = workbook.getActiveSheet().getSheetId(); + const currentSubUnitId = workbook.getActiveSheet()?.getSheetId() || ''; setActiveKey(currentSubUnitId); const sheets = workbook.getSheets(); @@ -182,6 +182,10 @@ export function SheetBarTabs() { onNameChangeCheck: () => { const unitId = workbook.getUnitId(); const worksheet = workbook?.getActiveSheet(); + if (!worksheet) { + throw new Error('No active sheet found'); + } + const subUnitId = worksheet.getSheetId(); const worksheetRule = worksheetProtectionRuleModel.getRule(unitId, subUnitId); const selectionRule = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).length > 0; @@ -228,7 +232,7 @@ export function SheetBarTabs() { const nameRepeatCheck = (name: string) => { const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const worksheet = workbook.getActiveSheet(); - const currenSheetName = worksheet.getName(); + const currenSheetName = worksheet?.getName(); // TODO@Dushusir: no need trigger save if (currenSheetName === name) return false; diff --git a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts index bd64ea72fa8..821cf0d0c44 100644 --- a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts @@ -144,14 +144,14 @@ describe('Test insert and remove rows cols commands', () => { function getRowCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowCount(); } function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } @@ -162,21 +162,21 @@ describe('Test insert and remove rows cols commands', () => { function getCellInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getCellMatrix().getValue(row, col); } function getMergedInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getMergedCell(row, col); } function getMergeData() { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getMergeData(); } diff --git a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts index d4ca71b15d5..59a5f2add8b 100644 --- a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts @@ -139,14 +139,14 @@ describe('Test move range commands', () => { function getMergedInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getMergedCell(row, col); } function getMergeData() { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getConfig().mergeData; } }); diff --git a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts index 5b4b006f479..4954de419fa 100644 --- a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts @@ -121,42 +121,42 @@ describe('Test move rows cols', () => { function getRowCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowCount(); } function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } function getCellInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getCellMatrix().getValue(row, col); } function getMergedInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getMergedCell(row, col); } function getRowHeight(row: number): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowHeight(row); } function getColWidth(col: number): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnWidth(col); } diff --git a/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts index 5c4ee12dfcb..38d96d92108 100644 --- a/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts @@ -94,14 +94,14 @@ describe('Test remove rows cols', () => { function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } function getCellInfo(row: number, col: number): Nullable { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getCellMatrix().getValue(row, col); } diff --git a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts index 88fa13a7548..873cbbc709b 100644 --- a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts @@ -31,7 +31,7 @@ describe('Test set col width commands', () => { let commandService: ICommandService; function getColumnWidth(col: number): number { - const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!; return worksheet.getColumnWidth(col); } @@ -45,7 +45,7 @@ describe('Test set col width commands', () => { commandService.registerCommand(SetColWidthCommand); commandService.registerCommand(SetWorksheetColWidthMutation); - const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!; const maxRow = worksheet.getMaxRows() - 1; const selectionManagerService = get(SelectionManagerService); selectionManagerService.setCurrentSelection({ diff --git a/packages/sheets/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-frozen.command.spec.ts index d28bb6d8473..f2fa6377119 100644 --- a/packages/sheets/src/commands/commands/__tests__/set-frozen.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/set-frozen.command.spec.ts @@ -111,7 +111,7 @@ describe('Test set frozen commands', () => { const workbook = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; if (!workbook) throw new Error('This is an error'); - const targetActiveSheet = workbook.getActiveSheet(); + const targetActiveSheet = workbook.getActiveSheet()!; const targetSheetId = targetActiveSheet?.getSheetId(); const originFreeze = workbook.getSheetBySheetId(targetSheetId)?.getConfig().freeze; expect( diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts index af8ffd7babe..ba0c2fbae77 100644 --- a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts @@ -76,26 +76,26 @@ describe('Test row col hide/unhine commands', () => { function getRowCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowCount(); } function getColCount(): number { const currentService = get(IUniverInstanceService); const workbook = currentService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColumnCount(); } function getRowRawVisible(row: number): boolean { const workbook = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getRowRawVisible(row); } function getColVisible(col: number): boolean { const workbook = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet.getColVisible(col); } diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts index dd70d551bc8..5e6a9a828c1 100644 --- a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts @@ -48,12 +48,12 @@ describe('Test set row height commands', () => { let commandService: ICommandService; function getRowHeight(row: number): number { - const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!; return worksheet.getRowHeight(row); } function getRowIsAutoHeight(row: number): Nullable { - const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!; const rowManager = worksheet.getRowManager(); const rowInfo = rowManager.getRow(row); @@ -72,7 +72,7 @@ describe('Test set row height commands', () => { commandService.registerCommand(SetWorksheetRowHeightMutation); commandService.registerCommand(SetWorksheetRowIsAutoHeightMutation); - const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); + const worksheet = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!; const maxColumn = worksheet.getMaxColumns() - 1; const selectionManager = get(SelectionManagerService); diff --git a/packages/sheets/src/commands/commands/__tests__/set-worksheet-show.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-worksheet-show.command.spec.ts index adbb315163a..6b21a3b3460 100644 --- a/packages/sheets/src/commands/commands/__tests__/set-worksheet-show.command.spec.ts +++ b/packages/sheets/src/commands/commands/__tests__/set-worksheet-show.command.spec.ts @@ -56,7 +56,7 @@ describe('Test set worksheet show commands', () => { const workbook = get(IUniverInstanceService).getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; if (!workbook) throw new Error('This is an error'); - const targetActiveSheet = workbook.getActiveSheet(); + const targetActiveSheet = workbook.getActiveSheet()!; const targetSheetId = targetActiveSheet?.getSheetId(); expect( await commandService.executeCommand(SetWorksheetActivateCommand.id, { subUnitId: targetSheetId }) diff --git a/packages/sheets/src/commands/commands/clear-selection-all.command.ts b/packages/sheets/src/commands/commands/clear-selection-all.command.ts index d3e5a5d40ce..60fc32221dc 100644 --- a/packages/sheets/src/commands/commands/clear-selection-all.command.ts +++ b/packages/sheets/src/commands/commands/clear-selection-all.command.ts @@ -49,6 +49,8 @@ export const ClearSelectionAllCommand: ICommand = { const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + const subUnitId = worksheet.getSheetId(); const selections = selectionManagerService.getSelectionRanges(); if (!selections?.length) { diff --git a/packages/sheets/src/commands/commands/clear-selection-content.command.ts b/packages/sheets/src/commands/commands/clear-selection-content.command.ts index 56461fa9bd3..c4ce18c0857 100644 --- a/packages/sheets/src/commands/commands/clear-selection-content.command.ts +++ b/packages/sheets/src/commands/commands/clear-selection-content.command.ts @@ -51,6 +51,8 @@ export const ClearSelectionContentCommand: ICommand = { const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + const subUnitId = worksheet.getSheetId(); const selections = selectionManagerService.getSelectionRanges(); if (!selections?.length) { diff --git a/packages/sheets/src/commands/commands/clear-selection-format.command.ts b/packages/sheets/src/commands/commands/clear-selection-format.command.ts index 6c7fcc868b0..7a7b23b296d 100644 --- a/packages/sheets/src/commands/commands/clear-selection-format.command.ts +++ b/packages/sheets/src/commands/commands/clear-selection-format.command.ts @@ -51,6 +51,8 @@ export const ClearSelectionFormatCommand: ICommand = { const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) return false; + const subUnitId = worksheet.getSheetId(); const selections = selectionManagerService.getSelectionRanges(); if (!selections?.length) { diff --git a/packages/sheets/src/commands/mutations/__tests__/remove-row-col.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/remove-row-col.mutation.spec.ts index 829f8bbc78e..3763d766111 100644 --- a/packages/sheets/src/commands/mutations/__tests__/remove-row-col.mutation.spec.ts +++ b/packages/sheets/src/commands/mutations/__tests__/remove-row-col.mutation.spec.ts @@ -37,13 +37,13 @@ describe('Test moving rows & cols', () => { const getWorksheet = () => { const univerInstanceService = get(IUniverInstanceService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return worksheet; }; const getId = () => { const univerInstanceService = get(IUniverInstanceService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const worksheet = workbook.getActiveSheet(); + const worksheet = workbook.getActiveSheet()!; return { unitId: workbook.getUnitId(), subUnitId: worksheet.getSheetId(), diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.ts index 6cc8794607e..4caf0bf6c16 100644 --- a/packages/sheets/src/controllers/merge-cell.controller.ts +++ b/packages/sheets/src/controllers/merge-cell.controller.ts @@ -145,6 +145,10 @@ export class MergeCellController extends Disposable { const workbook = self._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); const worksheet = workbook.getActiveSheet(); + if (!worksheet) { + return { redos: [], undos: [] }; + } + const subUnitId = worksheet.getSheetId(); const mergeData = worksheet.getConfig().mergeData; const selections = self._selectionManagerService.getSelectionRanges(); @@ -279,6 +283,8 @@ export class MergeCellController extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; if (workbook) { const sheet = workbook.getActiveSheet(); + if (!sheet) return; + registerRefRange(workbook.getUnitId(), sheet.getSheetId()); } } diff --git a/packages/sheets/src/services/__tests__/numfmt.service.test.ts b/packages/sheets/src/services/__tests__/numfmt.service.test.ts index 1d7a38172ac..5b0406c498d 100644 --- a/packages/sheets/src/services/__tests__/numfmt.service.test.ts +++ b/packages/sheets/src/services/__tests__/numfmt.service.test.ts @@ -47,7 +47,7 @@ describe('test numfmt service', () => { const univerInstanceService = get(IUniverInstanceService); const numfmtService = get(INumfmtService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - const sheet = workbook.getActiveSheet(); + const sheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = sheet.getSheetId(); const params: ISetNumfmtMutationParams = { @@ -78,7 +78,7 @@ describe('test numfmt service', () => { const numfmtService = get(INumfmtService); const workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; const styles = workbook.getStyles(); - const sheet = workbook.getActiveSheet(); + const sheet = workbook.getActiveSheet()!; const unitId = workbook.getUnitId(); const subUnitId = sheet.getSheetId(); const params: ISetNumfmtMutationParams = { diff --git a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts index 3e40679e5c7..f7efb91bef9 100644 --- a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts +++ b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts @@ -66,7 +66,7 @@ describe('Test ref-range.service', () => { const univerInstanceService = get(IUniverInstanceService); workbook = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; - worksheet = workbook.getActiveSheet(); + worksheet = workbook.getActiveSheet()!; }); afterEach(() => { univer.dispose(); diff --git a/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts b/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts index 32ee34bde93..092525d7781 100644 --- a/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts +++ b/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts @@ -127,6 +127,8 @@ export class RangeProtectionRefRangeService extends Disposable { const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!; if (workbook) { const sheet = workbook.getActiveSheet(); + if (!sheet) return; + registerRefRange(workbook.getUnitId(), sheet.getSheetId()); } } diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.ts index 4d81ffef5e5..290fbae91bc 100644 --- a/packages/sheets/src/services/ref-range/ref-range.service.ts +++ b/packages/sheets/src/services/ref-range/ref-range.service.ts @@ -161,6 +161,9 @@ export class RefRangeService extends Disposable { const worksheet = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet(); const unitId = getUnitId(this._univerInstanceService); const subUnitId = getSubUnitId(this._univerInstanceService); + if (!worksheet || !unitId || !subUnitId) { + return { redos: [], undos: [], preRedos: [], preUndos: [] }; + } // eslint-disable-next-line max-lines-per-function const getEffectsCbList = () => { switch (command.id) { @@ -365,6 +368,10 @@ export class RefRangeService extends Disposable { ): IDisposable => { const unitId = _unitId || getUnitId(this._univerInstanceService); const subUnitId = _subUnitId || getSubUnitId(this._univerInstanceService); + if (!unitId || !subUnitId) { + return toDisposable(() => {}); + } + const refRangeManagerId = getRefRangId(unitId, subUnitId); const rangeString = this._serializer.serialize(range); @@ -400,7 +407,7 @@ function getUnitId(univerInstanceService: IUniverInstanceService) { } function getSubUnitId(univerInstanceService: IUniverInstanceService) { - return univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(); + return univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(); } function getSelectionRanges(selectionManagerService: SelectionManagerService) {