fix(sheet): maybe get null when get active sheet (#2512)

* fix(sheet): maybe get null when get active sheet

* test(sheet): active sheet test

* fix(sheet): active sheet when init all sheets

* type(sheet): lint error

* fix(sheet): back demo data

* test(numfmt): remove unused ensureActiveSheet
This commit is contained in:
Dushusir
2024-06-15 15:48:10 +08:00
committed by GitHub
parent b6ef910eb8
commit 85e15afa80
111 changed files with 492 additions and 300 deletions
@@ -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(() => {
+12 -160
View File
@@ -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<IWorkbookData, UniverInstanceType.UNIVER
}
/**
*
* @returns
* Get the active sheet
*/
getRawActiveSheet(): Nullable<Worksheet> {
getActiveSheet(): Nullable<Worksheet> {
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<IWorkbookData, UniverInstanceType.UNIVER
.map((s) => 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<IWorkbookData, UniverInstanceType.UNIVER
return output;
}
/**
* Get the range array based on the range string and sheet id
*
* @param txt - range string
* @returns
*/
private _getCellRange(txt: IRangeStringData): IGridRange {
let sheetTxt: string = '';
let rangeTxt: string | string[] = '';
if (txt.indexOf('!') > -1) {
const val = txt.split('!');
sheetTxt = val[0];
rangeTxt = val[1];
sheetTxt = sheetTxt.replace(/\\'/g, "'").replace(/''/g, "'");
if (sheetTxt.substring(0, 1) === "'" && sheetTxt.substring(sheetTxt.length - 1, 1) === "'") {
sheetTxt = sheetTxt.substring(1, sheetTxt.length - 1);
}
} else {
rangeTxt = txt;
}
if (rangeTxt.indexOf(':') === -1) {
const row = 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<IWorkbookData, UniverInstanceType.UNIVER
sheetOrder.push(sheetId);
}
}
// Active the first sheet.
this.ensureActiveSheet();
}
}
@@ -45,7 +45,12 @@ export class DataValidationSheetController extends Disposable {
if (!workbook) {
return { redos: [], undos: [] };
}
const subUnitId = params.subUnitId || workbook.getActiveSheet().getSheetId();
const subUnitId = params.subUnitId || workbook.getActiveSheet()?.getSheetId();
if (!subUnitId) {
return { redos: [], undos: [] };
}
const manager = this._dataValidationModel.ensureManager(unitId, subUnitId);
if (!manager) {
return { redos: [], undos: [] };
@@ -54,6 +54,9 @@ export const SaveSnapshotOptions: ICommand = {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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;
@@ -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 },
@@ -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);
+1 -1
View File
@@ -66,7 +66,7 @@ export function getCurrentUnitInfo(currentUniverService: IUniverInstanceService)
let subUnitId: Nullable<string>;
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) {
@@ -267,7 +267,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
const sheetData: ISheetData = {};
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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()] = {
@@ -216,7 +216,7 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies
const sheetData: ISheetData = {};
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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()] = {
@@ -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() });
+10 -2
View File
@@ -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);
}
/**
@@ -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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
const formulaInitValue = useMemo(() => {
return String(value).startsWith('=') ? String(value) : '=';
}, [value]);
@@ -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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
const _value = useRef(value);
const config = useMemo(() => {
if ([CFValueType.percentile, CFValueType.percent].includes(type)) {
@@ -74,7 +74,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
<div className={`${stylesBase.mTSm}`}>
<TextEditor
id={createInternalEditorID(`${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_formula`)}
openForSheetSubUnitId={worksheet.getSheetId()}
openForSheetSubUnitId={worksheet?.getSheetId()}
openForSheetUnitId={workbook.getUnitId()}
value={formula}
canvasStyle={{ fontSize: 10 }}
@@ -40,7 +40,7 @@ const getIcon = (iconType: string, iconId: string | number) => {
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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
const className = useMemo(() => {
if (props.error) {
return styles.errorInput;
@@ -48,7 +48,7 @@ interface IRuleEditProps {
}
const getUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const getSubUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const getSubUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(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 };
@@ -118,6 +118,10 @@ export const RuleList = (props: IRuleListProps) => {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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<IRange[]>([]);
@@ -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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(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));
@@ -52,7 +52,11 @@ export class ConditionalFormattingAutoFillController extends Disposable {
mapFunc: (row: number, col: number) => ({ row: number; col: number })
) => {
const unitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getUnitId();
const subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet().getSheetId();
const subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet()?.getSheetId();
const matrixMap: Map<string, ObjectMatrix<1>> = new Map();
const redos: IMutationInfo[] = [];
@@ -49,6 +49,10 @@ export class ConditionalFormattingClearController extends Disposable {
}
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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;
@@ -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<Workbook>(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.
@@ -72,7 +72,7 @@ export class SheetsCfRefRangeController extends Disposable {
const { unitId, subUnitId, rule } = option;
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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) {
@@ -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));
}
@@ -33,6 +33,7 @@ const commandList = [SetWorksheetActiveOperation.id, AddConditionalRuleMutation.
type ICellPermission = Record<UnitAction, boolean> & { 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<Workbook>(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<Workbook>(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) => {
@@ -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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const getSubUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const getSubUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
@@ -44,6 +44,8 @@ export class DataValidationAlertController extends Disposable {
if (cellPos) {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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) {
@@ -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;
@@ -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<Workbook>(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();
@@ -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<Workbook>(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);
@@ -24,7 +24,7 @@ export function getSheetRangeValueSet(grid: IUnitRangeName, univerInstanceServic
const workbook = univerInstanceService.getUniverSheetInstance(unitId) ?? univerInstanceService.getCurrentUnitForType<Workbook>(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;
}
@@ -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;
}
@@ -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,
@@ -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),
@@ -37,6 +37,7 @@ describe('Test "Filter Interceptor"', () => {
get = testBed.get;
sheetsFilterService = testBed.sheetsFilterService;
commandService = testBed.commandService;
univer.__getInjector();
});
afterEach(() => {
@@ -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;
@@ -210,7 +210,7 @@ describe('test "hitCell" method', () => {
beforeEach(() => {
const testBed = createTestBed();
univer = testBed.univer;
worksheet = testBed.sheet.getActiveSheet();
worksheet = testBed.sheet.getActiveSheet()!;
});
afterEach(() => {
@@ -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;
@@ -59,6 +59,8 @@ export class FormulaAlertController extends Disposable {
if (cellPos) {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) return;
const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col);
if (cellData) {
@@ -93,7 +93,13 @@ export class FormulaClipboardController extends Disposable {
const matrix = data;
const workbook = this._currentUniverSheet.getCurrentUnitForType<Workbook>(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,
@@ -1142,7 +1142,7 @@ export class PromptController extends Disposable {
return {
unitId: workbook.getUnitId(),
sheetId: worksheet.getSheetId(),
sheetId: worksheet?.getSheetId() || '',
skeleton,
};
}
@@ -467,6 +467,8 @@ export class UpdateFormulaController extends Disposable {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const unitId = workbook.getUnitId();
const sheetId = workbook.getActiveSheet().getSheetId();
const sheetId = workbook.getActiveSheet()?.getSheetId() || '';
return {
unitId,
@@ -46,7 +46,7 @@ export class FormulaRefRangeService extends Disposable {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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) {
@@ -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) => ({
@@ -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);
@@ -239,6 +239,9 @@ export class SheetsHyperLinkResolverService {
return false;
}
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
return false;
}
if (worksheet.getSheetId() === subUnitId) {
return worksheet;
@@ -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);
@@ -53,7 +53,7 @@ describe('test cell-content', () => {
},
};
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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 });
@@ -54,7 +54,7 @@ describe('test editor', () => {
testBed.get(NumfmtEditorController);
testBed.get(SheetsNumfmtCellContentController);
workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
worksheet = workbook.getActiveSheet();
worksheet = workbook.getActiveSheet()!;
});
it('before edit with currency', () => {
@@ -107,6 +107,9 @@ export class NumfmtController extends Disposable implements INumfmtController {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const sheet = workbook.getActiveSheet();
if (!sheet) {
return false;
}
const cellValue = sheet.getCellRaw(range.startRow, range.startColumn);
const numfmtValue = numfmtService.getValue(
@@ -203,7 +203,13 @@ export class NumfmtEditorController extends Disposable {
case SetRangeValuesCommand.id: {
const workbook = self._univerInstanceService.getCurrentUnitForType<Workbook>(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 {
@@ -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 });
@@ -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));
@@ -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,
@@ -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<string | null>();
const panelService = useDependency(ThreadCommentPanelService);
const activeCommentId = useObservable(panelService.activeCommentId$);
@@ -352,6 +352,7 @@ describe('Test add worksheet merge commands', () => {
const univerInstanceService = get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(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();
@@ -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,
@@ -88,7 +88,7 @@ describe('Test commands used for change selections', () => {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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 () => {
@@ -115,14 +115,14 @@ describe('Test commands used for change selections', () => {
function getRowCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnCount();
}
@@ -152,6 +152,11 @@ export const DeleteWorksheetProtectionFormSheetBarCommand: ICommand = {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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);
@@ -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;
}
@@ -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<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getMergeData();
const worksheet = this._univerInstanceService.getCurrentUnitForType<Workbook>(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<Workbook>(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<ICellData>[][] = [];
target.rows.forEach((i) => {
@@ -57,7 +57,14 @@ export class AutoHeightController extends Disposable {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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()!;
@@ -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),
@@ -673,10 +673,16 @@ export class SheetClipboardController extends RxDisposable {
onPasteColumns(pasteTo, colProperties, payload) {
const workbook = self._currentUniverSheet.getCurrentUnitForType<Workbook>(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();
@@ -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,
@@ -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)) {
@@ -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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook?.getActiveSheet();
if (!worksheet) return null;
const cellData = worksheet.getCellMatrix();
const mergeData = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getMergeData();
const mergeData = worksheet.getMergeData();
const styles = workbook.getStyles();
const stylesMatrix = new ObjectMatrix<IStyleData>();
@@ -89,21 +89,21 @@ describe('Test row col menu items', () => {
function getRowCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnCount();
}
async function selectRow(rowStart: number, rowEnd: number): Promise<boolean> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
const endColumn = getColCount() - 1;
return commandService.executeCommand<ISetSelectionsOperationParams, boolean>(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
@@ -131,7 +131,7 @@ describe('Test row col menu items', () => {
async function selectColumn(columnStart: number, columnEnd: number): Promise<boolean> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
const endRow = getRowCount() - 1;
return commandService.executeCommand<ISetSelectionsOperationParams, boolean>(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
@@ -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<Workbook>(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<Workbook>(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<Workbook>(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<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
return true;
}
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
@@ -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);
@@ -60,6 +60,10 @@ export class SheetPermissionInterceptorClipboardController extends Disposable {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
return false;
}
const { startRow, endRow, startColumn, endColumn } = targetRange;
let hasPermission = true;
@@ -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<ICurrentEditCellParam>(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(),
};
}
@@ -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;
}
@@ -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(),
@@ -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,
@@ -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;
}
@@ -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;
@@ -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);
@@ -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();
@@ -275,7 +275,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
source,
target,
unitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId(),
subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId(),
subUnitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId(),
} = this.autoFillLocation || {};
const direction = this.direction;
if (!source || !target || unitId !== triggerUnitId || subUnitId !== triggerSubUnitId) {
@@ -104,6 +104,14 @@ export class SheetCanvasPopManagerService extends Disposable {
attachPopupToObject(targetObject: BaseObject, popup: ICanvasPopup): IDisposable {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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<IDisposable> {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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({
@@ -159,6 +159,9 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(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<boolean> {
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<ICellDataWithSpanInfo>) {
const target = this._getPastingTarget();
const { selection, unitId, subUnitId } = target;
if (!selection) {
if (!subUnitId || !selection) {
return null;
}
const accessor = {
@@ -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();
@@ -213,6 +213,8 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) return;
const location = {
workbook,
worksheet,
@@ -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();
@@ -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<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const currentSubUnitId = this._currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getSheetId();
const currentSubUnitId = this._currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
this._shapeMap.forEach((shape) => {
const { unitId, subUnitId, selection, control: oldControl, zIndex } = shape;
@@ -199,7 +199,7 @@ describe('Test indirect', () => {
const workbook = testBed.sheet;
const worksheet = workbook?.getActiveSheet();
const worksheet = workbook?.getActiveSheet()!;
const config = worksheet.getConfig();
@@ -36,7 +36,8 @@ export function ZoomSlider() {
const univerInstanceService = useDependency(IUniverInstanceService);
const getCurrentZoom = useCallback(() => {
const currentZoom = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet().getZoomRatio() * 100 || 100;
const worksheet = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();
const currentZoom = (worksheet && (worksheet.getZoomRatio() * 100)) || 100;
return Math.round(currentZoom);
}, [univerInstanceService]);
@@ -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) {
@@ -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);
@@ -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;
@@ -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;
@@ -45,6 +45,10 @@ export const SheetPermissionDialog = () => {
const permissionService = useDependency(IPermissionService);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
throw new Error('No active sheet found');
}
const [collaborators, setCollaborators] = useState<ICollaborator[]>([]);
const commandService = useDependency(ICommandService);
const [loading, setLoading] = useState(() => {
@@ -108,6 +112,9 @@ export const SheetPermissionDialog = () => {
const handleChangeActionPermission = async () => {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(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);
@@ -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<Workbook>(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;
@@ -144,14 +144,14 @@ describe('Test insert and remove rows cols commands', () => {
function getRowCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(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<ICellData> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getCellMatrix().getValue(row, col);
}
function getMergedInfo(row: number, col: number): Nullable<IRange> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getMergeData();
}
@@ -139,14 +139,14 @@ describe('Test move range commands', () => {
function getMergedInfo(row: number, col: number): Nullable<IRange> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getConfig().mergeData;
}
});
@@ -121,42 +121,42 @@ describe('Test move rows cols', () => {
function getRowCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnCount();
}
function getCellInfo(row: number, col: number): Nullable<ICellData> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getCellMatrix().getValue(row, col);
}
function getMergedInfo(row: number, col: number): Nullable<IRange> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnWidth(col);
}
@@ -94,14 +94,14 @@ describe('Test remove rows cols', () => {
function getColCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnCount();
}
function getCellInfo(row: number, col: number): Nullable<ICellData> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getCellMatrix().getValue(row, col);
}
@@ -31,7 +31,7 @@ describe('Test set col width commands', () => {
let commandService: ICommandService;
function getColumnWidth(col: number): number {
const worksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();
const worksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();
const worksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;
const maxRow = worksheet.getMaxRows() - 1;
const selectionManagerService = get(SelectionManagerService);
selectionManagerService.setCurrentSelection({
@@ -111,7 +111,7 @@ describe('Test set frozen commands', () => {
const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(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(
@@ -76,26 +76,26 @@ describe('Test row col hide/unhine commands', () => {
function getRowCount(): number {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColumnCount();
}
function getRowRawVisible(row: number): boolean {
const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(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<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
const worksheet = workbook.getActiveSheet()!;
return worksheet.getColVisible(col);
}

Some files were not shown because too many files have changed in this diff Show More