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.

feat(sheets-drawing): complete anchor placement API (#7379)

Univere9b3c28a1f83
diff --git a/packages/docs/src/facade/__tests__/f-document.node.spec.ts b/packages/docs/src/facade/__tests__/f-document.node.spec.ts
index 7174c05ad7..f4e8718f7d 100644
--- a/packages/docs/src/facade/__tests__/f-document.node.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.node.spec.ts
@@ -17,7 +17,7 @@
// @vitest-environment node
import type { Univer } from '@univerjs/core';
-import { ColumnSeparatorType, DocumentFlavor, PageOrientType, SectionType } from '@univerjs/core';
+import { ColumnSeparatorType, DataStreamTreeTokenType, DocumentFlavor, PageOrientType, SectionType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
import { createDocumentData, createTestBed } from './create-test-bed';
@@ -91,4 +91,18 @@ describe('FDocument in Node', () => {
properties: { docxBreakType: 'column' },
}));
});
+
+ it('reads custom block structure without rendering or pixel layout', () => {
+ const data = createDocumentData('node-custom-block-layout', {
+ dataStream: `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B\r\n`,
+ customBlocks: [{ blockId: 'embed-block', startIndex: 1 }],
+ });
+ const testBed = createTestBed(data);
+ univer = testBed.univer;
+
+ expect(globalThis).not.toHaveProperty('window');
+ expect(testBed.univerAPI.getActiveDocument()?.getCustomBlockLayout()).toEqual({
+ blocks: [{ blockId: 'embed-block', startIndex: 1, index: 0 }],
+ });
+ });
});
diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.ts
index 538356e15d..2cb3655316 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -46,6 +46,21 @@ export interface IFDocumentParagraphQuery {
segmentId?: string;
}
+export interface IDocumentCustomBlockLayoutItem {
+ blockId: string;
+ startIndex: number;
+ index: number;
+}
+
+/**
+ * Structural custom-block layout from the document model.
+ *
+ * This intentionally excludes rendered pixel positions and pagination.
+ */
+export interface IDocumentCustomBlockLayout {
+ blocks: IDocumentCustomBlockLayoutItem[];
+}
+
/**
* Options for inserting a section break in a traditional document.
*
@@ -102,6 +117,31 @@ export class FDocument extends FBaseInitialable {
return documentDataModel;
}
+ /**
+ * Returns the document's custom blocks in stable model order.
+ *
+ * This method is available in Node/headless environments and does not
+ * perform font measurement, line wrapping, pagination, or rendering.
+ *
+ * @returns {IDocumentCustomBlockLayout} Custom block identifiers and model positions.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * const layout = document?.getCustomBlockLayout();
+ * console.log(layout?.blocks);
+ * ```
+ */
+ getCustomBlockLayout(): IDocumentCustomBlockLayout {
+ const blocks = this._documentDataModel.getBody()?.customBlocks ?? [];
+ return {
+ blocks: blocks.map(({ blockId, startIndex }, index) => ({
+ blockId,
+ startIndex,
+ index,
+ })),
+ };
+ }
+
/**
* Get the document body or header/footer body by the segment id.
* The main body has an empty segment id.
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index c20c47f214..f41ef86fca 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -17,7 +17,11 @@
import './f-univer';
import './f-enum';
-export { FDocument } from './f-document';
+export {
+ FDocument,
+ type IDocumentCustomBlockLayout,
+ type IDocumentCustomBlockLayoutItem,
+} from './f-document';
export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
export type { IFDocumentFindTextOptions, IFDocumentParagraphInfo } from './f-document-paragraph';
export { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts
index c7f9b21cc4..5f843bfe2c 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts
@@ -15,7 +15,7 @@
*/
import { ObjectType } from '@univerjs/engine-render';
-import { InsertSheetDrawingCommand, SetDrawingArrangeCommand } from '@univerjs/sheets-drawing';
+import { InsertSheetDrawingCommand, SetDrawingArrangeCommand, SetSheetDrawingPlacementCommand } from '@univerjs/sheets-drawing';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { SheetDrawingPermissionController } from '../sheet-drawing-permission.controller';
@@ -151,8 +151,16 @@ describe('SheetDrawingPermissionController', () => {
subUnitId: 'sheet-1',
},
});
+ beforeCommandHandler()?.({
+ id: SetSheetDrawingPlacementCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawings: [],
+ },
+ });
- expect(sheetPermissionCheckController.permissionCheckWithoutRange).toHaveBeenCalledTimes(2);
+ expect(sheetPermissionCheckController.permissionCheckWithoutRange).toHaveBeenCalledTimes(3);
expect(sheetPermissionCheckController.blockExecuteWithoutPermission).toHaveBeenCalledWith('sheets-drawing-ui.permission.dialog.editErr');
controller.dispose();
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-permission.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-permission.controller.ts
index cfd6bb2034..dbaaff7beb 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-permission.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-permission.controller.ts
@@ -46,6 +46,7 @@ import {
RemoveSheetDrawingCommand,
SetDrawingArrangeCommand,
SetSheetDrawingCommand,
+ SetSheetDrawingPlacementCommand,
} from '@univerjs/sheets-drawing';
import { combineLatest, distinctUntilChanged, EMPTY, map, switchMap, tap } from 'rxjs';
@@ -442,6 +443,10 @@ export class SheetDrawingPermissionController extends Disposable {
const { drawings } = params;
unitId = drawings?.[0]?.unitId;
subUnitId = drawings?.[0]?.subUnitId;
+ } else if (command.id === SetSheetDrawingPlacementCommand.id) {
+ const target = getPlacementCommandTarget(command.params);
+ unitId = target.unitId;
+ subUnitId = target.subUnitId;
} else if (command.id === SetDrawingArrangeCommand.id) {
const params = command.params as ISetDrawingArrangeCommandParams;
unitId = params.unitId;
@@ -463,3 +468,20 @@ export class SheetDrawingPermissionController extends Disposable {
);
}
}
+
+function getPlacementCommandTarget(params: object | undefined): {
+ unitId?: string;
+ subUnitId?: string;
+} {
+ if (!params) {
+ return {};
+ }
+
+ const unitId = 'unitId' in params && typeof params.unitId === 'string'
+ ? params.unitId
+ : undefined;
+ const subUnitId = 'subUnitId' in params && typeof params.subUnitId === 'string'
+ ? params.subUnitId
+ : undefined;
+ return { unitId, subUnitId };
+}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
index 98664f0ee0..f02caf019a 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
@@ -16,13 +16,20 @@
import type { IDrawingParam, Nullable } from '@univerjs/core';
import type { BaseObject } from '@univerjs/engine-render';
-import type { ISheetDrawing } from '@univerjs/sheets-drawing';
+import type {
+ ISheetDrawing,
+ ISheetDrawingPlacementInput,
+} from '@univerjs/sheets-drawing';
import type { LocaleKey } from '../../locale/types';
import { ICommandService, LocaleService } from '@univerjs/core';
import { clsx, Radio, RadioGroup } from '@univerjs/design';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SetSheetDrawingCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import {
+ getSheetDrawingPlacement,
+ SetSheetDrawingPlacementCommand,
+ SheetDrawingAnchorType,
+} from '@univerjs/sheets-drawing';
import { useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
@@ -38,14 +45,16 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
const { drawings } = props;
- const drawingParam = drawings[0] as ISheetDrawing | undefined;
+ const drawingParam = isSheetDrawing(drawings[0]) ? drawings[0] : undefined;
const renderObject = drawingParam ? renderManagerService.getRenderUnitById(drawingParam.unitId) : undefined;
const scene = renderObject?.scene;
const transformer = scene?.getTransformerByCreate();
const [anchorShow, setAnchorShow] = useState(true);
- const type = drawingParam?.anchorType ?? SheetDrawingAnchorType.Position;
+ const type = drawingParam
+ ? getSheetDrawingPlacement(drawingParam).kind
+ : SheetDrawingAnchorType.Position;
const [value, setValue] = useState(type);
function getUpdateParams(objects: Map<string, BaseObject>, drawingManagerService: IDrawingManagerService): Nullable<ISheetDrawing>[] {
@@ -60,7 +69,12 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
return true;
}
- const { unitId, subUnitId, drawingId, drawingType, anchorType, sheetTransform, axisAlignSheetTransform } = searchParam as ISheetDrawing;
+ if (!isSheetDrawing(searchParam)) {
+ params.push(null);
+ return true;
+ }
+
+ const { unitId, subUnitId, drawingId, drawingType, anchorType, sheetTransform, axisAlignSheetTransform } = searchParam;
params.push({
unitId,
@@ -95,8 +109,10 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
setAnchorShow(false);
} else if (params.length >= 1) {
setAnchorShow(true);
- const anchorType = params[0]?.anchorType || SheetDrawingAnchorType.Position;
- setValue(anchorType);
+ const drawing = params[0];
+ setValue(drawing
+ ? getSheetDrawingPlacement(drawing).kind
+ : SheetDrawingAnchorType.Position);
}
});
@@ -111,26 +127,55 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
}
function handleChange(value: string | number | boolean) {
- setValue((value as SheetDrawingAnchorType));
+ const kind = getAnchorKind(value);
+ if (!kind) {
+ return;
+ }
const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
+ if (!focusDrawings.length || !focusDrawings.every(isSheetDrawing)) {
return;
}
- const updateParams = focusDrawings.map((drawing) => {
- return {
- unitId: drawing.unitId,
- subUnitId: drawing.subUnitId,
+ const { unitId, subUnitId } = focusDrawings[0];
+ const placementUpdates: Array<{ drawingId: string; placement: ISheetDrawingPlacementInput }> = [];
+ for (const drawing of focusDrawings) {
+ const { transform } = drawing;
+ const { left, top, width, height } = transform ?? {};
+ if (
+ typeof left !== 'number' ||
+ typeof top !== 'number' ||
+ typeof width !== 'number' ||
+ typeof height !== 'number' ||
+ !Number.isFinite(left) ||
+ !Number.isFinite(top) ||
+ !Number.isFinite(width) ||
+ !Number.isFinite(height)
+ ) {
+ return;
+ }
+ placementUpdates.push({
drawingId: drawing.drawingId,
- anchorType: value,
- };
- });
+ placement: {
+ kind,
+ bounds: {
+ left,
+ top,
+ width,
+ height,
+ },
+ },
+ });
+ }
- commandService.executeCommand(SetSheetDrawingCommand.id, {
- unitId: focusDrawings[0].unitId,
- drawings: updateParams,
+ const changed = commandService.syncExecuteCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId,
+ subUnitId,
+ drawings: placementUpdates,
});
+ if (changed) {
+ setValue(kind);
+ }
}
return (
@@ -158,3 +203,18 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
</div>
);
};
+
+function isSheetDrawing(drawing: IDrawingParam | undefined): drawing is ISheetDrawing {
+ return Boolean(drawing && 'sheetTransform' in drawing && 'axisAlignSheetTransform' in drawing);
+}
+
+function getAnchorKind(value: string | number | boolean): SheetDrawingAnchorType | null {
+ if (
+ value === SheetDrawingAnchorType.Position ||
+ value === SheetDrawingAnchorType.Both ||
+ value === SheetDrawingAnchorType.None
+ ) {
+ return value;
+ }
+ return null;
+}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
index afa1f6bc17..37b74ad701 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
@@ -16,10 +16,11 @@
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
import type { Root } from 'react-dom/client';
-import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import { DrawingTypeEnum, ImageSourceType, RedoCommand, UndoCommand } from '@univerjs/core';
import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType, transformToDrawingPosition } from '@univerjs/sheets-drawing';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -30,12 +31,16 @@ import { SheetDrawingAnchor } from '../SheetDrawingAnchor';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-function createSheetDrawing(drawingId: string, anchorType: SheetDrawingAnchorType): ISheetDrawing {
+function createSheetDrawing(
+ drawingId: string,
+ anchorType: SheetDrawingAnchorType,
+ drawingType = DrawingTypeEnum.DRAWING_IMAGE
+): ISheetDrawing {
return {
unitId: 'test',
subUnitId: 'sheet1',
drawingId,
- drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ drawingType,
imageSourceType: ImageSourceType.URL,
source: `https://example.com/${drawingId}.png`,
anchorType,
@@ -82,11 +87,20 @@ class TestRenderManagerService {
clearControl$: this.clearControl$,
changeStart$: this.changeStart$,
}),
+ getTransformer: () => ({
+ debounceRefreshControls: () => undefined,
+ }),
},
};
}
}
+function createTestBed() {
+ return createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService }],
+ ]);
+}
+
describe('SheetDrawingAnchor', () => {
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -101,9 +115,7 @@ describe('SheetDrawingAnchor', () => {
});
it('updates every focused sheet image when the anchor mode changes', async () => {
- const testBed = createSheetsDrawingUiTestBed(undefined, [
- [IRenderManagerService, { useClass: TestRenderManagerService as never }],
- ]);
+ const testBed = createTestBed();
const sheetDrawingService = testBed.get(ISheetDrawingService);
const drawingManagerService = testBed.get(IDrawingManagerService);
const drawings = [
@@ -153,13 +165,101 @@ describe('SheetDrawingAnchor', () => {
SheetDrawingAnchorType.None,
]);
+ expect(await testBed.commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-a',
+ })?.anchorType).toBe(SheetDrawingAnchorType.Position);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-b',
+ })?.anchorType).toBe(SheetDrawingAnchorType.Both);
+ expect(await testBed.commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-a',
+ })?.anchorType).toBe(SheetDrawingAnchorType.None);
+
+ testBed.univer.dispose();
+ });
+
+ it('recomputes Shape cell markers when Absolute changes to OneCell and then TwoCell', async () => {
+ const testBed = createTestBed();
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ const drawingManagerService = testBed.get(IDrawingManagerService);
+ const drawing = createSheetDrawing(
+ 'absolute-drawing',
+ SheetDrawingAnchorType.None,
+ DrawingTypeEnum.DRAWING_SHAPE
+ );
+ drawing.transform = { ...drawing.transform, left: 320, top: 220 };
+
+ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings: [drawing],
+ });
+ const skeleton = testBed.get(SheetSkeletonService).ensureSkeleton(testBed.unitId, testBed.subUnitId);
+ const transform = sheetDrawingService.getDrawingByParam({
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ })?.transform;
+ if (!transform || !skeleton) {
+ throw new Error('Sheet drawing test fixture is incomplete.');
+ }
+ const expected = transformToDrawingPosition(transform, skeleton);
+ drawingManagerService.focusDrawing([{
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ }]);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ const mountedRoot = createRoot(container);
+ root = mountedRoot;
+ await act(async () => {
+ mountedRoot.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <SheetDrawingAnchor drawings={[drawing]} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const oneCellOption = container.querySelectorAll<HTMLInputElement>('input[type="radio"]')[1];
+ await act(async () => {
+ oneCellOption.click();
+ await Promise.resolve();
+ });
+
+ const updated = sheetDrawingService.getDrawingByParam({
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ });
+ expect(updated?.anchorType).toBe(SheetDrawingAnchorType.Position);
+ expect(updated?.sheetTransform.from).toEqual(expected.from);
+
+ const twoCellOption = container.querySelectorAll<HTMLInputElement>('input[type="radio"]')[0];
+ await act(async () => {
+ twoCellOption.click();
+ await Promise.resolve();
+ });
+ const resized = sheetDrawingService.getDrawingByParam({
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ });
+ expect(resized?.anchorType).toBe(SheetDrawingAnchorType.Both);
+ expect(resized?.sheetTransform).toEqual(expected);
testBed.univer.dispose();
});
it('hides anchor controls when the transformer clears the sheet image selection', async () => {
- const testBed = createSheetsDrawingUiTestBed(undefined, [
- [IRenderManagerService, { useClass: TestRenderManagerService as never }],
- ]);
+ const testBed = createTestBed();
const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
const drawings = [
createSheetDrawing('drawing-a', SheetDrawingAnchorType.Position),
@@ -191,9 +291,7 @@ describe('SheetDrawingAnchor', () => {
});
it('syncs the selected anchor mode when the transformer starts editing another sheet image', async () => {
- const testBed = createSheetsDrawingUiTestBed(undefined, [
- [IRenderManagerService, { useClass: TestRenderManagerService as never }],
- ]);
+ const testBed = createTestBed();
const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
const drawings = [
createSheetDrawing('drawing-a', SheetDrawingAnchorType.Both),
diff --git a/packages/sheets-drawing/src/commands/commands/set-sheet-drawing-placement.command.ts b/packages/sheets-drawing/src/commands/commands/set-sheet-drawing-placement.command.ts
new file mode 100644
index 0000000000..25ff303059
--- /dev/null
+++ b/packages/sheets-drawing/src/commands/commands/set-sheet-drawing-placement.command.ts
@@ -0,0 +1,89 @@
+/**
+ * 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 { ICommand } from '@univerjs/core';
+import type { ISheetDrawingPlacementInput } from '../../services/sheet-drawing-placement';
+import { CommandType, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { applySheetDrawingPlacement } from '../../services/sheet-drawing-placement';
+import { ISheetDrawingService, SheetDrawingAnchorType } from '../../services/sheet-drawing.service';
+import { DrawingApplyType, SetDrawingApplyMutation } from '../mutations/set-drawing-apply.mutation';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+
+export interface ISetSheetDrawingPlacementCommandParams {
+ unitId: string;
+ subUnitId: string;
+ drawings: Array<{
+ drawingId: string;
+ placement: ISheetDrawingPlacementInput;
+ }>;
+}
+
+export const SetSheetDrawingPlacementCommand: ICommand<ISetSheetDrawingPlacementCommandParams> = {
+ id: 'sheet.command.set-drawing-placement',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params?.drawings.length) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const drawingService = accessor.get(ISheetDrawingService);
+ const skeleton = params.drawings.every(({ placement }) => placement.kind === SheetDrawingAnchorType.None)
+ ? undefined
+ : accessor.get(SheetSkeletonService).ensureSkeleton(params.unitId, params.subUnitId);
+ const updatedDrawings = [];
+ for (const { drawingId, placement } of params.drawings) {
+ const drawing = drawingService.getDrawingByParam({
+ unitId: params.unitId,
+ subUnitId: params.subUnitId,
+ drawingId,
+ });
+ if (!drawing) {
+ return false;
+ }
+ updatedDrawings.push(applySheetDrawingPlacement(drawing, placement, skeleton));
+ }
+ const drawingOp = drawingService.getBatchUpdateOp(updatedDrawings);
+ const { unitId, subUnitId, undo, redo, objects } = drawingOp;
+ const redoMutations = [
+ {
+ id: SetDrawingApplyMutation.id,
+ params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE },
+ },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ];
+ const undoMutations = [
+ {
+ id: SetDrawingApplyMutation.id,
+ params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE },
+ },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ];
+ const result = sequenceExecute(redoMutations, commandService);
+ if (!result.result) {
+ return false;
+ }
+
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations,
+ redoMutations,
+ });
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts
index 85e5423eaf..285c781adb 100644
--- a/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts
+++ b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts
@@ -14,6 +14,9 @@
* limitations under the License.
*/
+import type {
+ ISheetDrawingPlacement,
+} from '../../services/sheet-drawing-placement';
import type { ISheetDrawing } from '../../services/sheet-drawing.service';
import { Direction, DrawingTypeEnum, ImageSourceType, RANGE_TYPE, RedoCommandId, UndoCommandId } from '@univerjs/core';
import {
@@ -39,6 +42,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';
import { drawingPositionToTransform } from '../../basics/transform-position';
import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';
+import { SetSheetDrawingPlacementCommand } from '../../commands/commands/set-sheet-drawing-placement.command';
+import {
+ applySheetDrawingPlacement,
+ getSheetDrawingPlacement,
+ normalizeSheetDrawingPlacement,
+} from '../../services/sheet-drawing-placement';
import { ISheetDrawingService, SheetDrawingAnchorType } from '../../services/sheet-drawing.service';
describe('sheet drawing transforms without UI plugins', () => {
@@ -98,6 +107,139 @@ describe('sheet drawing transforms without UI plugins', () => {
expect(getDrawing(service)).toEqual(after);
});
+ it.each([
+ ['insert row', InsertRowCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 },
+ direction: Direction.DOWN,
+ }],
+ ['delete row', RemoveRowCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 },
+ }],
+ ['insert column', InsertColCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: { startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 },
+ direction: Direction.RIGHT,
+ }],
+ ['delete column', RemoveColCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: { startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 },
+ }],
+ ['resize row', SetRowHeightCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ value: 60,
+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 }],
+ }],
+ ['resize column', SetColWidthCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ value: 120,
+ ranges: [{ startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 }],
+ }],
+ ['hide row', SetRowHiddenCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 }],
+ }],
+ ['hide column', SetColHiddenCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ranges: [{ startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 }],
+ }],
+ ])('%s preserves the three placement contracts in headless mode', async (_name, commandId, params) => {
+ const skeleton = testBed.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');
+ if (!skeleton) {
+ throw new Error('Expected the Sheet skeleton to exist.');
+ }
+ const base = {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.URL,
+ source: 'https://example.com/anchor.png',
+ sheetTransform: {
+ from: { row: 0, column: 0, rowOffset: 0, columnOffset: 0 },
+ to: { row: 0, column: 0, rowOffset: 1, columnOffset: 1 },
+ },
+ axisAlignSheetTransform: {
+ from: { row: 0, column: 0, rowOffset: 0, columnOffset: 0 },
+ to: { row: 0, column: 0, rowOffset: 1, columnOffset: 1 },
+ },
+ transform: { left: 0, top: 0, width: 1, height: 1 },
+ };
+ const placements: ISheetDrawingPlacement[] = [
+ {
+ kind: SheetDrawingAnchorType.Position,
+ from: { row: 3, column: 3, rowOffset: 4, columnOffset: 6 },
+ width: 240,
+ height: 120,
+ },
+ {
+ kind: SheetDrawingAnchorType.Both,
+ from: { row: 1, column: 1, rowOffset: 4, columnOffset: 6 },
+ to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ },
+ {
+ kind: SheetDrawingAnchorType.None,
+ left: 640,
+ top: 96,
+ width: 240,
+ height: 120,
+ },
+ ];
+ const drawings = placements.map((placement, index) => applySheetDrawingPlacement({
+ ...base,
+ drawingId: `placement-${index}`,
+ }, placement, placement.kind === SheetDrawingAnchorType.None ? undefined : skeleton));
+ expect(await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings,
+ })).toBe(true);
+
+ const service = testBed.get(ISheetDrawingService);
+ const readDrawings = () => drawings.map((drawing) => {
+ const current = service.getDrawingByParam(drawing);
+ if (!current) {
+ throw new Error(`Expected drawing "${drawing.drawingId}" to exist.`);
+ }
+ return structuredClone(current);
+ });
+ const before = readDrawings();
+
+ expect(await testBed.commandService.executeCommand(commandId, params)).toBe(true);
+ const after = readDrawings();
+ expect(after[0].transform).not.toEqual(before[0].transform);
+ expect(after[2].transform).toEqual(before[2].transform);
+ expect(getSheetDrawingPlacement(after[2])).toEqual(getSheetDrawingPlacement(before[2]));
+ expect(after[0].transform?.width).toBe(before[0].transform?.width);
+ expect(after[0].transform?.height).toBe(before[0].transform?.height);
+ if (commandId === SetRowHiddenCommand.id || commandId === SetColHiddenCommand.id) {
+ expect(after[1]).not.toEqual(before[1]);
+ } else {
+ expect(after[1].transform).not.toEqual(before[1].transform);
+ expect([
+ after[1].transform?.width !== before[1].transform?.width,
+ after[1].transform?.height !== before[1].transform?.height,
+ ]).toContain(true);
+ }
+ expect(after.map(getSheetDrawingPlacement).map(({ kind }) => kind)).toEqual([
+ SheetDrawingAnchorType.Position,
+ SheetDrawingAnchorType.Both,
+ SheetDrawingAnchorType.None,
+ ]);
+
+ expect(await testBed.commandService.executeCommand(UndoCommandId)).toBe(true);
+ expect(readDrawings()).toEqual(before);
+ expect(await testBed.commandService.executeCommand(RedoCommandId)).toBe(true);
+ expect(readDrawings()).toEqual(after);
+ });
+
it('resizes both-anchored drawings when row height changes', async () => {
const service = await insertDrawing();
const before = structuredClone(getDrawing(service));
@@ -117,6 +259,115 @@ describe('sheet drawing transforms without UI plugins', () => {
expect(getDrawing(service)).toEqual(after);
});
+ it('updates placement through a command and round-trips through undo and redo', async () => {
+ const service = await insertDrawing();
+ const before = structuredClone(getDrawing(service));
+ const placement: ISheetDrawingPlacement = {
+ kind: SheetDrawingAnchorType.None,
+ left: 640,
+ top: 96,
+ width: 240,
+ height: 120,
+ };
+
+ expect(await testBed.commandService.executeCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawings: [{ drawingId: 'drawing-1', placement }],
+ })).toBe(true);
+ const after = structuredClone(getDrawing(service));
+ expect(getSheetDrawingPlacement(after)).toEqual(placement);
+
+ expect(await testBed.commandService.executeCommand(UndoCommandId)).toBe(true);
+ expect(getDrawing(service)).toEqual(before);
+ expect(await testBed.commandService.executeCommand(RedoCommandId)).toBe(true);
+ expect(getDrawing(service)).toEqual(after);
+ });
+
+ it('requires a loaded Sheet for bounds inference and preserves rotation state', () => {
+ expect(() => normalizeSheetDrawingPlacement({
+ kind: SheetDrawingAnchorType.Position,
+ bounds: { left: 120, top: 80, width: 240, height: 120 },
+ })).toThrow('SHEET_DRAWING_PLACEMENT_SKELETON_REQUIRED');
+
+ const skeleton = testBed.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');
+ if (!skeleton) {
+ throw new Error('Expected the Sheet skeleton to exist.');
+ }
+ const source: ISheetDrawing = {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'rotated-drawing',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ transform: {
+ left: 120,
+ top: 80,
+ width: 240,
+ height: 120,
+ angle: 37,
+ flipX: true,
+ flipY: false,
+ skewX: 4,
+ skewY: 2,
+ },
+ sheetTransform: {
+ from: { row: 2, column: 2, rowOffset: 4, columnOffset: 6 },
+ to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ angle: 37,
+ flipX: true,
+ flipY: false,
+ skewX: 4,
+ skewY: 2,
+ },
+ axisAlignSheetTransform: {
+ from: { row: 2, column: 2, rowOffset: 4, columnOffset: 6 },
+ to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ },
+ };
+ const placements: ISheetDrawingPlacement[] = [
+ {
+ kind: SheetDrawingAnchorType.Position,
+ from: { row: 3, column: 3, rowOffset: 8, columnOffset: 8 },
+ width: 320,
+ height: 180,
+ },
+ {
+ kind: SheetDrawingAnchorType.Both,
+ from: { row: 3, column: 3, rowOffset: 8, columnOffset: 8 },
+ to: { row: 10, column: 8, rowOffset: 0, columnOffset: 0 },
+ },
+ {
+ kind: SheetDrawingAnchorType.None,
+ left: 640,
+ top: 96,
+ width: 320,
+ height: 180,
+ },
+ ];
+
+ for (const placement of placements) {
+ const result = applySheetDrawingPlacement(
+ source,
+ placement,
+ placement.kind === SheetDrawingAnchorType.None ? undefined : skeleton
+ );
+ expect(result.transform).toEqual(expect.objectContaining({
+ angle: 37,
+ flipX: true,
+ flipY: false,
+ skewX: 4,
+ skewY: 2,
+ }));
+ expect(result.sheetTransform).toEqual(expect.objectContaining({
+ angle: 37,
+ flipX: true,
+ flipY: false,
+ skewX: 4,
+ skewY: 2,
+ }));
+ }
+ });
+
it.each([
['remove row', RemoveRowCommand.id, {
unitId: 'test',
diff --git a/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts b/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
index f88cf6f0c6..08e29ea174 100644
--- a/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
+++ b/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
@@ -24,6 +24,7 @@ import { CopySheetCommand, RemoveSheetCommand, SheetInterceptorService } from '@
import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-drawing.command';
import { SetDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
+import { SetSheetDrawingPlacementCommand } from '../commands/commands/set-sheet-drawing-placement.command';
import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
import { DrawingApplyType, SetDrawingApplyMutation } from '../commands/mutations/set-drawing-apply.mutation';
import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
@@ -76,6 +77,7 @@ export class SheetsDrawingLoadController extends Disposable {
InsertSheetDrawingCommand,
RemoveSheetDrawingCommand,
SetDrawingArrangeCommand,
+ SetSheetDrawingPlacementCommand,
ClearSheetDrawingTransformerOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
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 392bb9b8df..8d38183c60 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
@@ -14,8 +14,13 @@
* limitations under the License.
*/
-import type { Injector, Univer, Workbook } from '@univerjs/core';
+import type {
+ Injector,
+ Univer,
+ Workbook,
+} from '@univerjs/core';
import type { FWorkbook } from '@univerjs/sheets/facade';
+import type { ISheetDrawingPlacement } from '../../services/sheet-drawing-placement';
import type { ISheetDrawing } from '../../services/sheet-drawing.service';
import {
DrawingTypeEnum,
@@ -26,11 +31,13 @@ import {
UndoCommand,
UniverInstanceType,
} from '@univerjs/core';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';
import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';
import { resolveSheetDrawingRotateEnabled } from '../../common/rotate-enabled';
-import { ISheetDrawingService } from '../../services/sheet-drawing.service';
+import { getSheetDrawingPlacement } from '../../services/sheet-drawing-placement';
+import { ISheetDrawingService, SheetDrawingAnchorType } from '../../services/sheet-drawing.service';
import { FWorksheetDrawingMixin } from '../f-worksheet';
describe('FWorksheetDrawingMixin group drawings', () => {
@@ -219,6 +226,118 @@ describe('FWorksheetDrawingMixin group drawings', () => {
expect(fWorksheet.getImages()).toEqual([]);
});
+ it('builds and round-trips an Absolute image placement without a Sheet skeleton', async () => {
+ const fWorksheet = createFacade(injector);
+ const ensureSkeleton = vi.spyOn(injector.get(SheetSkeletonService), 'ensureSkeleton')
+ .mockImplementation(() => {
+ throw new Error('SKELETON_MUST_NOT_BE_READ');
+ });
+ const placement: ISheetDrawingPlacement = {
+ kind: SheetDrawingAnchorType.None,
+ left: 640,
+ top: 96,
+ width: 320,
+ height: 180,
+ };
+
+ const image = await fWorksheet.newOverGridImage()
+ .setSource('https://example.com/absolute.png', ImageSourceType.URL)
+ .setPlacement(placement)
+ .buildAsync();
+
+ expect(ensureSkeleton).not.toHaveBeenCalled();
+ expect(image.transform).toEqual(expect.objectContaining({
+ left: placement.left,
+ top: placement.top,
+ width: placement.width,
+ height: placement.height,
+ }));
+
+ fWorksheet.insertImages([image]);
+ expect(fWorksheet.getDrawingPlacement(image.drawingId)).toEqual(placement);
+ expect(fWorksheet.getImageById(image.drawingId)?.getPlacement()).toEqual(placement);
+
+ const moved: ISheetDrawingPlacement = {
+ ...placement,
+ left: 720,
+ top: 128,
+ };
+ expect(fWorksheet.setDrawingPlacement(image.drawingId, moved)).toBe(true);
+ expect(fWorksheet.getDrawingPlacement(image.drawingId)).toEqual(moved);
+ });
+
+ it('infers Position and Both markers from model bounds and returns the headless host layout', () => {
+ const fWorksheet = createFacade(injector);
+ const commandService = injector.get(ICommandService);
+ const drawing = createDrawing('layout-drawing', 120);
+ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [drawing],
+ })).toBe(true);
+
+ const bounds = { left: 120, top: 80, width: 320, height: 160 };
+ const position = fWorksheet.resolveDrawingPlacement({
+ kind: SheetDrawingAnchorType.Position,
+ bounds,
+ });
+ const both = fWorksheet.resolveDrawingPlacement({
+ kind: SheetDrawingAnchorType.Both,
+ bounds,
+ });
+
+ expect(position).toEqual(expect.objectContaining({
+ kind: SheetDrawingAnchorType.Position,
+ width: bounds.width,
+ height: bounds.height,
+ }));
+ expect(position).toHaveProperty('from');
+ expect(both).toEqual(expect.objectContaining({
+ kind: SheetDrawingAnchorType.Both,
+ }));
+ expect(both).toHaveProperty('from');
+ expect(both).toHaveProperty('to');
+
+ expect(fWorksheet.setDrawingPlacement(drawing.drawingId, {
+ kind: SheetDrawingAnchorType.Both,
+ bounds,
+ })).toBe(true);
+ expect(fWorksheet.getDrawingPlacement(drawing.drawingId)).toEqual(both);
+
+ const layout = fWorksheet.getDrawingLayout();
+ expect(layout.gridBounds.width).toBeGreaterThan(0);
+ expect(layout.gridBounds.height).toBeGreaterThan(0);
+ expect(layout.dataBounds.width).toBeGreaterThan(0);
+ expect(layout.dataBounds.height).toBeGreaterThan(0);
+ expect(layout.drawings).toEqual([
+ expect.objectContaining({
+ drawingId: drawing.drawingId,
+ bounds,
+ placement: both,
+ }),
+ ]);
+ });
+
+ it('rejects invalid bounds and reversed TwoCell markers without mutating the drawing', () => {
+ const fWorksheet = createFacade(injector);
+ const commandService = injector.get(ICommandService);
+ const drawing = createDrawing('validated-drawing', 120);
+ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [drawing],
+ })).toBe(true);
+
+ expect(() => fWorksheet.setDrawingPlacement(drawing.drawingId, {
+ kind: SheetDrawingAnchorType.Position,
+ bounds: { left: 120, top: 80, width: 0, height: 160 },
+ })).toThrow('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
+ expect(() => fWorksheet.setDrawingPlacement(drawing.drawingId, {
+ kind: SheetDrawingAnchorType.Both,
+ from: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ to: { row: 2, column: 2, rowOffset: 0, columnOffset: 0 },
+ })).toThrow('SHEET_DRAWING_PLACEMENT_EXTENT_INVALID');
+ expect(fWorksheet.getDrawingPlacement(drawing.drawingId)).toEqual(getSheetDrawingPlacement(drawing));
+ });
+
it('returns only images from sheet drawing data and exposes active images from the drawing selection', () => {
const commandService = injector.get(ICommandService);
const fWorksheet = createFacade(injector);
diff --git a/packages/sheets-drawing/src/facade/f-over-grid-image.ts b/packages/sheets-drawing/src/facade/f-over-grid-image.ts
index 9f4793ec50..bec494ba3c 100644
--- a/packages/sheets-drawing/src/facade/f-over-grid-image.ts
+++ b/packages/sheets-drawing/src/facade/f-over-grid-image.ts
@@ -14,10 +14,17 @@
* limitations under the License.
*/
-import type { IRotationSkewFlipTransform, ISize } from '@univerjs/core';
+import type {
+ IRotationSkewFlipTransform,
+ ISize,
+} from '@univerjs/core';
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { ICellOverGridPosition } from '@univerjs/sheets';
-import type { ISheetImage, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import type {
+ ISheetDrawingPlacement,
+ ISheetDrawingPlacementInput,
+ ISheetImage,
+} from '@univerjs/sheets-drawing';
import {
ArrangeTypeEnum,
DrawingTypeEnum,
@@ -30,7 +37,17 @@ import {
import { FBase } from '@univerjs/core/facade';
import { getImageSize } from '@univerjs/drawing';
import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute, SheetSkeletonService } from '@univerjs/sheets';
-import { RemoveSheetDrawingCommand, SetDrawingArrangeCommand, SetSheetDrawingCommand, transformToAxisAlignPosition } from '@univerjs/sheets-drawing';
+import {
+ applySheetDrawingPlacement,
+ getSheetDrawingPlacement,
+ ISheetDrawingService,
+ RemoveSheetDrawingCommand,
+ SetDrawingArrangeCommand,
+ SetSheetDrawingCommand,
+ SetSheetDrawingPlacementCommand,
+ SheetDrawingAnchorType,
+ transformToAxisAlignPosition,
+} from '@univerjs/sheets-drawing';
export interface IFOverGridImage extends Omit<ISheetImage, 'sheetTransform' | 'transform'>, ICellOverGridPosition, IRotationSkewFlipTransform, Required<ISize> {
@@ -124,10 +141,11 @@ function convertFOverGridImageToSheetImage(fOverGridImage: IFOverGridImage, shee
*/
export class FOverGridImageBuilder {
private _image: IFOverGridImage;
+ private _placement?: ISheetDrawingPlacementInput;
constructor(
unitId: string,
subUnitId: string,
- @Inject(Injector) protected readonly _injector: Injector
+ @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService
) {
this._image = {
drawingId: generateRandomId(6),
@@ -187,8 +205,7 @@ export class FOverGridImageBuilder {
*/
setImage(image: ISheetImage): FOverGridImageBuilder {
const { unitId, subUnitId } = image;
- const sheetSkeletonService = this._injector.get(SheetSkeletonService);
- const skeleton = sheetSkeletonService.getSkeleton(unitId, subUnitId);
+ const skeleton = this._sheetSkeletonService.getSkeleton(unitId, subUnitId);
if (!skeleton) {
throw new Error(`Skeleton for unitId ${unitId} and subUnitId ${subUnitId} not found`);
}
@@ -501,6 +518,74 @@ export class FOverGridImageBuilder {
return this;
}
+ /**
+ * Set an explicit OneCell, TwoCell, or Absolute placement for the image.
+ *
+ * This placement takes precedence over the individual row, column, size,
+ * and anchor type builder fields. Use bounds inference for an existing
+ * transform; use exact markers when a caller explicitly chose cells.
+ * @param {ISheetDrawingPlacementInput} placement Exact placement or bounds with an explicit anchor type.
+ * @returns {FOverGridImageBuilder} This builder.
+ * @example
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const image = await sheet.newOverGridImage()
+ * .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
+ * .setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
+ * from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
+ * width: 240,
+ * height: 120,
+ * })
+ * .buildAsync();
+ * sheet.insertImages([image]);
+ * ```
+ * @example Infer Position markers from model-space bounds
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const image = await sheet.newOverGridImage()
+ * .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
+ * .setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
+ * bounds: { left: 120, top: 80, width: 240, height: 120 },
+ * })
+ * .buildAsync();
+ * sheet.insertImages([image]);
+ * ```
+ * @example TwoCell
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const image = await sheet.newOverGridImage()
+ * .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
+ * .setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
+ * from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
+ * to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ * })
+ * .buildAsync();
+ * sheet.insertImages([image]);
+ * ```
+ * @example Absolute
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const image = await sheet.newOverGridImage()
+ * .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
+ * .setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.None,
+ * left: 640,
+ * top: 96,
+ * width: 240,
+ * height: 120,
+ * })
+ * .buildAsync();
+ * sheet.insertImages([image]);
+ * ```
+ */
+ setPlacement(placement: ISheetDrawingPlacementInput): FOverGridImageBuilder {
+ this._placement = placement;
+ return this;
+ }
+
/**
* Set the cropping region of the image by defining the top edges, thereby displaying the specific part of the image you want.
* @param {number} top - The number of pixels to crop from the top of the image
@@ -652,9 +737,9 @@ export class FOverGridImageBuilder {
}
async buildAsync(): Promise<ISheetImage> {
- const sheetSkeletonService = this._injector.get(SheetSkeletonService);
+ const sheetSkeletonService = this._sheetSkeletonService;
- if (this._image.width === 0 || this._image.height === 0) {
+ if (!this._placement && (this._image.width === 0 || this._image.height === 0)) {
const size = await getImageSize(this._image.source);
const width = size.width;
const height = size.height;
@@ -668,7 +753,50 @@ export class FOverGridImageBuilder {
}
}
- return convertFOverGridImageToSheetImage(this._image, sheetSkeletonService);
+ if (this._placement?.kind === SheetDrawingAnchorType.None) {
+ const { left, top, width, height } = 'bounds' in this._placement
+ ? this._placement.bounds
+ : this._placement;
+ const sheetTransform = {
+ from: {
+ column: 0,
+ columnOffset: left,
+ row: 0,
+ rowOffset: top,
+ },
+ to: {
+ column: 0,
+ columnOffset: left + width,
+ row: 0,
+ rowOffset: top + height,
+ },
+ };
+ const image: ISheetImage = {
+ ...this._image,
+ transform: {
+ left,
+ top,
+ width,
+ height,
+ flipY: this._image.flipY,
+ flipX: this._image.flipX,
+ angle: this._image.angle,
+ skewX: this._image.skewX,
+ skewY: this._image.skewY,
+ },
+ sheetTransform,
+ axisAlignSheetTransform: sheetTransform,
+ };
+ return applySheetDrawingPlacement(image, this._placement);
+ }
+
+ const image = convertFOverGridImageToSheetImage(this._image, sheetSkeletonService);
+ if (!this._placement) {
+ return image;
+ }
+
+ const skeleton = sheetSkeletonService.ensureSkeleton(image.unitId, image.subUnitId);
+ return applySheetDrawingPlacement(image, this._placement, skeleton);
}
}
@@ -679,7 +807,9 @@ export class FOverGridImage extends FBase {
constructor(
private _image: ISheetImage,
@ICommandService protected readonly _commandService: ICommandService,
- @Inject(Injector) protected readonly _injector: Injector
+ @Inject(Injector) protected readonly _injector: Injector,
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
+ @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService
) {
super();
}
@@ -720,6 +850,78 @@ export class FOverGridImage extends FBase {
return this._image.drawingType;
}
+ /**
+ * Get this image's explicit placement.
+ * @returns {ISheetDrawingPlacement} OneCell, TwoCell, or Absolute placement.
+ * @example
+ * ```ts
+ * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
+ * console.log(image.getPlacement());
+ * ```
+ */
+ getPlacement(): ISheetDrawingPlacement {
+ const current = this._sheetDrawingService.getDrawingByParam({
+ unitId: this._image.unitId,
+ subUnitId: this._image.subUnitId,
+ drawingId: this._image.drawingId,
+ });
+ return getSheetDrawingPlacement(current ?? this._image);
+ }
+
+ /**
+ * Set this image's explicit placement through the drawing command.
+ * `Position`, `Both`, and `None` correspond to OneCell, TwoCell, and
+ * Absolute. Bounds inference is preferable when preserving the current
+ * visual bounds; exact markers are for user-selected cells and offsets.
+ * @param {ISheetDrawingPlacementInput} placement Exact placement or bounds with an explicit anchor type.
+ * @returns {boolean} `true` when the command succeeds.
+ * @example OneCell
+ * ```ts
+ * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
+ * image.setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
+ * from: { row: 4, column: 3, rowOffset: 8, columnOffset: 8 },
+ * width: 320,
+ * height: 180,
+ * });
+ * ```
+ * @example Infer TwoCell markers while preserving current model-space bounds
+ * ```ts
+ * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
+ * image.setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
+ * bounds: { left: 120, top: 80, width: 320, height: 160 },
+ * });
+ * ```
+ * @example TwoCell
+ * ```ts
+ * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
+ * image.setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
+ * from: { row: 4, column: 3, rowOffset: 8, columnOffset: 8 },
+ * to: { row: 10, column: 8, rowOffset: 0, columnOffset: 0 },
+ * });
+ * ```
+ * @example Absolute
+ * ```ts
+ * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
+ * image.setPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.None,
+ * left: 640,
+ * top: 96,
+ * width: 320,
+ * height: 180,
+ * });
+ * ```
+ */
+ setPlacement(placement: ISheetDrawingPlacementInput): boolean {
+ return this._commandService.syncExecuteCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId: this._image.unitId,
+ subUnitId: this._image.subUnitId,
+ drawings: [{ drawingId: this._image.drawingId, placement }],
+ });
+ }
+
/**
* Remove the image from the sheet
* @returns {boolean} true if the image is removed successfully, otherwise false
@@ -934,8 +1136,7 @@ export class FOverGridImage extends FBase {
this._image.sheetTransform.angle = angle;
this._image.transform && (this._image.transform.angle = angle);
if (this._image.transform) {
- const sheetSkeletonService = this._injector.get(SheetSkeletonService);
- const skeleton = sheetSkeletonService.getSkeleton(this._image.unitId, this._image.subUnitId);
+ const skeleton = this._sheetSkeletonService.getSkeleton(this._image.unitId, this._image.subUnitId);
if (!skeleton) {
throw new Error(`Skeleton for unitId ${this._image.unitId} and subUnitId ${this._image.subUnitId} not found`);
}
diff --git a/packages/sheets-drawing/src/facade/f-worksheet.ts b/packages/sheets-drawing/src/facade/f-worksheet.ts
index 501d7d4924..4cbf187311 100644
--- a/packages/sheets-drawing/src/facade/f-worksheet.ts
+++ b/packages/sheets-drawing/src/facade/f-worksheet.ts
@@ -14,17 +14,35 @@
* limitations under the License.
*/
-import type { IDrawingParam } from '@univerjs/core';
+import type { IDrawingParam, IGroupBaseBound, Injector } from '@univerjs/core';
import type { IFBlobSource } from '@univerjs/core/facade';
import type { IDrawingGroupUpdateParam, IDrawingJsonUndo1 } from '@univerjs/drawing';
-import type { ISheetDrawing, ISheetImage } from '@univerjs/sheets-drawing';
+import type { ISheetDrawing, ISheetDrawingPlacement, ISheetDrawingPlacementInput, ISheetImage } from '@univerjs/sheets-drawing';
import { DrawingTypeEnum, generateRandomId, ImageSourceType, IUndoRedoService } from '@univerjs/core';
import { isGroupableDrawingType } from '@univerjs/drawing';
import { getGroupState, transformObjectOutOfGroup } from '@univerjs/engine-render';
-import { DrawingApplyType, InsertSheetDrawingCommand, ISheetDrawingService, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { DrawingApplyType, getSheetDrawingPlacement, InsertSheetDrawingCommand, ISheetDrawingService, normalizeSheetDrawingPlacement, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SetSheetDrawingCommand, SetSheetDrawingPlacementCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { FWorksheet } from '@univerjs/sheets/facade';
import { FOverGridImage, FOverGridImageBuilder } from './f-over-grid-image';
+export interface ISheetDrawingLayoutObject {
+ drawingId: string;
+ drawingType: DrawingTypeEnum;
+ bounds: IGroupBaseBound;
+ placement: ISheetDrawingPlacement;
+ groupId?: string;
+}
+
+export interface ISheetDrawingLayout {
+ /** Entire Sheet grid in model coordinates. */
+ gridBounds: IGroupBaseBound;
+ /** Cell content range in model coordinates. */
+ dataBounds: IGroupBaseBound;
+ /** Drawings ordered from back to front. */
+ drawings: ISheetDrawingLayoutObject[];
+}
+
/**
* @ignore
*/
@@ -185,6 +203,113 @@ export interface IFWorksheetDrawingMixin {
*/
updateImages(sheetImages: ISheetImage[]): FWorksheet;
+ /**
+ * Get the placement of any drawing on this sheet.
+ *
+ * Image, Shape, Chart, and Group use the same placement contract.
+ * @param {string} drawingId Drawing id.
+ * @returns {ISheetDrawingPlacement | null} The placement, or `null` when the drawing does not exist.
+ * @example
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const placement = sheet.getDrawingPlacement('drawing-id');
+ * if (placement?.kind === univerAPI.Enum.SheetDrawingAnchorType.Both) {
+ * console.log(placement.from, placement.to);
+ * }
+ * ```
+ */
+ getDrawingPlacement(drawingId: string): ISheetDrawingPlacement | null;
+
+ /**
+ * Set the placement of any drawing on this sheet through the drawing command.
+ *
+ * @param {string} drawingId Drawing id.
+ * @param {ISheetDrawingPlacementInput} placement Exact markers or model-space bounds with an explicit anchor type.
+ * @returns {boolean} `true` when the command succeeds.
+ * @example OneCell: move with cells, keep pixel size
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const drawingId = sheet.getImages()[0]?.getId();
+ * if (!drawingId) throw new Error('No drawing found.');
+ * const changed = sheet.setDrawingPlacement(drawingId, {
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
+ * from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
+ * width: 240,
+ * height: 120,
+ * });
+ * console.log(changed);
+ * ```
+ * @example TwoCell: move and resize with both cell markers
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const drawingId = sheet.getImages()[0]?.getId();
+ * if (!drawingId) throw new Error('No drawing found.');
+ * sheet.setDrawingPlacement(drawingId, {
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
+ * from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
+ * to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
+ * });
+ * ```
+ * @example Absolute: do not move or resize after row or column changes
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const drawingId = sheet.getImages()[0]?.getId();
+ * if (!drawingId) throw new Error('No drawing found.');
+ * sheet.setDrawingPlacement(drawingId, {
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.None,
+ * left: 640,
+ * top: 96,
+ * width: 240,
+ * height: 120,
+ * });
+ * ```
+ */
+ setDrawingPlacement(drawingId: string, placement: ISheetDrawingPlacementInput): boolean;
+
+ /**
+ * Resolve exact markers or model-space bounds to a normalized Placement.
+ *
+ * Bounds inference is usually preferable when positioning from an existing
+ * transform. Exact markers are useful when the caller must preserve a
+ * user-selected cell and offset. `Position` maps to OOXML OneCell,
+ * `Both` maps to TwoCell, and `None` maps to Absolute.
+ * @param {ISheetDrawingPlacementInput} placement Exact markers or bounds with an explicit anchor type.
+ * @returns {ISheetDrawingPlacement} The normalized Placement.
+ * @example Infer Position and Both placements from bounds in Node/headless
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const positionPlacement = sheet.resolveDrawingPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
+ * bounds: { left: 120, top: 80, width: 320, height: 160 },
+ * });
+ * const bothPlacement = sheet.resolveDrawingPlacement({
+ * kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
+ * bounds: { left: 120, top: 80, width: 320, height: 160 },
+ * });
+ * console.log(positionPlacement.from);
+ * console.log(bothPlacement.from, bothPlacement.to);
+ * ```
+ */
+ resolveDrawingPlacement(placement: ISheetDrawingPlacementInput): ISheetDrawingPlacement;
+
+ /**
+ * Get the Sheet host layout in model coordinates.
+ *
+ * This API is available in Node/headless and does not include viewport,
+ * scroll, zoom, frozen-pane clipping, or screen coordinates.
+ * @returns {ISheetDrawingLayout} Grid, data, and ordered Drawing bounds.
+ * @example
+ * ```ts
+ * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * const layout = sheet.getDrawingLayout();
+ * console.log(layout.gridBounds, layout.dataBounds);
+ * for (const drawing of layout.drawings) {
+ * console.log(drawing.drawingId, drawing.bounds);
+ * }
+ * ```
+ */
+ getDrawingLayout(): ISheetDrawingLayout;
+
/**
* Get the current selected images.
* @returns {FOverGridImage[]} The FOverGridImage instances
@@ -384,6 +509,16 @@ export interface IFWorksheetDrawingMixin {
}
export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDrawingMixin {
+ declare private _sheetDrawingService: ISheetDrawingService;
+ declare private _sheetSkeletonService: SheetSkeletonService;
+ declare private _undoRedoService: IUndoRedoService;
+
+ override _initialize(injector: Injector): void {
+ this._sheetDrawingService = injector.get(ISheetDrawingService);
+ this._sheetSkeletonService = injector.get(SheetSkeletonService);
+ this._undoRedoService = injector.get(IUndoRedoService);
+ }
+
override async insertImage(url: IFBlobSource | string, column?: number, row?: number, offsetX?: number, offsetY?: number): Promise<boolean> {
const imageBuilder = this.newOverGridImage();
if (typeof url === 'string') {
@@ -450,7 +585,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
}
override getImages(): FOverGridImage[] {
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const drawingData = sheetDrawingService.getDrawingData(this._fWorkbook.getId(), this.getSheetId());
const images: FOverGridImage[] = [];
for (const drawingId in drawingData) {
@@ -464,7 +599,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
}
override getImageById(id: string): FOverGridImage | null {
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const drawing = sheetDrawingService.getDrawingByParam({ unitId: this._fWorkbook.getId(), subUnitId: this.getSheetId(), drawingId: id });
if (drawing && drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE) {
return this._injector.createInstance(FOverGridImage, drawing as ISheetImage);
@@ -473,7 +608,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
}
override getActiveImages(): FOverGridImage[] {
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const drawingData = sheetDrawingService.getFocusDrawings();
const images: FOverGridImage[] = [];
for (const drawingId in drawingData) {
@@ -488,6 +623,81 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
return this;
}
+ override getDrawingPlacement(drawingId: string): ISheetDrawingPlacement | null {
+ const drawing = this._sheetDrawingService.getDrawingByParam({
+ unitId: this._fWorkbook.getId(),
+ subUnitId: this.getSheetId(),
+ drawingId,
+ });
+ return drawing ? getSheetDrawingPlacement(drawing) : null;
+ }
+
+ override setDrawingPlacement(drawingId: string, placement: ISheetDrawingPlacementInput): boolean {
+ return this._commandService.syncExecuteCommand(SetSheetDrawingPlacementCommand.id, {
+ unitId: this._fWorkbook.getId(),
+ subUnitId: this.getSheetId(),
+ drawings: [{ drawingId, placement }],
+ });
+ }
+
+ override resolveDrawingPlacement(placement: ISheetDrawingPlacementInput): ISheetDrawingPlacement {
+ const skeleton = placement.kind === SheetDrawingAnchorType.None
+ ? undefined
+ : this._sheetSkeletonService.ensureSkeleton(this._fWorkbook.getId(), this.getSheetId());
+ if (placement.kind !== SheetDrawingAnchorType.None && !skeleton) {
+ throw new Error('SHEET_DRAWING_PLACEMENT_SKELETON_REQUIRED');
+ }
+ return normalizeSheetDrawingPlacement(placement, skeleton);
+ }
+
+ override getDrawingLayout(): ISheetDrawingLayout {
+ const unitId = this._fWorkbook.getId();
+ const subUnitId = this.getSheetId();
+ const skeleton = this._sheetSkeletonService.ensureSkeleton(unitId, subUnitId);
+ if (!skeleton) {
+ throw new Error('SHEET_DRAWING_PLACEMENT_SKELETON_REQUIRED');
+ }
+ const { startRow, endRow, startColumn, endColumn } = this._worksheet.getDataRealRange();
+ const startCell = skeleton.getCellWithCoordByIndex(startRow, startColumn, false);
+ const endCell = skeleton.getCellWithCoordByIndex(endRow, endColumn, false);
+ const drawingService = this._sheetDrawingService;
+ const drawingData = drawingService.getDrawingData(unitId, subUnitId);
+ const orderedIds = drawingService.getDrawingOrder(unitId, subUnitId);
+ const drawingIds = [...orderedIds, ...Object.keys(drawingData).filter((drawingId) => !orderedIds.includes(drawingId))];
+ const drawings: ISheetDrawingLayoutObject[] = [];
+
+ for (const drawingId of drawingIds) {
+ const drawing = drawingData[drawingId];
+ const bounds = drawing && getDrawingBounds(drawing);
+ if (!drawing || !bounds) {
+ continue;
+ }
+ drawings.push({
+ drawingId,
+ drawingType: drawing.drawingType,
+ bounds,
+ placement: getSheetDrawingPlacement(drawing),
+ groupId: drawing.groupId,
+ });
+ }
+
+ return {
+ gridBounds: {
+ left: 0,
+ top: 0,
+ width: skeleton.columnTotalWidth,
+ height: skeleton.rowTotalHeight,
+ },
+ dataBounds: {
+ left: startCell.startX,
+ top: startCell.startY,
+ width: endCell.endX - startCell.startX,
+ height: endCell.endY - startCell.startY,
+ },
+ drawings,
+ };
+ }
+
override newOverGridImage(): FOverGridImageBuilder {
const unitId = this._fWorkbook.getId();
const subUnitId = this.getSheetId();
@@ -500,7 +710,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
const unitId = this._fWorkbook.getId();
const subUnitId = this.getSheetId();
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
if (sheetDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId: groupId })) return null;
const drawings = uniqueDrawingIds.map((drawingId) => sheetDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId }));
@@ -539,7 +749,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
override ungroupDrawings(groupIds: string[]): boolean {
const unitId = this._fWorkbook.getId();
const subUnitId = this.getSheetId();
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const groupParams: IDrawingGroupUpdateParam[] = [];
for (const groupId of groupIds) {
@@ -581,7 +791,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
override getDrawingGroupChildren(groupId: string, recursive = false): ISheetDrawing[] {
const unitId = this._fWorkbook.getId();
const subUnitId = this.getSheetId();
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
if (!recursive) {
return sheetDrawingService.getDrawingsByGroup({ unitId, subUnitId, drawingId: groupId }) as ISheetDrawing[];
@@ -599,7 +809,7 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
override getDrawingParentGroup(drawingId: string): ISheetDrawing | null {
const unitId = this._fWorkbook.getId();
const subUnitId = this.getSheetId();
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const drawing = sheetDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId });
if (!drawing?.groupId) return null;
@@ -617,9 +827,9 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
private _applyGroupDrawingOperation(groupParams: IDrawingGroupUpdateParam[], type: DrawingApplyType.GROUP | DrawingApplyType.UNGROUP): boolean {
if (groupParams.length === 0) return false;
- const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const sheetDrawingService = this._sheetDrawingService;
const commandService = this._commandService;
- const undoRedoService = this._injector.get(IUndoRedoService);
+ const undoRedoService = this._undoRedoService;
const jsonOp = (type === DrawingApplyType.GROUP
? sheetDrawingService.getGroupDrawingOp(groupParams)
: sheetDrawingService.getUngroupDrawingOp(groupParams)) as IDrawingJsonUndo1;
@@ -688,6 +898,23 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
}
}
+function getDrawingBounds(drawing: ISheetDrawing): IGroupBaseBound | null {
+ const { left, top, width, height } = drawing.transform ?? {};
+ if (
+ typeof left !== 'number' ||
+ typeof top !== 'number' ||
+ typeof width !== 'number' ||
+ typeof height !== 'number' ||
+ !Number.isFinite(left) ||
+ !Number.isFinite(top) ||
+ !Number.isFinite(width) ||
+ !Number.isFinite(height)
+ ) {
+ return null;
+ }
+ return { left, top, width, height };
+}
+
FWorksheet.extend(FWorksheetDrawingMixin);
declare module '@univerjs/sheets/facade' {
// eslint-disable-next-line ts/naming-convention
diff --git a/packages/sheets-drawing/src/index.ts b/packages/sheets-drawing/src/index.ts
index 7eff9f9665..cda6c724e5 100644
--- a/packages/sheets-drawing/src/index.ts
+++ b/packages/sheets-drawing/src/index.ts
@@ -25,6 +25,8 @@ export { RemoveSheetDrawingCommand } from './commands/commands/remove-sheet-draw
export type { IRemoveSheetDrawingCommandParam, IRemoveSheetDrawingCommandParams } from './commands/commands/remove-sheet-drawing.command';
export { SetDrawingArrangeCommand } from './commands/commands/set-drawing-arrange.command';
export type { ISetDrawingArrangeCommandParams } from './commands/commands/set-drawing-arrange.command';
+export { SetSheetDrawingPlacementCommand } from './commands/commands/set-sheet-drawing-placement.command';
+export type { ISetSheetDrawingPlacementCommandParams } from './commands/commands/set-sheet-drawing-placement.command';
export { SetSheetDrawingCommand } from './commands/commands/set-sheet-drawing.command';
export type { ISetDrawingCommandParams } from './commands/commands/set-sheet-drawing.command';
export { DrawingApplyType, SetDrawingApplyMutation } from './commands/mutations/set-drawing-apply.mutation';
@@ -34,6 +36,19 @@ export { isKnownSheetNonRotatableDrawingType, resolveSheetDrawingRotateEnabled }
export type { IUniverSheetsDrawingConfig } from './config/config';
export { SHEET_DRAWING_PLUGIN } from './controllers/sheet-drawing.controller';
export { UniverSheetsDrawingPlugin } from './plugin';
+export {
+ applySheetDrawingPlacement,
+ getSheetDrawingPlacement,
+ normalizeSheetDrawingPlacement,
+} from './services/sheet-drawing-placement';
+export type {
+ ISheetDrawingAbsolutePlacement,
+ ISheetDrawingOneCellPlacement,
+ ISheetDrawingPlacement,
+ ISheetDrawingPlacementByBounds,
+ ISheetDrawingPlacementInput,
+ ISheetDrawingTwoCellPlacement,
+} from './services/sheet-drawing-placement';
export { SheetDrawingTransformPlanService } from './services/sheet-drawing-transform-plan.service';
export type {
ISheetDrawingTransformExtension,
diff --git a/packages/sheets-drawing/src/services/sheet-drawing-placement.ts b/packages/sheets-drawing/src/services/sheet-drawing-placement.ts
new file mode 100644
index 0000000000..058ecaa0dd
--- /dev/null
+++ b/packages/sheets-drawing/src/services/sheet-drawing-placement.ts
@@ -0,0 +1,352 @@
+/**
+ * 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 { IGroupBaseBound, ITransformState } from '@univerjs/core';
+import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
+import type { ICellOverGridPosition } from '@univerjs/sheets';
+import type {
+ ISheetDrawing,
+ ISheetDrawingPosition,
+ ISheetFloatDom,
+ ISheetImage,
+} from './sheet-drawing.service';
+import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute } from '@univerjs/sheets';
+import { transformToAxisAlignPosition, transformToDrawingPosition } from '../basics/transform-position';
+import {
+ SheetDrawingAnchorType,
+} from './sheet-drawing.service';
+
+/**
+ * Anchor a drawing to one cell while keeping a fixed pixel extent.
+ */
+export interface ISheetDrawingOneCellPlacement {
+ /** Placement discriminator. */
+ kind: SheetDrawingAnchorType.Position;
+ /** Zero-based anchor cell and pixel offsets from its top-left corner. */
+ from: ICellOverGridPosition;
+ /** Drawing width in pixels. */
+ width: number;
+ /** Drawing height in pixels. */
+ height: number;
+}
+
+/**
+ * Anchor a drawing between two cell markers.
+ */
+export interface ISheetDrawingTwoCellPlacement {
+ /** Placement discriminator. */
+ kind: SheetDrawingAnchorType.Both;
+ /** Zero-based start cell and pixel offsets. */
+ from: ICellOverGridPosition;
+ /** Zero-based end cell and pixel offsets. */
+ to: ICellOverGridPosition;
+}
+
+/**
+ * Position a drawing in the Sheet canvas pixel coordinate system.
+ */
+export interface ISheetDrawingAbsolutePlacement {
+ /** Placement discriminator. */
+ kind: SheetDrawingAnchorType.None;
+ /** Horizontal pixel offset from the Sheet canvas origin. */
+ left: number;
+ /** Vertical pixel offset from the Sheet canvas origin. */
+ top: number;
+ /** Drawing width in pixels. */
+ width: number;
+ /** Drawing height in pixels. */
+ height: number;
+}
+
+/**
+ * Explicit Sheet drawing placement.
+ */
+export type ISheetDrawingPlacement =
+ | ISheetDrawingOneCellPlacement
+ | ISheetDrawingTwoCellPlacement
+ | ISheetDrawingAbsolutePlacement;
+
+/**
+ * Infer cell markers from model-space bounds after the anchor semantics have
+ * been selected explicitly.
+ */
+export interface ISheetDrawingPlacementByBounds {
+ /** Position, Both, or None semantics. */
+ kind: SheetDrawingAnchorType;
+ /** Bounds in the Sheet model coordinate system. */
+ bounds: IGroupBaseBound;
+}
+
+/**
+ * Exact Placement or model-space bounds to normalize into one.
+ */
+export type ISheetDrawingPlacementInput = ISheetDrawingPlacement | ISheetDrawingPlacementByBounds;
+
+export function getSheetDrawingPlacement(drawing: ISheetDrawing): ISheetDrawingPlacement {
+ const anchorType = drawing.anchorType ?? SheetDrawingAnchorType.Position;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return {
+ kind: SheetDrawingAnchorType.None,
+ left: drawing.transform?.left ?? 0,
+ top: drawing.transform?.top ?? 0,
+ width: drawing.transform?.width ?? 0,
+ height: drawing.transform?.height ?? 0,
+ };
+ }
+
+ if (anchorType === SheetDrawingAnchorType.Both) {
+ return {
+ kind: SheetDrawingAnchorType.Both,
+ from: { ...drawing.sheetTransform.from },
+ to: { ...drawing.sheetTransform.to },
+ };
+ }
+
+ return {
+ kind: SheetDrawingAnchorType.Position,
+ from: { ...drawing.sheetTransform.from },
+ width: drawing.transform?.width ?? 0,
+ height: drawing.transform?.height ?? 0,
+ };
+}
+
+export function applySheetDrawingPlacement(
+ drawing: ISheetImage,
+ input: ISheetDrawingPlacementInput,
+ skeleton?: SpreadsheetSkeleton
+): ISheetImage;
+export function applySheetDrawingPlacement(
+ drawing: ISheetFloatDom,
+ input: ISheetDrawingPlacementInput,
+ skeleton?: SpreadsheetSkeleton
+): ISheetFloatDom;
+export function applySheetDrawingPlacement(
+ drawing: ISheetDrawing,
+ input: ISheetDrawingPlacementInput,
+ skeleton?: SpreadsheetSkeleton
+): ISheetDrawing;
+export function applySheetDrawingPlacement(
+ drawing: ISheetDrawing,
+ input: ISheetDrawingPlacementInput,
+ skeleton?: SpreadsheetSkeleton
+): ISheetDrawing {
+ const placement = normalizeSheetDrawingPlacement(input, skeleton);
+
+ if (placement.kind === SheetDrawingAnchorType.None) {
+ const transform = withExistingTransform(drawing.transform, placement);
+ const sheetTransform = absoluteSheetTransform(placement, drawing.sheetTransform);
+ return {
+ ...drawing,
+ anchorType: SheetDrawingAnchorType.None,
+ transform,
+ sheetTransform,
+ axisAlignSheetTransform: sheetTransform,
+ };
+ }
+
+ if (!skeleton) {
+ throw new Error('SHEET_DRAWING_PLACEMENT_SKELETON_REQUIRED');
+ }
+
+ if (placement.kind === SheetDrawingAnchorType.Position) {
+ const converted = convertPositionCellToSheetOverGrid(
+ drawing.unitId,
+ drawing.subUnitId,
+ placement.from,
+ placement.width,
+ placement.height,
+ skeleton
+ );
+ const sheetTransform = withExistingSheetTransform(drawing.sheetTransform, converted.sheetTransform);
+ const transform = withExistingTransform(drawing.transform, converted.transform);
+ return {
+ ...drawing,
+ anchorType: SheetDrawingAnchorType.Position,
+ sheetTransform,
+ transform,
+ axisAlignSheetTransform: transformToAxisAlignPosition(transform, skeleton),
+ };
+ }
+
+ const sheetTransform = withExistingSheetTransform(drawing.sheetTransform, {
+ from: placement.from,
+ to: placement.to,
+ });
+ const bounds = convertPositionSheetOverGridToAbsolute(
+ drawing.unitId,
+ drawing.subUnitId,
+ sheetTransform,
+ skeleton
+ );
+ const transform = withExistingTransform(drawing.transform, bounds);
+ return {
+ ...drawing,
+ anchorType: SheetDrawingAnchorType.Both,
+ sheetTransform,
+ transform,
+ axisAlignSheetTransform: transformToAxisAlignPosition(transform, skeleton),
+ };
+}
+
+/**
+ * Normalize exact markers or model-space bounds to the authoritative
+ * Position, Both, or None Placement.
+ */
+export function normalizeSheetDrawingPlacement(
+ input: ISheetDrawingPlacementInput,
+ skeleton?: SpreadsheetSkeleton
+): ISheetDrawingPlacement {
+ if (!('bounds' in input)) {
+ validatePlacement(input);
+ if (input.kind === SheetDrawingAnchorType.Both && skeleton) {
+ validateBounds(convertPositionSheetOverGridToAbsolute(
+ skeleton.worksheet.getUnitId(),
+ skeleton.worksheet.getSheetId(),
+ {
+ from: input.from,
+ to: input.to,
+ },
+ skeleton
+ ));
+ }
+ return input;
+ }
+
+ validateBounds(input.bounds);
+ if (input.kind === SheetDrawingAnchorType.None) {
+ return {
+ kind: SheetDrawingAnchorType.None,
+ ...input.bounds,
+ };
+ }
+ if (!skeleton) {
+ throw new Error('SHEET_DRAWING_PLACEMENT_SKELETON_REQUIRED');
+ }
+
+ const sheetTransform = transformToDrawingPosition(input.bounds, skeleton);
+ if (input.kind === SheetDrawingAnchorType.Position) {
+ return {
+ kind: SheetDrawingAnchorType.Position,
+ from: sheetTransform.from,
+ width: input.bounds.width,
+ height: input.bounds.height,
+ };
+ }
+ if (input.kind === SheetDrawingAnchorType.Both) {
+ return {
+ kind: SheetDrawingAnchorType.Both,
+ from: sheetTransform.from,
+ to: sheetTransform.to,
+ };
+ }
+
+ throw new Error('SHEET_DRAWING_PLACEMENT_KIND_INVALID');
+}
+
+function withExistingSheetTransform(
+ current: ISheetDrawingPosition,
+ placement: Pick<ISheetDrawingPosition, 'from' | 'to'>
+): ISheetDrawingPosition {
+ return {
+ ...current,
+ from: { ...placement.from },
+ to: { ...placement.to },
+ };
+}
+
+function withExistingTransform(
+ current: ITransformState | null | undefined | void,
+ bounds: Pick<ITransformState, 'left' | 'top' | 'width' | 'height'>
+): ITransformState {
+ return {
+ ...current,
+ left: bounds.left,
+ top: bounds.top,
+ width: bounds.width,
+ height: bounds.height,
+ };
+}
+
+function absoluteSheetTransform(
+ placement: ISheetDrawingAbsolutePlacement,
+ current: ISheetDrawingPosition
+): ISheetDrawingPosition {
+ return {
+ ...current,
+ from: {
+ column: 0,
+ columnOffset: placement.left,
+ row: 0,
+ rowOffset: placement.top,
+ },
+ to: {
+ column: 0,
+ columnOffset: placement.left + placement.width,
+ row: 0,
+ rowOffset: placement.top + placement.height,
+ },
+ };
+}
+
+function validatePlacement(placement: ISheetDrawingPlacement): void {
+ if (placement.kind === SheetDrawingAnchorType.Position) {
+ validateCellPosition(placement.from);
+ validateExtent(placement.width, placement.height);
+ return;
+ }
+
+ if (placement.kind === SheetDrawingAnchorType.Both) {
+ validateCellPosition(placement.from);
+ validateCellPosition(placement.to);
+ return;
+ }
+
+ if (placement.kind === SheetDrawingAnchorType.None) {
+ if (!Number.isFinite(placement.left) || !Number.isFinite(placement.top)) {
+ throw new TypeError('SHEET_DRAWING_PLACEMENT_POSITION_INVALID');
+ }
+ validateExtent(placement.width, placement.height);
+ return;
+ }
+
+ throw new Error('SHEET_DRAWING_PLACEMENT_KIND_INVALID');
+}
+
+function validateBounds(bounds: IGroupBaseBound): void {
+ if (!Number.isFinite(bounds.left) || !Number.isFinite(bounds.top)) {
+ throw new TypeError('SHEET_DRAWING_PLACEMENT_POSITION_INVALID');
+ }
+ validateExtent(bounds.width, bounds.height);
+}
+
+function validateCellPosition(position: ICellOverGridPosition): void {
+ if (
+ !Number.isInteger(position.row) ||
+ !Number.isInteger(position.column) ||
+ position.row < 0 ||
+ position.column < 0 ||
+ !Number.isFinite(position.rowOffset) ||
+ !Number.isFinite(position.columnOffset)
+ ) {
+ throw new Error('SHEET_DRAWING_PLACEMENT_CELL_INVALID');
+ }
+}
+
+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');
+ }
+}
diff --git a/packages/sheets-drawing/src/services/sheet-drawing.service.ts b/packages/sheets-drawing/src/services/sheet-drawing.service.ts
index 46e9028acb..385692fc4c 100644
--- a/packages/sheets-drawing/src/services/sheet-drawing.service.ts
+++ b/packages/sheets-drawing/src/services/sheet-drawing.service.ts
@@ -15,7 +15,7 @@
*/
import type { IDrawingParam, IRotationSkewFlipTransform, Serializable } from '@univerjs/core';
-import type { IImageData, IUnitDrawingService } from '@univerjs/drawing';
+import type { IDrawingJsonUndo1, IImageData, IUnitDrawingService } from '@univerjs/drawing';
import type { ISheetOverGridPosition } from '@univerjs/sheets';
import { createIdentifier } from '@univerjs/core';
import { UnitDrawingService } from '@univerjs/drawing';
@@ -81,6 +81,8 @@ export type ISheetUpdateDrawing = OptionalField<ISheetImage | ISheetShape, 'shee
export class SheetDrawingService extends UnitDrawingService<ISheetDrawing> { }
-export interface ISheetDrawingService extends IUnitDrawingService<ISheetDrawing> { }
+export interface ISheetDrawingService extends IUnitDrawingService<ISheetDrawing> {
+ getBatchUpdateOp(updateParams: ISheetDrawing[]): IDrawingJsonUndo1;
+}
export const ISheetDrawingService = createIdentifier<ISheetDrawingService>('sheets-drawing.sheet-drawing.service');