Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-drawing): preserve valid lines and isolate drawing activation errors (#7873)

siam4e110cf46b74
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts
index 2fabd63990..307f37fc8e 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts
@@ -17,7 +17,18 @@
import type { Workbook } from '@univerjs/core';
import type { IRenderContext } from '@univerjs/engine-render';
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
-import { DrawingTypeEnum, ImageSourceType, RedoCommandId, Tools, UndoCommandId } from '@univerjs/core';
+import {
+ BooleanNumber,
+ Disposable,
+ DrawingTypeEnum,
+ ILogService,
+ ImageSourceType,
+ IUndoRedoService,
+ LogLevel,
+ RedoCommandId,
+ Tools,
+ UndoCommandId,
+} from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { RemoveColByRangeCommand, RemoveRowByRangeCommand, SheetSkeletonService } from '@univerjs/sheets';
import {
@@ -26,6 +37,7 @@ import {
getSheetDrawingPlacement,
InsertSheetDrawingCommand,
ISheetDrawingService,
+ SetSheetDrawingPlacementCommand,
SheetDrawingAnchorType,
} from '@univerjs/sheets-drawing';
import { BehaviorSubject } from 'rxjs';
@@ -76,6 +88,143 @@ describe('SheetDrawingActiveRenderController', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
+ it.each([SheetDrawingAnchorType.Position, SheetDrawingAnchorType.Both])(
+ 'isolates failed geometry and retries repaired drawings on activation (%s)',
+ async (anchorType) => {
+ const bed = createTestBed();
+ const subscriptions = new Disposable();
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const base = await insertDrawing(bed, anchorType);
+ const sheetService = bed.get(ISheetDrawingService);
+ const manager = bed.get(IDrawingManagerService);
+ bed.get(ILogService).setLogLevel(LogLevel.ERROR);
+ const valid = { ...base, drawingId: 'before', transform: { ...base.transform, left: -100, top: -100 } };
+ const invalid = {
+ ...base,
+ drawingId: 'invalid',
+ transform: { ...base.transform, width: -1 },
+ sheetTransform: { ...base.sheetTransform, to: { ...base.sheetTransform.from, columnOffset: -2 } },
+ };
+ const secondInvalid = { ...invalid, drawingId: 'second-invalid' };
+ const last = { ...valid, drawingId: 'after' };
+ const drawings = [valid, invalid, secondInvalid, last];
+ const snapshot = {
+ [bed.subUnitId]: {
+ data: Object.fromEntries(drawings.map((drawing) => [drawing.drawingId, drawing])),
+ order: drawings.map((drawing) => drawing.drawingId),
+ },
+ };
+ sheetService.registerDrawingData(bed.unitId, Tools.deepClone(snapshot));
+ manager.registerDrawingData(bed.unitId, Tools.deepClone(snapshot));
+ const beforeHistory = bed.get(IUndoRedoService).getUndoRedoStatus(bed.unitId);
+ const notifications = [sheetService, manager].map((service) => {
+ const added = vi.fn();
+ const removed = vi.fn();
+ subscriptions.disposeWithMe(service.add$.subscribe(added));
+ subscriptions.disposeWithMe(service.remove$.subscribe(removed));
+ return { added, removed };
+ });
+ bed.get(SheetDrawingActiveRenderController);
+ bed.activated$.next(true);
+ expect(() => vi.runOnlyPendingTimers()).not.toThrow();
+ for (const { added, removed } of notifications) {
+ expect(added.mock.calls.at(-1)![0].map((drawing: ISheetDrawing) => drawing.drawingId))
+ .toEqual([valid.drawingId, last.drawingId]);
+ expect(removed).toHaveBeenLastCalledWith([invalid, secondInvalid]);
+ }
+ for (const drawing of drawings) {
+ expect(manager.getDrawingByParam(drawing)).toEqual(sheetService.getDrawingByParam(drawing));
+ }
+ for (const drawing of [valid, last]) {
+ expect(sheetService.getDrawingByParam(drawing)?.transform).toMatchObject({
+ left: base.transform!.left,
+ top: base.transform!.top,
+ });
+ }
+ expect(sheetService.getDrawingByParam(invalid)).toEqual(invalid);
+ expect(sheetService.getDrawingByParam(secondInvalid)).toEqual(secondInvalid);
+ expect(bed.get(IUndoRedoService).getUndoRedoStatus(bed.unitId)).toEqual(beforeHistory);
+ expect(logged).toHaveBeenCalledTimes(1);
+ expect(logged.mock.calls[0][1]).toMatchObject({
+ unitId: bed.unitId,
+ subUnitId: bed.subUnitId,
+ failures: [invalid, secondInvalid].map(({ drawingId, drawingType }) => ({
+ drawingId,
+ drawingType,
+ anchorType,
+ error: expect.objectContaining({
+ width: anchorType === SheetDrawingAnchorType.Both ? -2 : -1,
+ height: anchorType === SheetDrawingAnchorType.Both ? 0 : base.transform!.height,
+ }),
+ })),
+ });
+ expect(await bed.commandService.executeCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId: bed.unitId,
+ subUnitId: bed.subUnitId,
+ drawings: [invalid, secondInvalid].map(({ drawingId }) => ({
+ drawingId,
+ placement: getSheetDrawingPlacement(base),
+ })),
+ })).toBe(true);
+ bed.activated$.next(true);
+ vi.runOnlyPendingTimers();
+ for (const { added } of notifications) {
+ expect(added.mock.calls.at(-1)![0].map((drawing: ISheetDrawing) => drawing.drawingId))
+ .toEqual(drawings.map((drawing) => drawing.drawingId));
+ }
+ expect(logged).toHaveBeenCalledTimes(1);
+ } finally {
+ subscriptions.dispose();
+ logged.mockRestore();
+ bed.univer.dispose();
+ bed.activated$.complete();
+ }
+ }
+ );
+
+ it.each(['row', 'column'] as const)('reactivates an image after initially hidden %ss become visible', async (axis) => {
+ const bed = createTestBed();
+ const subscriptions = new Disposable();
+ try {
+ const drawing = await insertDrawing(bed, SheetDrawingAnchorType.Both);
+ const sheetService = bed.get(ISheetDrawingService);
+ const before = Tools.deepClone(sheetService.getDrawingByParam(drawing));
+ const worksheet = bed.workbook.getActiveSheet();
+ const data = axis === 'row' ? worksheet.getRowManager().getRowData() : worksheet.getColumnManager().getColumnData();
+ for (let index = 3; index < 6; index++) {
+ data[index] = { ...data[index], hd: BooleanNumber.TRUE };
+ }
+ const skeleton = bed.get(SheetSkeletonService).getSkeleton(bed.unitId, bed.subUnitId)!;
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ const added = vi.fn();
+ const removed = vi.fn();
+ subscriptions.disposeWithMe(sheetService.add$.subscribe(added));
+ subscriptions.disposeWithMe(sheetService.remove$.subscribe(removed));
+ bed.get(SheetDrawingActiveRenderController);
+ bed.activated$.next(true);
+ expect(() => vi.runOnlyPendingTimers()).not.toThrow();
+ expect(removed).toHaveBeenLastCalledWith([drawing]);
+ expect(added).toHaveBeenLastCalledWith([]);
+ expect(sheetService.getDrawingByParam(drawing)).toEqual(before);
+ for (let index = 3; index < 6; index++) {
+ data[index]!.hd = BooleanNumber.FALSE;
+ }
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ bed.activated$.next(true);
+ vi.runOnlyPendingTimers();
+ expect(added.mock.calls.at(-1)![0]).toHaveLength(1);
+ expect(sheetService.getDrawingByParam(drawing)?.transform).toEqual(before!.transform);
+ expect(bed.get(IDrawingManagerService).getDrawingByParam(drawing)).toEqual(sheetService.getDrawingByParam(drawing));
+ } finally {
+ subscriptions.dispose();
+ bed.univer.dispose();
+ bed.activated$.complete();
+ }
+ });
+
it.each([
['row', SheetDrawingAnchorType.Both],
['column', SheetDrawingAnchorType.Both],
@@ -121,6 +270,75 @@ describe('SheetDrawingActiveRenderController', () => {
}
});
+ it.each([
+ [SheetDrawingAnchorType.Both, 0, 81.9],
+ [SheetDrawingAnchorType.Position, 0, 81.9],
+ [SheetDrawingAnchorType.None, 0, 81.9],
+ [SheetDrawingAnchorType.Both, 81.9, 0],
+ [SheetDrawingAnchorType.Position, 81.9, 0],
+ [SheetDrawingAnchorType.None, 81.9, 0],
+ ] as const)('reactivates a line and preserves movement undo/redo (%s, %s, %s)', async (anchorType, width, height) => {
+ const bed = createTestBed();
+ try {
+ const from = { row: 3, column: 3, rowOffset: 0, columnOffset: 0 };
+ const sheetTransform = { from, to: { ...from, rowOffset: height, columnOffset: width } };
+ const skeleton = bed.get(SheetSkeletonService).getSkeletonParam(bed.unitId, bed.subUnitId);
+ const drawing: ISheetDrawing = {
+ unitId: bed.unitId,
+ subUnitId: bed.subUnitId,
+ drawingId: 'line',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ anchorType,
+ sheetTransform,
+ axisAlignSheetTransform: sheetTransform,
+ transform: drawingPositionToTransform(sheetTransform, skeleton),
+ };
+ expect(await bed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: bed.unitId,
+ drawings: [drawing],
+ })).toBe(true);
+ bed.get(SheetDrawingActiveRenderController);
+ const sheetService = bed.get(ISheetDrawingService);
+ const manager = bed.get(IDrawingManagerService);
+ manager.registerDrawingData(bed.unitId, Tools.deepClone(sheetService.getDrawingDataForUnit(bed.unitId)));
+ const reactivate = () => {
+ bed.activated$.next(false);
+ vi.runOnlyPendingTimers();
+ bed.activated$.next(true);
+ vi.runOnlyPendingTimers();
+ const current = Tools.deepClone(sheetService.getDrawingByParam(drawing)!);
+ expect(current.transform).toMatchObject({ width, height });
+ expect(manager.getDrawingByParam(drawing)).toEqual(current);
+ return current;
+ };
+ const before = reactivate();
+ expect(reactivate()).toEqual(before);
+ expect(await bed.commandService.executeCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId: bed.unitId,
+ subUnitId: bed.subUnitId,
+ drawings: [{ drawingId: drawing.drawingId, placement: {
+ kind: anchorType,
+ bounds: {
+ left: before.transform!.left! + 10,
+ top: before.transform!.top! + 10,
+ width,
+ height,
+ },
+ } }],
+ })).toBe(true);
+ const after = reactivate();
+ expect(after.transform!.left).toBeCloseTo(before.transform!.left! + 10);
+ expect(after.transform!.top).toBeCloseTo(before.transform!.top! + 10);
+ expect(bed.commandService.syncExecuteCommand(UndoCommandId)).toBe(true);
+ expect(reactivate()).toEqual(before);
+ expect(bed.commandService.syncExecuteCommand(RedoCommandId)).toBe(true);
+ expect(reactivate()).toEqual(after);
+ } finally {
+ bed.univer.dispose();
+ bed.activated$.complete();
+ }
+ });
+
it.each([SheetDrawingAnchorType.None, undefined])('activates absolute or legacy cell-anchored geometry (%s)', async (anchorType) => {
const bed = createTestBed();
try {
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts
index eab86b149d..8d630b205c 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts
@@ -15,10 +15,10 @@
*/
import type { ICommandInfo, IDrawingParam, Workbook } from '@univerjs/core';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { ISetWorksheetActiveOperationParams } from '@univerjs/sheets';
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
-import { Disposable, ICommandService, Inject } from '@univerjs/core';
+import { Disposable, ICommandService, ILogService, Inject } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { SetWorksheetActiveOperation, SheetSkeletonService } from '@univerjs/sheets';
import {
@@ -36,7 +36,8 @@ export class SheetDrawingActiveRenderController extends Disposable implements IR
@ICommandService private readonly _commandService: ICommandService,
@Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService,
@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
- @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @ILogService private readonly _logService: ILogService
) {
super();
this._commandListener();
@@ -109,44 +110,60 @@ export class SheetDrawingActiveRenderController extends Disposable implements IR
private _updateDrawings(showUnitId: string, showSubunitId: string): void {
this._scheduleRender(() => {
const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(showUnitId, showSubunitId);
- const drawingMap = this._drawingManagerService.drawingManagerData;
- const insertDrawings: IDrawingParam[] = [];
- const refreshedDrawings: ISheetDrawing[] = [];
- const removeDrawings: IDrawingParam[] = [];
-
- Object.keys(drawingMap ?? {}).forEach((unitId) => {
- if (unitId !== showUnitId) {
- return;
+ const subUnitMap = this._drawingManagerService.drawingManagerData[showUnitId] ?? {};
+ const drawingData = subUnitMap[showSubunitId]?.data ?? {};
+ const { successDrawings, refreshedDrawings, failures } = prepareSheetDrawings(
+ Object.values(drawingData) as ISheetDrawing[],
+ sheetSkeletonParam?.skeleton
+ );
+ const removeDrawings: IDrawingParam[] = failures.map(({ drawingId }) => drawingData[drawingId]);
+ for (const subUnitId of Object.keys(subUnitMap)) {
+ if (subUnitId !== showSubunitId) {
+ for (const drawing of Object.values(subUnitMap[subUnitId]?.data ?? {})) {
+ removeDrawings.push(drawing);
+ }
}
-
- const subUnitMap = drawingMap[unitId] ?? {};
- Object.keys(subUnitMap).forEach((subUnitId) => {
- const drawingData = subUnitMap[subUnitId]?.data ?? {};
- Object.keys(drawingData).forEach((drawingId) => {
- if (unitId === showUnitId && subUnitId === showSubunitId) {
- const drawing = drawingData[drawingId] as ISheetDrawing;
- if (sheetSkeletonParam && drawing.sheetTransform && drawing.anchorType !== SheetDrawingAnchorType.None) {
- refreshedDrawings.push(applySheetDrawingPlacement(
- drawing,
- getSheetDrawingPlacement(drawing),
- sheetSkeletonParam.skeleton
- ));
- }
- insertDrawings.push(drawingData[drawingId]);
- } else {
- removeDrawings.push(drawingData[drawingId]);
- }
- });
- });
- });
+ }
// JSON1 drawing mutations are applied to both stores, so derived geometry must agree.
this._sheetDrawingService.refreshTransform(refreshedDrawings);
this._drawingManagerService.refreshTransform(refreshedDrawings);
this._sheetDrawingService.removeNotification(removeDrawings);
- this._sheetDrawingService.addNotification(insertDrawings);
+ this._sheetDrawingService.addNotification(successDrawings);
this._drawingManagerService.removeNotification(removeDrawings);
- this._drawingManagerService.addNotification(insertDrawings);
+ this._drawingManagerService.addNotification(successDrawings);
+ if (failures.length) {
+ this._logService.error('[SheetDrawingActiveRenderController]', {
+ unitId: showUnitId,
+ subUnitId: showSubunitId,
+ failures,
+ });
+ }
});
}
}
+
+function prepareSheetDrawings(drawings: ISheetDrawing[], skeleton?: SpreadsheetSkeleton) {
+ const successDrawings: ISheetDrawing[] = [];
+ const refreshedDrawings: ISheetDrawing[] = [];
+ const failures: Array<Pick<ISheetDrawing, 'drawingId' | 'drawingType' | 'anchorType'> & { error: unknown }> = [];
+
+ for (const drawing of drawings) {
+ if (skeleton && drawing.sheetTransform && drawing.anchorType !== SheetDrawingAnchorType.None) {
+ try {
+ refreshedDrawings.push(applySheetDrawingPlacement(drawing, getSheetDrawingPlacement(drawing), skeleton));
+ } catch (error) {
+ failures.push({
+ drawingId: drawing.drawingId,
+ drawingType: drawing.drawingType,
+ anchorType: drawing.anchorType ?? SheetDrawingAnchorType.Position,
+ error,
+ });
+ continue;
+ }
+ }
+ successDrawings.push(drawing);
+ }
+
+ return { successDrawings, refreshedDrawings, failures };
+}
diff --git a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
index c75a71cdf3..69681b3be8 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
@@ -349,7 +349,7 @@ describe('FWorksheetDrawingMixin group drawings', () => {
expect(() => fWorksheet.setDrawingPlacement(drawing.drawingId, {
kind: SheetDrawingAnchorType.Position,
- bounds: { left: 120, top: 80, width: 0, height: 160 },
+ bounds: { left: 120, top: 80, width: -1, height: 160 },
})).toThrow('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
expect(() => fWorksheet.setDrawingPlacement(drawing.drawingId, {
kind: SheetDrawingAnchorType.Both,
diff --git a/packages/sheets-drawing/src/services/__tests__/sheet-drawing-placement.spec.ts b/packages/sheets-drawing/src/services/__tests__/sheet-drawing-placement.spec.ts
new file mode 100644
index 0000000000..f157664089
--- /dev/null
+++ b/packages/sheets-drawing/src/services/__tests__/sheet-drawing-placement.spec.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISheetDrawingPlacement } from '../sheet-drawing-placement';
+import type { ISheetDrawing } from '../sheet-drawing.service';
+import { DrawingTypeEnum } from '@univerjs/core';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';
+import { applySheetDrawingPlacement, normalizeSheetDrawingPlacement } from '../sheet-drawing-placement';
+import { SheetDrawingAnchorType } from '../sheet-drawing.service';
+
+describe('sheet drawing placement extents', () => {
+ let bed: ReturnType<typeof createSheetsDrawingTestBed>;
+ beforeEach(() => {
+ bed = createSheetsDrawingTestBed();
+ });
+ afterEach(() => bed.univer.dispose());
+
+ it.each([
+ [0, 81.9],
+ [81.9, 0],
+ ])('preserves a line bounding box of %s by %s in every anchor mode', (width, height) => {
+ const skeleton = bed.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1')!;
+ const from = { row: 2, column: 2, rowOffset: 0, columnOffset: 0 };
+ const to = { ...from, rowOffset: height, columnOffset: width };
+ const drawing: ISheetDrawing = {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'line',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ sheetTransform: { from, to },
+ axisAlignSheetTransform: { from, to },
+ transform: { left: 200, top: 100, width, height },
+ };
+ const placements: ISheetDrawingPlacement[] = [
+ { kind: SheetDrawingAnchorType.None, left: 200, top: 100, width, height },
+ { kind: SheetDrawingAnchorType.Position, from, width, height },
+ { kind: SheetDrawingAnchorType.Both, from, to },
+ ];
+ for (const placement of placements) {
+ const result = applySheetDrawingPlacement(drawing, placement, skeleton);
+ expect(result.transform).toMatchObject({ width, height });
+ expect(result.anchorType).toBe(placement.kind);
+ for (const drawingType of [DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_DOM]) {
+ expect(() => applySheetDrawingPlacement({ ...drawing, drawingType }, placement, skeleton))
+ .toThrow('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
+ }
+ }
+ });
+
+ it.each([[0, 0], [-1, 20], [20, -1], [NaN, 20], [20, Infinity]])(
+ 'rejects an invalid extent of %s by %s',
+ (width, height) => {
+ expect(() => normalizeSheetDrawingPlacement({
+ kind: SheetDrawingAnchorType.None,
+ left: 0,
+ top: 0,
+ width,
+ height,
+ })).toThrow('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
+ }
+ );
+});
diff --git a/packages/sheets-drawing/src/services/sheet-drawing-placement.ts b/packages/sheets-drawing/src/services/sheet-drawing-placement.ts
index 984dd101d4..1076aca8a4 100644
--- a/packages/sheets-drawing/src/services/sheet-drawing-placement.ts
+++ b/packages/sheets-drawing/src/services/sheet-drawing-placement.ts
@@ -17,14 +17,14 @@
import type { IGroupBaseBound, ITransformState } from '@univerjs/core';
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { ICellOverGridPosition } from '@univerjs/sheets';
-import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute } from '@univerjs/sheets';
-
import type {
ISheetDrawing,
ISheetDrawingPosition,
ISheetFloatDom,
ISheetImage,
} from './sheet-drawing.service';
+import { DrawingTypeEnum } from '@univerjs/core';
+import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute } from '@univerjs/sheets';
import { transformToAxisAlignPosition, transformToDrawingPosition } from '../basics/transform-position';
import {
SheetDrawingAnchorType,
@@ -144,7 +144,9 @@ export function applySheetDrawingPlacement(
input: ISheetDrawingPlacementInput,
skeleton?: SpreadsheetSkeleton
): ISheetDrawing {
- const placement = normalizeSheetDrawingPlacement(input, skeleton);
+ const requiresArea = drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE
+ || drawing.drawingType === DrawingTypeEnum.DRAWING_DOM;
+ const placement = normalizePlacement(input, skeleton, requiresArea);
if (placement.kind === SheetDrawingAnchorType.None) {
const transform = withExistingTransform(drawing.transform, placement);
@@ -209,9 +211,17 @@ export function applySheetDrawingPlacement(
export function normalizeSheetDrawingPlacement(
input: ISheetDrawingPlacementInput,
skeleton?: SpreadsheetSkeleton
+): ISheetDrawingPlacement {
+ return normalizePlacement(input, skeleton, false);
+}
+
+function normalizePlacement(
+ input: ISheetDrawingPlacementInput,
+ skeleton: SpreadsheetSkeleton | undefined,
+ requiresArea: boolean
): ISheetDrawingPlacement {
if (!('bounds' in input)) {
- validatePlacement(input);
+ validatePlacement(input, requiresArea);
if (input.kind === SheetDrawingAnchorType.Both && skeleton) {
validateBounds(convertPositionSheetOverGridToAbsolute(
skeleton.worksheet.getUnitId(),
@@ -221,12 +231,12 @@ export function normalizeSheetDrawingPlacement(
to: input.to,
},
skeleton
- ));
+ ), requiresArea);
}
return input;
}
- validateBounds(input.bounds);
+ validateBounds(input.bounds, requiresArea);
if (input.kind === SheetDrawingAnchorType.None) {
return {
kind: SheetDrawingAnchorType.None,
@@ -302,10 +312,10 @@ function absoluteSheetTransform(
};
}
-function validatePlacement(placement: ISheetDrawingPlacement): void {
+function validatePlacement(placement: ISheetDrawingPlacement, requiresArea: boolean): void {
if (placement.kind === SheetDrawingAnchorType.Position) {
validateCellPosition(placement.from);
- validateExtent(placement.width, placement.height);
+ validateExtent(placement.width, placement.height, requiresArea);
return;
}
@@ -319,18 +329,18 @@ function validatePlacement(placement: ISheetDrawingPlacement): void {
if (!Number.isFinite(placement.left) || !Number.isFinite(placement.top)) {
throw new TypeError('SHEET_DRAWING_PLACEMENT_POSITION_INVALID');
}
- validateExtent(placement.width, placement.height);
+ validateExtent(placement.width, placement.height, requiresArea);
return;
}
throw new Error('SHEET_DRAWING_PLACEMENT_KIND_INVALID');
}
-function validateBounds(bounds: IGroupBaseBound): void {
+function validateBounds(bounds: IGroupBaseBound, requiresArea: boolean): void {
if (!Number.isFinite(bounds.left) || !Number.isFinite(bounds.top)) {
throw new TypeError('SHEET_DRAWING_PLACEMENT_POSITION_INVALID');
}
- validateExtent(bounds.width, bounds.height);
+ validateExtent(bounds.width, bounds.height, requiresArea);
}
function validateCellPosition(position: ICellOverGridPosition): void {
@@ -346,8 +356,12 @@ function validateCellPosition(position: ICellOverGridPosition): void {
}
}
-function validateExtent(width: number, height: number): void {
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
- throw new Error('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
+function validateExtent(width: number, height: number, requiresArea: boolean): void {
+ // Horizontal and vertical lines have a zero bounding-box extent on one axis;
+ // this is independent of stroke width. Images and floating DOM still require area.
+ const hasInvalidZeroExtent = requiresArea ? width === 0 || height === 0 : width === 0 && height === 0;
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width < 0 || height < 0 || hasInvalidZeroExtent) {
+ // Preserve the error message contract and report the actual checked extent, including converted cell bounds.
+ throw Object.assign(new Error('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID'), { width, height });
}
}