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(drawing): keep controls and sheet objects reachable (#8096)

白熱353d66c03d66
diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.ts
index d5d4e96f03..efc58d7222 100644
--- a/packages/drawing-ui/src/index.ts
+++ b/packages/drawing-ui/src/index.ts
@@ -82,9 +82,6 @@ export {
ObjectListPanelBase,
} from './views/object-list-panel/ObjectListPanelBase';
export type {
- IDrawingObjectListItem,
- IDrawingObjectListPanelLabels,
- IDrawingObjectListPanelProps,
IObjectListPanelBaseProps,
IObjectListPanelItem,
IObjectListPanelLabels,
diff --git a/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx b/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx
index 309a6fb400..d74a1b139d 100644
--- a/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx
@@ -18,7 +18,7 @@ import type { ComponentProps } from 'react';
import { Button, clsx, Input, StateIconButton } from '@univerjs/design';
import { ArrowDownIcon, ArrowUpIcon, EyeIcon, EyelashIcon, LocateFixedIcon, LockIcon, MoreDownIcon, UnlockIcon } from '@univerjs/icons';
import type { IObjectListPanelBaseProps, IObjectListRowProps } from './ObjectListPanelBase';
-import { hasCapability, ObjectDetailsEditor, useObjectListPanel, useObjectListRow } from './ObjectListPanelBase';
+import { hasCapability, ObjectDetailsEditor, useObjectListPanel } from './ObjectListPanelBase';
const mobileIconButtonClassName = `
univer-flex univer-size-11 univer-shrink-0 univer-items-center univer-justify-center univer-rounded-xl
@@ -230,7 +230,7 @@ export function MobileObjectListPanel(props: IObjectListPanelBaseProps) {
labels={labels}
permissionAction={renderPermissionAction?.(item)}
showLock={!!onToggleSelectable && hasCapability(capabilities, item, 'selectable')}
- showName={hasCapability(capabilities, item, 'name')}
+
showVisible={hasCapability(capabilities, item, 'visible')}
draggable={canReorder && hasCapability(capabilities, item, 'reorder') && !item.disabled && item.canReorder !== false}
dragging={draggingId === item.id}
@@ -238,7 +238,7 @@ export function MobileObjectListPanel(props: IObjectListPanelBaseProps) {
onToggleExpanded={() => onToggleExpanded?.(item.id)}
onToggleVisible={() => onSetVisible([item.id], !item.visible)}
onToggleSelectable={() => onToggleSelectable?.(item.id)}
- onCommitName={(value) => onCommitName(item.id, value)}
+
onDragStart={() => setDraggingId(item.id)}
onDragEnd={() => setDraggingId(null)}
onDrop={() => handleDrop(item.id)}
@@ -265,8 +265,10 @@ export function MobileObjectListPanel(props: IObjectListPanelBaseProps) {
}
function MobileObjectListRow(props: IObjectListRowProps) {
- const { item, selected, labels, showLock, showName, showVisible, permissionAction, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable } = props;
- const { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown } = useObjectListRow(props);
+ const { item, selected, labels, showLock, showVisible, permissionAction, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable } = props;
+ const disabled = item.disabled === true;
+ const level = item.level ?? 0;
+ const locked = item.selectable === false;
return (
<div
className={clsx(`
@@ -302,25 +304,21 @@ function MobileObjectListRow(props: IObjectListRowProps) {
</button>
)
: <span className="univer-w-2 univer-shrink-0" />}
- {showName
- ? (
- <MobileObjectListInput
- className="univer-w-0 univer-min-w-0 univer-flex-1"
- value={draftName}
- disabled={disabled}
- aria-label={labels.nameInput}
- onChange={setDraftName}
- onBlur={handleBlur}
- onKeyDown={handleKeyDown}
- onClick={(event) => {
- event.stopPropagation();
- if (!disabled) {
- onSelect(false);
- }
- }}
- />
- )
- : <span className="univer-min-w-0 univer-flex-1 univer-truncate univer-text-sm">{item.name}</span>}
+ <button
+ type="button"
+ className="
+ univer-min-h-10 univer-min-w-0 univer-flex-1 univer-truncate univer-border-0 univer-bg-transparent
+ univer-px-1 univer-text-start univer-text-base univer-text-inherit
+ "
+ disabled={disabled}
+ aria-pressed={selected}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(false);
+ }}
+ >
+ {item.name}
+ </button>
{permissionAction}
{showLock && (
<StateIconButton
diff --git a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
index 792ebf016b..810beb0119 100644
--- a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ComponentProps, ComponentType, DragEvent, FocusEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';
+import type { ComponentProps, ComponentType, DragEvent, MouseEvent, ReactNode } from 'react';
import { Button, clsx, Input, StateIconButton, Textarea } from '@univerjs/design';
import {
ArrowDownIcon,
@@ -26,7 +26,7 @@ import {
MoreDownIcon,
UnlockIcon,
} from '@univerjs/icons';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useMemo, useState } from 'react';
import { OBJECT_LIST_CANVAS_SECTION_ID, OBJECT_LIST_FLOATING_SECTION_ID } from './object-list-panel-layer';
export interface IObjectListPanelCapabilities {
@@ -497,7 +497,6 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
labels={labels}
permissionAction={renderPermissionAction?.(item)}
showLock={!!onToggleSelectable && hasCapability(capabilities, item, 'selectable')}
- showName={hasCapability(capabilities, item, 'name')}
showVisible={hasCapability(capabilities, item, 'visible')}
draggable={canReorder && hasCapability(capabilities, item, 'reorder') && !item.disabled && item.canReorder !== false}
dragging={draggingId === item.id}
@@ -505,7 +504,6 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
onToggleExpanded={() => onToggleExpanded?.(item.id)}
onToggleVisible={() => onSetVisible([item.id], !item.visible)}
onToggleSelectable={() => onToggleSelectable?.(item.id)}
- onCommitName={(value) => onCommitName(item.id, value)}
onDragStart={() => setDraggingId(item.id)}
onDragEnd={() => setDraggingId(null)}
onDrop={() => handleDrop(item.id)}
@@ -535,7 +533,6 @@ export interface IObjectListRowProps {
selected: boolean;
labels: IObjectListPanelLabels;
showLock: boolean;
- showName: boolean;
showVisible: boolean;
draggable: boolean;
dragging: boolean;
@@ -543,15 +540,16 @@ export interface IObjectListRowProps {
onToggleExpanded: () => void;
onToggleVisible: () => void;
onToggleSelectable: () => void;
- onCommitName: (value: string) => void;
onDragStart: () => void;
onDragEnd: () => void;
onDrop: () => void;
}
function ObjectListRow(props: IObjectListRowProps) {
- const { permissionAction, item, selected, labels, showLock, showName, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onDragStart, onDragEnd, onDrop } = props;
- const { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown } = useObjectListRow(props);
+ const { permissionAction, item, selected, labels, showLock, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onDragStart, onDragEnd, onDrop } = props;
+ const disabled = item.disabled === true;
+ const level = item.level ?? 0;
+ const locked = item.selectable === false;
return (
<div
@@ -629,46 +627,21 @@ function ObjectListRow(props: IObjectListRowProps) {
</button>
)
: <span className="univer-size-5 univer-shrink-0" />}
- {showName
- ? (
- <Input
- key={item.name}
- className={clsx('univer-h-7 univer-w-0 univer-min-w-0 univer-flex-1', disabled && `
- univer-cursor-not-allowed
- `)}
- inputClass={clsx(
- `
- univer-min-w-0 univer-overflow-hidden univer-text-ellipsis univer-whitespace-nowrap
- !univer-rounded !univer-border-transparent !univer-bg-transparent !univer-px-1
- univer-text-sm univer-text-gray-900 !univer-shadow-none
- focus:!univer-border-primary-500 focus:!univer-bg-gray-0 focus:!univer-ring-1
- focus:!univer-ring-primary-100
- disabled:!univer-bg-transparent disabled:univer-opacity-100
- dark:!univer-text-gray-100
- dark:focus:!univer-bg-gray-900 dark:focus:!univer-ring-primary-900
- `,
- '!univer-h-7',
- disabled && `
- univer-text-gray-400
- dark:!univer-text-gray-500
- `
- )}
- inputStyle={{ maxWidth: '100%', boxSizing: 'border-box' }}
- value={draftName}
- disabled={disabled}
- aria-label={labels.nameInput}
- onChange={setDraftName}
- onBlur={handleBlur}
- onKeyDown={handleKeyDown}
- onClick={(event) => {
- event.stopPropagation();
- if (!disabled) {
- onSelect(event.ctrlKey || event.metaKey);
- }
- }}
- />
- )
- : <span className="univer-min-w-0 univer-flex-1 univer-truncate univer-px-1 univer-text-sm">{item.name}</span>}
+ <button
+ type="button"
+ className="
+ univer-h-7 univer-min-w-0 univer-flex-1 univer-truncate univer-border-0 univer-bg-transparent
+ univer-px-1 univer-text-start univer-text-sm univer-text-inherit
+ "
+ disabled={disabled}
+ aria-pressed={selected}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(event.ctrlKey || event.metaKey);
+ }}
+ >
+ {item.name}
+ </button>
{permissionAction}
{showLock && (
<StateIconButton
@@ -720,15 +693,8 @@ export function ObjectDetailsEditor(props: {
onCommitDescription: (value: string) => void;
}) {
const { item, InputComponent = Input, descriptionClassName, labels, showName, showDescription, onCommitName, onCommitDescription } = props;
- const [draftName, setDraftName] = useState(item?.name ?? '');
- const [draftDescription, setDraftDescription] = useState(item?.description ?? '');
const disabled = item?.disabled === true;
- useEffect(() => {
- setDraftName(item?.name ?? '');
- setDraftDescription(item?.description ?? '');
- }, [item?.description, item?.id, item?.name]);
-
if (!item) {
return (
<div
@@ -770,13 +736,13 @@ export function ObjectDetailsEditor(props: {
{labels.name}
</span>
<InputComponent
- value={draftName}
+ key={JSON.stringify([item.id, item.name])}
+ defaultValue={item.name}
aria-label={labels.nameInput}
disabled={disabled}
- onChange={setDraftName}
- onBlur={() => {
- if (!disabled && normalizeText(draftName) !== item.name) {
- onCommitName(draftName);
+ onBlur={(event) => {
+ if (!disabled && normalizeText(event.currentTarget.value) !== item.name) {
+ onCommitName(event.currentTarget.value);
}
}}
onKeyDown={(event) => {
@@ -799,14 +765,14 @@ export function ObjectDetailsEditor(props: {
</span>
<Textarea
className={clsx('univer-min-h-16 univer-resize-none univer-text-sm', descriptionClassName)}
- value={draftDescription}
+ key={JSON.stringify([item.id, item.description])}
+ defaultValue={item.description ?? ''}
disabled={disabled}
placeholder={labels.descriptionPlaceholder}
aria-label={labels.description}
- onChange={(event) => setDraftDescription(event.currentTarget.value)}
- onBlur={() => {
- if (!disabled && normalizeText(draftDescription) !== (item.description ?? '')) {
- onCommitDescription(draftDescription);
+ onBlur={(event) => {
+ if (!disabled && normalizeText(event.currentTarget.value) !== (item.description ?? '')) {
+ onCommitDescription(event.currentTarget.value);
}
}}
/>
@@ -815,45 +781,3 @@ export function ObjectDetailsEditor(props: {
</div>
);
}
-
-export type IDrawingObjectListItem = IObjectListPanelItem;
-export type IDrawingObjectListPanelLabels = IObjectListPanelLabels;
-export type IDrawingObjectListPanelProps = IObjectListPanelBaseProps;
-export function useObjectListRow({ item, onCommitName }: Pick<IObjectListRowProps, 'item' | 'onCommitName'>) {
- const [draftName, setDraftName] = useState(item.name);
- const skipCommitOnBlurRef = useRef(false);
- const disabled = item.disabled === true;
- const level = item.level ?? 0;
- const locked = item.selectable === false;
-
- useEffect(() => {
- setDraftName(item.name);
- }, [item.name]);
-
- const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
- if (disabled) {
- return;
- }
- if (skipCommitOnBlurRef.current) {
- skipCommitOnBlurRef.current = false;
- return;
- }
- if (event.currentTarget.value !== item.name) {
- onCommitName(event.currentTarget.value);
- }
- };
-
- const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- if (event.key === 'Enter') {
- event.currentTarget.blur();
- return;
- }
- if (event.key === 'Escape') {
- skipCommitOnBlurRef.current = true;
- setDraftName(item.name);
- event.currentTarget.blur();
- }
- };
-
- return { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown };
-}
diff --git a/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
index d32e162817..a245e7acd7 100644
--- a/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
@@ -16,12 +16,12 @@
import type { ReactElement } from 'react';
import type { Root } from 'react-dom/client';
-import type { IObjectListPanelBaseProps, IObjectListPanelItem } from '../ObjectListPanelBase';
import { LocaleService, LocaleType, Univer } from '@univerjs/core';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IObjectListPanelBaseProps, IObjectListPanelItem } from '../ObjectListPanelBase';
import enUS from '../../../locale/en-US';
import { MobileObjectListPanel } from '../MobileObjectListPanel';
import { ObjectListPanelBase } from '../ObjectListPanelBase';
@@ -90,6 +90,31 @@ describe.each([
);
}
+ it('selects an object without focusing a name editor and renames it through details', async () => {
+ const onSelect = vi.fn();
+ const onCommitName = vi.fn();
+ const item = { id: 'a', name: 'Offscreen shape', visible: true };
+ const view = await render(panel([item], { onSelect, onCommitName }));
+ const button = getButton(item.name);
+ await act(async () => {
+ button.focus();
+ button.click();
+ });
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith('a', false);
+ expect(document.activeElement).toBe(button);
+ expect(container.querySelector('input[aria-label="Object name"]')).toBeNull();
+
+ await view.rerender(panel([item], { onSelect, onCommitName, selectedIds: ['a'] }));
+ const input = container.querySelector<HTMLInputElement>('input[aria-label="Object name"]')!;
+ await act(async () => {
+ input.focus();
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'Recovered shape');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => input.blur());
+ expect(onCommitName).toHaveBeenCalledExactlyOnceWith('a', 'Recovered shape');
+ });
+
it('switches both bulk actions from current model state, including external updates', async () => {
const original = [{ id: 'a', name: 'A', visible: true }, { id: 'b', name: 'B', visible: true }];
const view = await render(panel(original));
@@ -156,6 +181,6 @@ describe.each([
await act(async () => description.blur());
expect(onCommitDescription).toHaveBeenCalledExactlyOnceWith('a', 'New description');
await view.rerender(panel([{ ...item, description: 'External update' }], props));
- expect(description.value).toBe('External update');
+ expect(container.querySelector('textarea')!.value).toBe('External update');
});
});
diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
index 0122bfa1a3..c8e2f0a8f2 100644
--- a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
@@ -22,8 +22,6 @@ import { Vector2 } from '../basics/vector2';
import { Engine } from '../engine';
import { Group } from '../group';
import { MAIN_VIEW_PORT_KEY, Scene } from '../scene';
-import { Transformer } from '../scene.transformer';
-import { Line } from '../shape/line';
import { Rect } from '../shape/rect';
import { ScrollBar } from '../shape/scroll-bar';
import { Viewport } from '../viewport';
@@ -715,514 +713,6 @@ describe('engine scene viewport extra', () => {
engine.dispose();
});
- it('covers transformer geometry and state helper branches', () => {
- const sceneMock = {
- ancestorScaleX: 2,
- ancestorScaleY: 4,
- ancestorLeft: 6,
- ancestorTop: 8,
- getEngine: () => ({ activeScene: null }),
- } as any;
-
- const transformer = new Transformer(sceneMock, {
- anchorSize: 12,
- borderSpacing: 2,
- rotateAnchorOffset: 20,
- rotateSize: 10,
- });
-
- const changingSpy = vi.fn();
- transformer.changing$.subscribe(changingSpy);
- (transformer as any)._selectedObjectMap.set('s1', { oKey: 's1', dispose: vi.fn() });
- transformer.changeNotification();
- expect(changingSpy).toHaveBeenCalled();
-
- transformer.updateZeroPoint(1, 2);
- expect(transformer.zeroLeft).toBe(1);
- expect(transformer.zeroTop).toBe(2);
-
- const moveBoundary = (transformer as any)._checkMoveBoundary(
- { left: 5, top: 5, width: 20, height: 10 },
- -100,
- -100,
- 0,
- 0,
- 200,
- 100
- );
- expect(moveBoundary.moveLeft).toBeLessThanOrEqual(0);
- expect(moveBoundary.moveTop).toBeLessThanOrEqual(0);
-
- const freeMoveTransformer = new Transformer(sceneMock, {
- moveBoundaryEnabled: false,
- } as any);
- const freeMoveBoundary = (freeMoveTransformer as any)._checkMoveBoundary(
- {
- left: 820,
- top: -28,
- width: 520,
- height: 520,
- },
- 0,
- 40,
- 0,
- 0,
- 1280,
- 720
- );
- expect(freeMoveBoundary.moveLeft).toBe(0);
- expect(freeMoveBoundary.moveTop).toBe(40);
-
- (transformer as any)._startOffsetX = 10;
- (transformer as any)._startOffsetY = 10;
- expect((transformer as any)._moveBufferBlocker(11, 11)).toBe(true);
- expect((transformer as any)._moveBufferBlocker(30, 30)).toBe(false);
-
- const movePoint = (transformer as any)._getMovePoint(40, 60, {
- left: 10,
- top: 20,
- width: 80,
- height: 40,
- angle: 30,
- });
- expect(Number.isFinite(movePoint.moveLeft)).toBe(true);
- expect(Number.isFinite(movePoint.moveTop)).toBe(true);
-
- const rotateFixed = (transformer as any)._applyRotationForResult(
- { left: 10, top: 20, width: 50, height: 30 },
- { left: 0, top: 0, width: 40, height: 20 },
- 25
- );
- expect(rotateFixed.width).toBeGreaterThan(0);
- expect(rotateFixed.height).toBeGreaterThan(0);
-
- const noRotate = (transformer as any)._applyRotationForResult(
- { left: 1, top: 2, width: 3, height: 4 },
- { left: 0, top: 0, width: 0, height: 0 },
- 0
- );
- expect(noRotate).toEqual({ left: 1, top: 2, width: 3, height: 4 });
-
- const ltState = (transformer as any)._updateCloseKeepRatioState('__SpreadsheetTransformerResizeLT__', 10, 10, 60, 40, 55, 30);
- const rbState = (transformer as any)._updateCloseKeepRatioState('__SpreadsheetTransformerResizeRB__', 10, 10, 60, 40, -100, -100);
- expect(ltState.width).toBeGreaterThanOrEqual(20);
- expect(rbState.height).toBeGreaterThanOrEqual(20);
-
- const limited = (transformer as any)._getLimitedSize(120, 60);
- expect(limited.limitWidth).toBeGreaterThan(20);
- expect(limited.limitHeight).toBe(20);
-
- const ltFix = (transformer as any)._fixMoveLtRb(10, 2, 100, 50, 2);
- const lbFix = (transformer as any)._fixMoveLbRt(10, 2, 100, 50, 2);
- expect(Number.isFinite(ltFix.moveLeft)).toBe(true);
- expect(Number.isFinite(lbFix.moveTop)).toBe(true);
-
- const moveObject = {
- left: 10,
- top: 20,
- width: 100,
- height: 60,
- getState: () => ({ left: 10, top: 20, width: 100, height: 60 }),
- } as any;
- expect((transformer as any)._resizeLeftTop(moveObject, 5, 3, { width: 100, height: 60 }).width).toBeGreaterThan(0);
- expect((transformer as any)._resizeRightTop(moveObject, 5, 3, { width: 100, height: 60 }).height).toBeGreaterThan(0);
- expect((transformer as any)._resizeLeftBottom(moveObject, 5, 3, { width: 100, height: 60 }).width).toBeGreaterThan(0);
- expect((transformer as any)._resizeRightBottom(moveObject, 5, 3, { width: 100, height: 60 }).height).toBeGreaterThan(0);
-
- const recoveryTarget = {
- left: -4,
- top: -3,
- width: 20,
- height: 10,
- transformByState: vi.fn(),
- };
- (transformer as any)._recoverySizeBoundary([recoveryTarget], 0, 0, 100, 80);
- expect(recoveryTarget.transformByState).toHaveBeenCalled();
- recoveryTarget.transformByState.mockClear();
- (freeMoveTransformer as any)._recoverySizeBoundary([recoveryTarget], 0, 0, 100, 80);
- expect(recoveryTarget.transformByState).not.toHaveBeenCalled();
-
- expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerResizeLM__')).toBe(CURSOR_TYPE.WEST_RESIZE);
- expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerResizeCB__')).toBe(CURSOR_TYPE.SOUTH_RESIZE);
- expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerRotate__')).toBe(CURSOR_TYPE.MOVE);
- expect((transformer as any)._getRotateAnchorPosition('__SpreadsheetTransformerRotate__', 40, 100, { transformerConfig: {} })).toEqual({
- left: 45,
- top: 64,
- });
- expect((transformer as any)._getRotateAnchorPosition('__SpreadsheetTransformerRotate__', 40, 100, {
- transformerConfig: {
- rotateAnchorPosition: 'bottom',
- rotateSize: 16,
- },
- })).toEqual({
- left: 42,
- top: 64,
- });
- expect((transformer as any)._getRotateAnchorPosition('__SpreadsheetTransformerRotateLine__', 40, 100, {
- transformerConfig: {
- rotateAnchorPosition: 'bottom',
- },
- })).toEqual({
- left: 50,
- top: 43,
- });
- expect((transformer as any)._checkTransformerType('__SpreadsheetTransformerResizeRT__123')).toBe('__SpreadsheetTransformerResizeRT__');
- expect((transformer as any)._getNorthEastPoints(10, 4)[0]).toHaveLength(6);
- expect((transformer as any)._getNorthWestPoints(10, 4)[0]).toHaveLength(6);
- expect((transformer as any)._getSouthEastPoints(10, 4)[0]).toHaveLength(7);
- expect((transformer as any)._getSouthWestPoints(10, 4)[0]).toHaveLength(7);
- expect((transformer as any)._smoothAccuracy(1.23456)).toBe(1.2);
- expect((transformer as any)._smoothAccuracy(1.23456, true)).toBe(1.235);
-
- transformer.dispose();
- });
-
- it('positions transformer controls symmetrically around object bounds', () => {
- const transformer = new Transformer({
- getEngine: () => ({ activeScene: null }),
- } as any, {
- anchorSize: 8,
- anchorStyle: 'canva',
- borderSpacing: 2,
- borderStrokeWidth: 1,
- });
-
- const outline = new Rect('outline', {
- ...(transformer as any)._getOutlinePosition(100, 50, 2, 1),
- strokeWidth: 1,
- });
- expect(outline.getState()).toEqual(expect.objectContaining({
- left: -3.5,
- top: -3.5,
- width: 106,
- height: 56,
- }));
- const outlineMatrix = outline.transform.getMatrix();
- expect([
- outlineMatrix[4],
- outlineMatrix[5],
- outlineMatrix[4] + outline.width,
- outlineMatrix[5] + outline.height,
- ]).toEqual([-3, -3, 103, 53]);
-
- const applyObject = {
- getState: () => ({ width: 100, height: 50 }),
- transformerConfig: {
- anchorSize: 8,
- anchorStyle: 'canva',
- borderSpacing: 2,
- borderStrokeWidth: 1,
- },
- };
- const anchorTypes = [
- '__SpreadsheetTransformerResizeLT__',
- '__SpreadsheetTransformerResizeCT__',
- '__SpreadsheetTransformerResizeRT__',
- '__SpreadsheetTransformerResizeLM__',
- '__SpreadsheetTransformerResizeRM__',
- '__SpreadsheetTransformerResizeLB__',
- '__SpreadsheetTransformerResizeCB__',
- '__SpreadsheetTransformerResizeRB__',
- ];
- const anchorCenters = anchorTypes.map((type) => {
- const anchor = (transformer as any)._createResizeAnchor(type, applyObject, 1) as Rect;
- const matrix = anchor.transform.getMatrix();
- return [matrix[4] + anchor.width / 2, matrix[5] + anchor.height / 2];
- });
-
- expect(anchorCenters).toEqual([
- [-3, -3],
- [50, -3],
- [103, -3],
- [-3, 25],
- [103, 25],
- [-3, 53],
- [50, 53],
- [103, 53],
- ]);
-
- transformer.dispose();
- });
-
- it('supports bottom rotate control without a connector line', () => {
- const { engine, scene } = createFixture();
- engine.setActiveScene(scene.sceneKey);
-
- const rect = scene.getObject('rect-main') as Rect;
- rect.transformerConfig = {
- rotateAnchorPosition: 'bottom',
- rotateLineEnabled: false,
- rotateIconEnabled: true,
- };
- const transformer = new Transformer(scene, {
- rotateEnabled: true,
- resizeEnabled: true,
- borderEnabled: true,
- });
-
- transformer.setSelectedControl(rect);
- const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;
- const controlObjects = control.getObjects();
-
- expect(controlObjects.some((o) => o.oKey.includes('__SpreadsheetTransformerRotateLine__'))).toBe(false);
- expect(controlObjects.some((o) => o.oKey.includes('_ICON_'))).toBe(true);
-
- transformer.dispose();
- scene.dispose();
- engine.dispose();
- });
-
- it('renders controls from resolved display geometry without changing the selected object', () => {
- const { engine, scene } = createFixture();
- engine.setActiveScene(scene.sceneKey);
-
- const rect = scene.getObject('rect-main');
- if (!(rect instanceof Rect)) {
- throw new TypeError('Fixture should contain the main rectangle');
- }
- rect.transformerConfig = {
- keepRatio: false,
- controlStateResolver: (object) => ({
- ...object.getState(),
- left: object.left - 8,
- top: object.top - 6,
- width: object.width + 24,
- height: object.height + 18,
- }),
- };
- const transformer = new Transformer(scene);
-
- transformer.setSelectedControl(rect);
- const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`);
- if (!(control instanceof Group)) {
- throw new TypeError('Transformer should create a control group');
- }
-
- expect(control.getState()).toEqual(expect.objectContaining({
- left: 2,
- top: 4,
- width: 124,
- height: 78,
- }));
- expect(rect.getState()).toEqual(expect.objectContaining({
- left: 10,
- top: 10,
- width: 100,
- height: 60,
- }));
-
- rect.translate(30, 40);
- transformer.updateControl();
- expect(control.getState()).toEqual(expect.objectContaining({
- left: 22,
- top: 34,
- width: 124,
- height: 78,
- }));
-
- const resizeAnchor = control.getObjects().find((object) => object.oKey.includes('__SpreadsheetTransformerResizeRB__'));
- if (!resizeAnchor) {
- throw new TypeError('Transformer should create a bottom-right resize anchor');
- }
- resizeAnchor.triggerPointerDown(createInputEvent('pointerdown', { offsetX: 146, offsetY: 112 }));
- scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 186, offsetY: 137 }));
- scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 186, offsetY: 137 }));
- expect(rect.getState()).toEqual(expect.objectContaining({
- width: 140,
- height: 85,
- }));
-
- transformer.dispose();
- scene.dispose();
- engine.dispose();
- });
-
- it('insets the icon inside a small rotate control and matches the connector to its border', () => {
- const { engine, scene } = createFixture();
- engine.setActiveScene(scene.sceneKey);
-
- const rect = scene.getObject('rect-main') as Rect;
- rect.transformerConfig = {
- rotateAnchorPosition: 'bottom',
- rotateAnchorOffset: 20,
- rotateLineEnabled: true,
- rotateSize: 14,
- rotateCornerRadius: 4,
- rotateStroke: '#d1d5db',
- rotateIconEnabled: true,
- };
- const transformer = new Transformer(scene, {
- rotateEnabled: true,
- resizeEnabled: true,
- borderEnabled: true,
- });
-
- transformer.setSelectedControl(rect);
- const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;
- const controlObjects = control.getObjects();
- const rotateLine = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotateLine__'));
- const rotate = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotate__') && !o.oKey.includes('_ICON_')) as Rect;
- const rotateIcon = controlObjects.find((o) => o.oKey.includes('_ICON_')) as Rect;
-
- expect(rotateLine).toBeInstanceOf(Line);
- if (!(rotateLine instanceof Line)) {
- throw new TypeError('Rotate line should use the Line render primitive');
- }
-
- expect(rotateLine.stroke).toBe('#d1d5db');
- expect(rotateLine.startX).toBe(rotateLine.endX);
- expect(rotateLine.endY - rotateLine.startY).toBe(20);
- expect(rotateLine.startX).toBe(rotate.left + rotate.width / 2);
- expect(rotate.radius).toBe(4);
- expect(rotateIcon.width).toBe(10);
- expect(rotateIcon.height).toBe(10);
-
- transformer.dispose();
- scene.dispose();
- engine.dispose();
- });
-
- it('expands transformer outline symmetrically when border spacing is configured', () => {
- const { engine, scene } = createFixture();
- const rect = scene.getObject('rect-main') as Rect;
- rect.transformerConfig = {
- borderSpacing: 6,
- borderStrokeWidth: 1,
- anchorStyle: 'canva',
- anchorSize: 8,
- };
- const transformer = new Transformer(scene);
-
- expect((transformer as any)._getOutlinePosition(100, 40, 6, 1)).toEqual({
- left: -7.5,
- top: -7.5,
- width: 114,
- height: 54,
- });
-
- transformer.setSelectedControl(rect);
- const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;
- const controlObjects = control.getObjects();
- const outline = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerOutline__')) as Rect;
- const leftMiddle = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerResizeLM__')) as Rect;
-
- const outlineMatrix = outline.transform.getMatrix();
- const leftMiddleMatrix = leftMiddle.transform.getMatrix();
- expect(outlineMatrix[4]).toBe(-7);
- expect(leftMiddleMatrix[4] + leftMiddle.width / 2).toBe(outlineMatrix[4]);
-
- transformer.dispose();
- scene.dispose();
- engine.dispose();
- });
-
- it('rotates around the scene center when the scene is scaled', () => {
- const sceneMock = {
- ancestorScaleX: 2,
- ancestorScaleY: 2,
- } as any;
- const transformer = new Transformer(sceneMock);
- const transformByState = vi.fn();
-
- (transformer as any)._selectedObjectMap.set('s1', {
- oKey: 's1',
- transformByState,
- dispose: vi.fn(),
- });
- (transformer as any)._moveBufferSkip = true;
- (transformer as any)._viewportScrollX = 0;
- (transformer as any)._viewportScrollY = 0;
- (transformer as any)._startOffsetX = 200;
- (transformer as any)._startOffsetY = 240;
-
- (transformer as any)._rotateMoving(240, 200, 100, 100, 0);
-
- expect(transformByState).toHaveBeenCalledWith({ angle: 270 });
- transformer.dispose();
- });
-
- it('covers transformer attach, controls, resize and rotate flows', () => {
- const { engine, scene } = createFixture();
- engine.setActiveScene(scene.sceneKey);
-
- const rect = scene.getObject('rect-main') as Rect;
- const transformer = new Transformer(scene, {
- rotateEnabled: true,
- resizeEnabled: true,
- enabledAnchors: [1, 1, 1, 1, 1, 1, 1, 1],
- borderEnabled: true,
- });
-
- const startSpy = vi.fn();
- const changingSpy = vi.fn();
- const endSpy = vi.fn();
- transformer.changeStart$.subscribe(startSpy);
- transformer.changing$.subscribe(changingSpy);
- transformer.changeEnd$.subscribe(endSpy);
-
- transformer.attachTo(rect);
- (rect.onPointerDown$ as any).emitEvent(
- createInputEvent('pointerdown', { offsetX: 20, offsetY: 20 }),
- { stopPropagation: vi.fn() }
- );
- scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 80, offsetY: 60 }));
- scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 80, offsetY: 60 }));
- expect(startSpy).toHaveBeenCalled();
- expect(changingSpy).toHaveBeenCalled();
- expect(endSpy).toHaveBeenCalled();
-
- transformer.setSelectedControl(rect);
- const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;
- expect(control).toBeTruthy();
- const allControlObjects = control.getObjects();
-
- const resizeAnchor = allControlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerResizeRB__')) as Rect;
- (resizeAnchor.onPointerDown$ as any).emitEvent(
- createInputEvent('pointerdown', { offsetX: 26, offsetY: 26 }),
- { stopPropagation: vi.fn() }
- );
- scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 96, offsetY: 92 }));
- scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 96, offsetY: 92 }));
-
- const rotateAnchor = allControlObjects.find(
- (o) => o.oKey.includes('__SpreadsheetTransformerRotate__') && !o.oKey.includes('LINE')
- ) as Rect | undefined;
- if (rotateAnchor) {
- (rotateAnchor.onPointerDown$ as any).emitEvent(
- createInputEvent('pointerdown', { offsetX: 30, offsetY: 8 }),
- { stopPropagation: vi.fn() }
- );
- scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 120, offsetY: 90 }));
- scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 120, offsetY: 90 }));
- } else {
- (transformer as any)._moveBufferSkip = true;
- (transformer as any)._startOffsetX = 30;
- (transformer as any)._startOffsetY = 8;
- (transformer as any)._viewportScrollX = 0;
- (transformer as any)._viewportScrollY = 0;
- (transformer as any)._rotateMoving(120, 90, 60, 40, 0);
- }
-
- expect(rect.width).toBeGreaterThan(0);
- expect(rect.height).toBeGreaterThan(0);
- expect(rect.angle).toBeGreaterThanOrEqual(0);
-
- transformer.clearControlByIds([rect.oKey]);
- rect.transformerConfig = {
- isCropper: true,
- resizeEnabled: true,
- enabledAnchors: [1, 1, 1, 1, 1, 1, 1, 1],
- } as any;
- transformer.createControlForCopper(rect);
- expect((transformer as any)._copperControl).toBeTruthy();
- transformer.clearCopperControl();
-
- transformer.clearSelectedObjects();
- transformer.dispose();
- scene.dispose();
- engine.dispose();
- });
-
it('covers scene/viewport utility and early-return branches', () => {
const { engine, scene, viewport } = createFixture();
diff --git a/packages/engine-render/src/__tests__/scene.spec.ts b/packages/engine-render/src/__tests__/scene.spec.ts
new file mode 100644
index 0000000000..0173cd4b9c
--- /dev/null
+++ b/packages/engine-render/src/__tests__/scene.spec.ts
@@ -0,0 +1,88 @@
+/**
+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { Engine } from '../engine';
+import { Scene } from '../scene';
+import { Rect } from '../shape/rect';
+import { ScrollBar } from '../shape/scroll-bar';
+import { Viewport } from '../viewport';
+import { setupRenderTestEnv } from './render-test-utils';
+
+describe('Scene', () => {
+ const env = setupRenderTestEnv();
+ afterEach(() => env.restore());
+
+ it('preserves backgrounds painted by beforeRender subscribers after clearing the canvas', () => {
+ const engine = new Engine('background', { elementWidth: 300, elementHeight: 200, dpr: 1 });
+ const scene = new Scene('background', engine);
+ const viewport = new Viewport('main', scene, { left: 0, top: 0, width: 300, height: 200 });
+ scene.addObject(new Rect('object', { left: 100, top: 100, width: 20, height: 20 }));
+ const context = engine.getCanvas().getContext();
+ const clear = vi.spyOn(context, 'clearRect');
+ const fill = vi.spyOn(context, 'fillRect');
+ const subscription = scene.beforeRender$.subscribe((canvas) => {
+ if (canvas) {
+ context.fillStyle = '#ffffff';
+ context.fillRect(0, 0, 300, 200);
+ }
+ });
+ try {
+ scene.render();
+ expect(clear).toHaveBeenCalledWith(0, 0, 300, 200);
+ expect(fill).toHaveBeenCalledWith(0, 0, 300, 200);
+ expect(clear.mock.invocationCallOrder[0]).toBeLessThan(fill.mock.invocationCallOrder[0]);
+ } finally {
+ subscription.unsubscribe();
+ clear.mockRestore();
+ fill.mockRestore();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('clears the whole canvas when a prepare-render layout change invalidates a preserved scroll frame', () => {
+ const engine = new Engine('scene', { elementWidth: 500, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('scene', engine, { width: 1000, height: 1000 });
+ const viewport = new Viewport('main', scene, { left: 0, top: 0, width: 500, height: 400, allowCache: true });
+ const scrollbar = new ScrollBar(viewport);
+ const rect = new Rect('marker', { left: 100, top: 100, width: 30, height: 30 });
+ scene.addObject(rect);
+ scene.render();
+ let relayout = false;
+ const subscription = scene.prepareRender$.subscribe(() => {
+ if (relayout) {
+ rect.translate(150, 100);
+ scene.makeDirty();
+ }
+ });
+ const clear = vi.spyOn(engine.getCanvas().getContext(), 'clearRect');
+ try {
+ viewport.scrollToViewportPos({ viewportScrollY: 20 });
+ scene.makeDirtyForScrolling();
+ relayout = true;
+ scene.render();
+ expect(clear).toHaveBeenCalledWith(0, 0, 500, 400);
+ } finally {
+ clear.mockRestore();
+ subscription.unsubscribe();
+ scrollbar.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+});
diff --git a/packages/engine-render/src/__tests__/scene.transformer.spec.ts b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
index d06a3c92c9..d25fb163d2 100644
--- a/packages/engine-render/src/__tests__/scene.transformer.spec.ts
+++ b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
@@ -18,10 +18,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { DeviceType, PointerInput } from '../basics/i-events';
import { Vector2 } from '../basics/vector2';
import { Engine } from '../engine';
+import { Group } from '../group';
import { Scene } from '../scene';
import { Transformer } from '../scene.transformer';
import { Control } from '../shape/control';
+import { Line } from '../shape/line';
import { Rect } from '../shape/rect';
+import { ScrollBar } from '../shape/scroll-bar';
import { Viewport } from '../viewport';
import { setupRenderTestEnv } from './render-test-utils';
@@ -46,6 +49,15 @@ function createPointerEvent(type: string, offsetX: number, offsetY: number) {
return event;
}
+function createTransformerFixture() {
+ const engine = new Engine('transformer', { elementWidth: 500, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('transformer', engine, { width: 500, height: 400 });
+ const viewport = new Viewport('main', scene, { left: 0, top: 0, width: 500, height: 400 });
+ const rect = new Rect('rect-main', { left: 10, top: 10, width: 100, height: 60 });
+ scene.addObject(rect);
+ return { engine, scene, rect, viewport };
+}
+
describe('Transformer', () => {
const env = setupRenderTestEnv();
@@ -83,6 +95,442 @@ describe('Transformer', () => {
}
});
+ it.each([
+ { left: 120, top: 30, angle: 0, scale: 1 },
+ { left: 120, top: 66, angle: 0, scale: 1 },
+ { left: 120, top: 290, angle: 180, scale: 1 },
+ { left: 20, top: 160, angle: 90, scale: 1 },
+ { left: 340, top: 180, angle: 270, scale: 1 },
+ { left: 120, top: 20, angle: 30, scale: 0.5 },
+ { left: 40, top: 20, angle: 15, scale: 2 },
+ { left: -80, top: -60, angle: 0, scale: 1 },
+ ])('keeps rotation visible and clickable near viewport edges: %j', ({ left, top, angle, scale }) => {
+ const engine = new Engine('rotation-edge', { elementWidth: 500, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('rotation-edge', engine);
+ const viewport = new Viewport('main', scene, { left: 40, top: 20, width: 460, height: 380 });
+ scene.scale(scale, scale);
+ const rect = new Rect('edge-object', { left, top, width: 200, height: 120, angle });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateAnchorPosition: 'top' });
+ try {
+ transformer.setSelectedControl(rect);
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes('Rotate__'))!;
+ const center = viewport.getAbsoluteVector(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2)));
+ expect(anchor.visible).toBe(true);
+ expect(center.x - 22).toBeGreaterThanOrEqual(viewport.left + 7.9);
+ expect(center.y - 22).toBeGreaterThanOrEqual(viewport.top + 7.9);
+ expect(center.x + 22).toBeLessThanOrEqual(viewport.left + viewport.width! - 7.9);
+ expect(center.y + 22).toBeLessThanOrEqual(viewport.top + viewport.height! - 7.9);
+ expect(scene.pick(center, DeviceType.Mouse)).toBe(anchor);
+ expect(transformer.isPointOnControl(rect.oKey, center)).toBe(true);
+ expect(scene.pick(center, DeviceType.Touch)).toBe(anchor);
+ } finally {
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each([50, 200])('keeps the handle usable in the pane showing most of a frozen selection at x=%s', (left) => {
+ const engine = new Engine('frozen', { elementWidth: 600, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('frozen', engine, { width: 1000, height: 1000 });
+ const frozen = new Viewport('frozen', scene, { left: 40, top: 30, width: 200, height: 370 });
+ const main = new Viewport('main', scene, { left: 240, top: 30, width: 360, height: 370 });
+ const rect = new Rect('frozen-object', { left, top: 35, width: 200, height: 100 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateAnchorPosition: 'top' });
+ try {
+ transformer.setSelectedControl(rect);
+ const viewport = left === 50 ? frozen : main;
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes('Rotate__'))!;
+ const point = viewport.getAbsoluteVector(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2)));
+ expect(point.x - 22).toBeGreaterThanOrEqual(viewport.left + 8);
+ expect(point.x + 22).toBeLessThanOrEqual(viewport.left + viewport.width! - 8);
+ expect(point.y - 22).toBeGreaterThanOrEqual(viewport.top + 8);
+ expect(transformer.isPointOnControl(rect.oKey, point, DeviceType.Touch)).toBe(true);
+ if (left === 50) {
+ main.updateScrollVal({ viewportScrollY: 200 });
+ const clipped = main.getAbsoluteVector(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2)));
+ expect(clipped.y).toBeLessThan(0);
+ expect(transformer.isPointOnControl(rect.oKey, clipped)).toBe(false);
+ }
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('repositions after scrolling and zooming without changing the object or keeping the scene dirty', () => {
+ const engine = new Engine('rotation-scroll', { elementWidth: 500, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('rotation-scroll', engine, { width: 1000, height: 1000 });
+ const viewport = new Viewport('main', scene, { left: 40, top: 20, width: 460, height: 380 });
+ const scrollbar = new ScrollBar(viewport);
+ const rect = new Rect('object', { left: 120, top: 200, width: 200, height: 120 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateAnchorPosition: 'top', rotateIconEnabled: true });
+ try {
+ transformer.setSelectedControl(rect);
+ const initial = rect.getState();
+ viewport.scrollToViewportPos({ viewportScrollY: 190 });
+ for (const scale of [1, 1.5, 0.75]) {
+ scene.scale(scale, scale);
+ scene.render();
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes('Rotate__') && object instanceof Control)!;
+ const icon = (anchor.ancestorGroup as Group).getObjects().find((object) => object.oKey.includes('Rotate___ICON'))!;
+ const center = viewport.getAbsoluteVector(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2)));
+ expect(center.y - 22).toBeGreaterThanOrEqual(viewport.top + 7.9);
+ expect(center.y + 22).toBeLessThanOrEqual(viewport.top + viewport.height! - scrollbar.totalSize - 7.9);
+ expect(scene.pick(center, DeviceType.Touch)).toBe(anchor);
+ const iconCenter = viewport.getAbsoluteVector(icon.ancestorTransform.applyPoint(new Vector2(icon.width / 2, icon.height / 2)));
+ expect(iconCenter.x).toBeCloseTo(center.x);
+ expect(iconCenter.y).toBeCloseTo(center.y);
+ expect(rect.getState()).toEqual(initial);
+ expect(scene.isDirty()).toBe(false);
+ }
+ } finally {
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each([1, 2])('rotates from a relocated handle without jumping at scale %s', (scale) => {
+ const engine = new Engine('rotation-gesture', { elementWidth: 500, elementHeight: 400, dpr: 1 });
+ const scene = new Scene('rotation-gesture', engine, { width: 500, height: 400 });
+ const viewport = new Viewport('main', scene, { left: 0, top: 0, width: 500, height: 400 });
+ scene.scale(scale, scale);
+ const rect = new Rect('object', { left: 80, top: 10, width: 100, height: 60 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateAnchorPosition: 'top' });
+ try {
+ transformer.setSelectedControl(rect);
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes('Rotate__'))!;
+ const point = viewport.getAbsoluteVector(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2)));
+ const center = new Vector2((rect.left + rect.width / 2) * scale, (rect.top + rect.height / 2) * scale);
+ expect(point.y).toBeGreaterThan(rect.top + rect.height);
+ anchor.onPointerDown$.emitEvent(createPointerEvent('pointerdown', point.x, point.y));
+ expect(rect.angle).toBe(0);
+ const end = new Vector2(center.x - (point.y - center.y), center.y + point.x - center.x);
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', end.x, end.y));
+ expect(rect.angle).toBeCloseTo(90);
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', end.x, end.y));
+ expect((rect.left + rect.width / 2) * scale).toBe(center.x);
+ expect((rect.top + rect.height / 2) * scale).toBe(center.y);
+ const relocated = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes('Rotate__'))!;
+ const finalPoint = viewport.getAbsoluteVector(relocated.ancestorTransform.applyPoint(new Vector2(relocated.width / 2, relocated.height / 2)));
+ expect(transformer.isPointOnControl(rect.oKey, finalPoint)).toBe(true);
+ } finally {
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('supports bottom rotate control without a connector line', () => {
+ const { engine, scene } = createTransformerFixture();
+ engine.setActiveScene(scene.sceneKey);
+
+ const rect = scene.getObject('rect-main') as Rect;
+ rect.transformerConfig = {
+ rotateAnchorPosition: 'bottom',
+ rotateLineEnabled: false,
+ rotateIconEnabled: true,
+ };
+ const transformer = new Transformer(scene, {
+ rotateEnabled: true,
+ resizeEnabled: true,
+ borderEnabled: true,
+ });
+
+ transformer.setSelectedControl(rect);
+ const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`) as Group;
+ const controlObjects = control.getObjects();
+
+ expect(controlObjects.some((o) => o.visible && o.oKey.includes('__SpreadsheetTransformerRotateLine__'))).toBe(false);
+ expect(controlObjects.some((o) => o.oKey.includes('_ICON_'))).toBe(true);
+
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+
+ it('renders controls from resolved display geometry without changing the selected object', () => {
+ const { engine, scene } = createTransformerFixture();
+ engine.setActiveScene(scene.sceneKey);
+
+ const rect = scene.getObject('rect-main');
+ if (!(rect instanceof Rect)) {
+ throw new TypeError('Fixture should contain the main rectangle');
+ }
+ rect.transformerConfig = {
+ keepRatio: false,
+ controlStateResolver: (object) => ({
+ ...object.getState(),
+ left: object.left - 8,
+ top: object.top - 6,
+ width: object.width + 24,
+ height: object.height + 18,
+ }),
+ };
+ const transformer = new Transformer(scene);
+
+ transformer.setSelectedControl(rect);
+ const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`);
+ if (!(control instanceof Group)) {
+ throw new TypeError('Transformer should create a control group');
+ }
+
+ expect(control.getState()).toEqual(expect.objectContaining({
+ left: 2,
+ top: 4,
+ width: 124,
+ height: 78,
+ }));
+ expect(rect.getState()).toEqual(expect.objectContaining({
+ left: 10,
+ top: 10,
+ width: 100,
+ height: 60,
+ }));
+
+ rect.translate(30, 40);
+ transformer.updateControl();
+ expect(control.getState()).toEqual(expect.objectContaining({
+ left: 22,
+ top: 34,
+ width: 124,
+ height: 78,
+ }));
+
+ const resizeAnchor = control.getObjects().find((object) => object.oKey.includes('__SpreadsheetTransformerResizeRB__'));
+ if (!resizeAnchor) {
+ throw new TypeError('Transformer should create a bottom-right resize anchor');
+ }
+ resizeAnchor.triggerPointerDown(createPointerEvent('pointerdown', 146, 112));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 186, 137));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 186, 137));
+ expect(rect.getState()).toEqual(expect.objectContaining({
+ width: 140,
+ height: 85,
+ }));
+
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+
+ it('insets the icon inside a small rotate control and matches the connector to its border', () => {
+ const { engine, scene } = createTransformerFixture();
+ engine.setActiveScene(scene.sceneKey);
+
+ const rect = scene.getObject('rect-main') as Rect;
+ rect.transformerConfig = {
+ rotateAnchorPosition: 'bottom',
+ rotateAnchorOffset: 20,
+ rotateLineEnabled: true,
+ rotateSize: 14,
+ rotateCornerRadius: 4,
+ rotateStroke: '#d1d5db',
+ rotateIconEnabled: true,
+ };
+ const transformer = new Transformer(scene, {
+ rotateEnabled: true,
+ resizeEnabled: true,
+ borderEnabled: true,
+ });
+
+ transformer.setSelectedControl(rect);
+ const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`) as Group;
+ const controlObjects = control.getObjects();
+ const rotateLine = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotateLine__'));
+ const rotate = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotate__') && !o.oKey.includes('_ICON_')) as Rect;
+ const rotateIcon = controlObjects.find((o) => o.oKey.includes('_ICON_')) as Rect;
+
+ expect(rotateLine).toBeInstanceOf(Line);
+ if (!(rotateLine instanceof Line)) {
+ throw new TypeError('Rotate line should use the Line render primitive');
+ }
+
+ expect(rotateLine.stroke).toBe('#d1d5db');
+ expect(rotateLine.startX).toBe(rotateLine.endX);
+ const center = rotate.transform.applyPoint(new Vector2(rotate.width / 2, rotate.height / 2));
+ expect(rotateLine.startX).toBeCloseTo(center.x);
+ expect(center.y - rotateLine.endY).toBeCloseTo(rotate.height / 2);
+ const iconCenter = rotateIcon.transform.applyPoint(new Vector2(rotateIcon.width / 2, rotateIcon.height / 2));
+ expect(iconCenter.x).toBeCloseTo(center.x);
+ expect(iconCenter.y).toBeCloseTo(center.y);
+ expect(rotate.radius).toBe(4);
+ expect(rotateIcon.width).toBe(10);
+ expect(rotateIcon.height).toBe(10);
+
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+
+ it('expands transformer outline symmetrically when border spacing is configured', () => {
+ const { engine, scene } = createTransformerFixture();
+ const rect = scene.getObject('rect-main') as Rect;
+ rect.transformerConfig = {
+ borderSpacing: 6,
+ borderStrokeWidth: 1,
+ anchorStyle: 'canva',
+ anchorSize: 8,
+ };
+ const transformer = new Transformer(scene);
+
+ transformer.setSelectedControl(rect);
+ const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`) as Group;
+ const controlObjects = control.getObjects();
+ const outline = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerOutline__')) as Rect;
+ const leftMiddle = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerResizeLM__')) as Rect;
+
+ const outlineMatrix = outline.transform.getMatrix();
+ const leftMiddleMatrix = leftMiddle.transform.getMatrix();
+ expect(outlineMatrix[4]).toBe(-7);
+ expect(leftMiddleMatrix[4] + leftMiddle.width / 2).toBe(outlineMatrix[4]);
+
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+ it.each(['ResizeLT', 'ResizeRB'])('keeps a positive minimum size when dragging %s past the opposite corner', (key) => {
+ const { engine, scene, rect } = createTransformerFixture();
+ const transformer = new Transformer(scene, { keepRatio: false });
+ try {
+ transformer.setSelectedControl(rect);
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes(key))!;
+ const start = anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2));
+ const direction = key === 'ResizeLT' ? 1 : -1;
+ anchor.onPointerDown$.emitEvent(createPointerEvent('pointerdown', start.x, start.y));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', start.x + direction * 300, start.y + direction * 300));
+ expect(rect.width).toBe(20);
+ expect(rect.height).toBe(20);
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', start.x, start.y));
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each(['ResizeLT', 'ResizeRB'])('clips a resized object to the content bounds at %s', (key) => {
+ const { engine, scene, rect } = createTransformerFixture();
+ rect.translate(80, 60);
+ const transformer = new Transformer(scene, { keepRatio: false, zeroLeft: 46, zeroTop: 20 });
+ try {
+ transformer.setSelectedControl(rect);
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes(key))!;
+ const start = anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2));
+ const direction = key === 'ResizeLT' ? -1 : 1;
+ anchor.onPointerDown$.emitEvent(createPointerEvent('pointerdown', start.x, start.y));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', start.x + direction * 600, start.y + direction * 600));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', start.x + direction * 600, start.y + direction * 600));
+ if (key === 'ResizeLT') {
+ expect([rect.left, rect.top, rect.left + rect.width, rect.top + rect.height]).toEqual([46, 20, 180, 120]);
+ } else {
+ expect([rect.left, rect.top, rect.left + rect.width, rect.top + rect.height]).toEqual([80, 60, 500, 400]);
+ }
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each([true, false])('respects the move boundary setting %s', (moveBoundaryEnabled) => {
+ const { engine, scene, rect } = createTransformerFixture();
+ const transformer = new Transformer(scene, { moveBoundaryEnabled });
+ const changed = vi.fn();
+ const subscription = transformer.changing$.subscribe(changed);
+ try {
+ transformer.attachTo(rect);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 30, 30));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', -70, -70));
+ if (moveBoundaryEnabled) {
+ expect(rect.left).toBeGreaterThanOrEqual(0);
+ expect(rect.top).toBeGreaterThanOrEqual(0);
+ } else {
+ expect(rect.left).toBe(-90);
+ expect(rect.top).toBe(-90);
+ }
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', -70, -70));
+ transformer.changeNotification();
+ expect(changed).toHaveBeenLastCalledWith(expect.objectContaining({ objects: new Map([[rect.oKey, rect]]) }));
+ } finally {
+ subscription.unsubscribe();
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each([0.5, 1, 2])('keeps a selection inside scene bounds including the header origin at zoom %s', (scale) => {
+ const { engine, scene, rect } = createTransformerFixture();
+ scene.scale(scale, scale);
+ rect.translate(80, 60);
+ const second = new Rect('second', { left: 200, top: 150, width: 80, height: 50 });
+ scene.addObject(second);
+ const transformer = new Transformer(scene, { zeroLeft: 46, zeroTop: 20 });
+ try {
+ transformer.attachTo(rect);
+ transformer.setSelectedControl(rect);
+ transformer.setSelectedControl(second);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 100 * scale, 80 * scale));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', -500, -500));
+ expect([rect.left, rect.top, second.left - rect.left, second.top - rect.top]).toEqual([46, 20, 120, 90]);
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', -500, -500));
+
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 70 * scale, 40 * scale));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 2000, 2000));
+ expect([second.left + second.width, second.top + second.height]).toEqual([scene.width, scene.height]);
+ expect([second.left - rect.left, second.top - rect.top]).toEqual([120, 90]);
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 2000, 2000));
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('keeps an oversized object reachable without resizing it', () => {
+ const { engine, scene, rect } = createTransformerFixture();
+ rect.transformByState({ left: 46, top: 20, width: 800, height: 600 });
+ const transformer = new Transformer(scene, { zeroLeft: 46, zeroTop: 20 });
+ try {
+ transformer.attachTo(rect);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 100, 80));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 800, 600));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 800, 600));
+ expect([rect.left, rect.top, rect.width, rect.height]).toEqual([46, 20, 800, 600]);
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('allows moving outside the viewport while remaining inside the scene', () => {
+ const { engine, scene, rect } = createTransformerFixture();
+ scene.transformByState({ width: 2000, height: 2000 });
+ const transformer = new Transformer(scene);
+ try {
+ transformer.attachTo(rect);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 30, 30));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 900, 800));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 900, 800));
+ expect([rect.left, rect.top]).toEqual([880, 780]);
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
it('chooses the nearest touch control and leaves mouse, hidden controls and overlays precise', () => {
const engine = new Engine('adjust-hit-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
const scene = new Scene('adjust-hit-scene', engine);
@@ -221,21 +669,27 @@ describe('Transformer', () => {
const engine = new Engine('transformer-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
const scene = new Scene('transformer-scene', engine);
const rect = new Rect('transformer-rect', { width: 10, height: 10 });
+ const entered = vi.fn();
+ const left = vi.fn();
const transformer = new Transformer(scene, {
hoverEnabled: true,
- hoverEnterFunc: vi.fn(),
- hoverLeaveFunc: vi.fn(),
+ hoverEnterFunc: entered,
+ hoverLeaveFunc: left,
});
transformer.attachTo(rect);
- expect((rect.onPointerEnter$ as any).observers).toHaveLength(1);
- expect((rect.onPointerLeave$ as any).observers).toHaveLength(1);
+ rect.onPointerEnter$.emitEvent(createPointerEvent('pointerenter', 5, 5));
+ rect.onPointerLeave$.emitEvent(createPointerEvent('pointerleave', 5, 5));
+ expect(entered).toHaveBeenCalledTimes(1);
+ expect(left).toHaveBeenCalledTimes(1);
transformer.dispose();
- expect((rect.onPointerEnter$ as any).observers).toHaveLength(0);
- expect((rect.onPointerLeave$ as any).observers).toHaveLength(0);
+ rect.onPointerEnter$.emitEvent(createPointerEvent('pointerenter', 5, 5));
+ rect.onPointerLeave$.emitEvent(createPointerEvent('pointerleave', 5, 5));
+ expect(entered).toHaveBeenCalledTimes(1);
+ expect(left).toHaveBeenCalledTimes(1);
rect.dispose();
scene.dispose();
diff --git a/packages/engine-render/src/__tests__/transformer-rotation.spec.ts b/packages/engine-render/src/__tests__/transformer-rotation.spec.ts
new file mode 100644
index 0000000000..9b33fff40d
--- /dev/null
+++ b/packages/engine-render/src/__tests__/transformer-rotation.spec.ts
@@ -0,0 +1,107 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import type { IRotationHandleLayout } from '../transformer-rotation';
+import { placeRotationHandle } from '../transformer-rotation';
+
+function createLayout(): IRotationHandleLayout {
+ return {
+ bounds: { left: 0, top: 0, right: 400, bottom: 400 },
+ radius: 22,
+ artworkRadius: 10,
+ preferred: { center: { x: 200, y: 60 }, attachment: { x: 200, y: 110 }, side: 'top' },
+ opposite: { center: { x: 200, y: 290 }, attachment: { x: 200, y: 240 }, side: 'bottom' },
+ corners: [{ x: 100, y: 110 }, { x: 300, y: 110 }, { x: 300, y: 240 }, { x: 100, y: 240 }],
+ obstacles: [{ x: 200, y: 110, radius: 6 }, { x: 200, y: 240, radius: 6 }],
+ };
+}
+
+describe('placeRotationHandle', () => {
+ it('preserves an unobstructed default position', () => {
+ const layout = createLayout();
+ expect(placeRotationHandle(layout)).toMatchObject({ ...layout.preferred, adjusted: false });
+ });
+
+ it('shortens the stem before changing sides and keeps the full touch target inside', () => {
+ const layout = createLayout();
+ layout.preferred = { center: { x: 200, y: 20 }, attachment: { x: 200, y: 70 }, side: 'top' };
+ layout.obstacles[0].y = 70;
+ const placement = placeRotationHandle(layout)!;
+ expect(placement.side).toBe('top');
+ expect(placement.center.y).toBeGreaterThan(layout.preferred.center.y);
+ expect(placement.center.y - layout.radius).toBeGreaterThanOrEqual(8);
+ expect(placement.center.y).toBeLessThan(layout.preferred.attachment.y);
+ });
+
+ it('switches sides when shortening would overlap a resize handle, and waits for clearance before returning', () => {
+ const layout = createLayout();
+ layout.preferred = { center: { x: 200, y: -10 }, attachment: { x: 200, y: 40 }, side: 'top' };
+ layout.obstacles[0].y = 40;
+ expect(placeRotationHandle(layout)?.side).toBe('bottom');
+ layout.previousSide = 'bottom';
+ layout.preferred.center.y = 35;
+ layout.preferred.attachment.y = 85;
+ layout.obstacles[0].y = 85;
+ expect(placeRotationHandle(layout)?.side).toBe('bottom');
+ layout.preferred.center.y = 50;
+ layout.preferred.attachment.y = 100;
+ layout.obstacles[0].y = 100;
+ expect(placeRotationHandle(layout)?.side).toBe('top');
+ });
+
+ it('insets a handle for an oversized object and avoids another adjustment control', () => {
+ const layout = createLayout();
+ layout.preferred = { center: { x: 200, y: -100 }, attachment: { x: 200, y: -50 }, side: 'top' };
+ layout.opposite = { center: { x: 200, y: 500 }, attachment: { x: 200, y: 450 }, side: 'bottom' };
+ layout.corners = [{ x: -100, y: -50 }, { x: 300, y: -50 }, { x: 300, y: 450 }, { x: -100, y: 450 }];
+ layout.obstacles = [{ x: 200, y: 30, radius: 8 }];
+ const placement = placeRotationHandle(layout)!;
+ expect(placement.side).toBe('inset');
+ expect(placement.center.x).toBeGreaterThanOrEqual(30);
+ expect(placement.center.x).toBeLessThanOrEqual(370);
+ expect(placement.center.y).toBeGreaterThanOrEqual(30);
+ expect(placement.center.y).toBeLessThanOrEqual(370);
+ expect(Math.hypot(placement.center.x - 200, placement.center.y - 30)).toBeGreaterThanOrEqual(layout.artworkRadius + 8);
+ expect(placement.attachment.x === 300 || placement.attachment.y === -50).toBe(true);
+ });
+
+ it('keeps the nearest clear inset without scanning every distant candidate against every control', () => {
+ const layout = createLayout();
+ layout.preferred = { center: { x: 200, y: -100 }, attachment: { x: 200, y: -50 }, side: 'top' };
+ layout.opposite = { center: { x: 200, y: 500 }, attachment: { x: 200, y: 450 }, side: 'bottom' };
+ let coordinateReads = 0;
+ const distantControls = Array.from({ length: 1000 }, (_, index) => ({
+ get x() {
+ coordinateReads++;
+ return 1000 + index * 30;
+ },
+ y: 1000,
+ radius: 6,
+ }));
+ layout.obstacles = [{ x: 200, y: 30, radius: 8 }, ...distantControls];
+
+ expect(placeRotationHandle(layout)).toMatchObject({ center: { x: 178, y: 30 }, side: 'inset' });
+ // Bound collision work independently of machine speed for large drawing selections.
+ expect(coordinateReads).toBeLessThan(distantControls.length * 20);
+ });
+
+ it('does not expose a clipped interaction target when the viewport is too small', () => {
+ const layout = createLayout();
+ layout.bounds.right = 40;
+ expect(placeRotationHandle(layout)).toBeUndefined();
+ });
+});
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index 814e92d7c9..4963568699 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -16,17 +16,20 @@
import type { IAbsoluteTransform, Nullable } from '@univerjs/core';
import type { Subscription } from 'rxjs';
+import { Disposable, MOVE_BUFFER_VALUE, requestImmediateMacroTask, toDisposable } from '@univerjs/core';
+import { Subject } from 'rxjs';
import type { BaseObject } from './base-object';
import type { IMouseEvent, IPointerEvent } from './basics/i-events';
import type { ITransformerConfig } from './basics/transformer-config';
-import type { IPoint } from './basics/vector2';
+import type { IBoundRectNoAngle, IPoint } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import type { Scene } from './scene';
import type { IRectProps } from './shape/rect';
import type { IRegularPolygonProps } from './shape/regular-polygon';
-import { Disposable, MOVE_BUFFER_VALUE, requestImmediateMacroTask, toDisposable } from '@univerjs/core';
-import { Subject } from 'rxjs';
+import type { IRotationHandleCandidate, IRotationHandleObstacle, IRotationHandlePlacement } from './transformer-rotation';
+import type { Viewport } from './viewport';
import { CURSOR_TYPE } from './basics/const';
+import { DeviceType } from './basics/i-events';
import { offsetRotationAxis } from './basics/offset-rotation-axis';
import { getCurrentScrollXY } from './basics/scroll-xy';
import { degToRad, precisionTo, radToDeg } from './basics/tools';
@@ -34,10 +37,11 @@ import { DEFAULT_TRANSFORMER_CONFIG } from './basics/transformer-config';
import { Vector2 } from './basics/vector2';
import { Group } from './group';
import { ScrollTimer } from './scroll-timer';
-import { Control } from './shape/control';
+import { Control, CONTROL_TOUCH_HIT_RADIUS } from './shape/control';
import { Line } from './shape/line';
import { Rect } from './shape/rect';
import { RegularPolygon } from './shape/regular-polygon';
+import { placeRotationHandle } from './transformer-rotation';
enum TransformerManagerType {
RESIZE_LT = '__SpreadsheetTransformerResizeLT__',
@@ -275,6 +279,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _transformerControlMap = new Map<string, Group>();
private _selectedObjectMap = new Map<string, BaseObject>();
+ private readonly _rotationControls = new Map<string, { handle: Control; icon?: Rect; line: Line }>();
+ private readonly _rotationSides = new Map<string, IRotationHandlePlacement['side']>();
private _subscriptionObjectMap = new Map<string, Nullable<Subscription>>();
private _copperControl: Nullable<Group>;
@@ -290,6 +296,16 @@ export class Transformer extends Disposable implements ITransformerConfig {
) {
super();
this._initialProps(config);
+ this.disposeWithMe(this._scene.prepareRender$.subscribe(() => this._updateRotationControls()));
+ }
+
+ /** Hit-test the actual displayed handles using canvas coordinates, including viewport edge avoidance. */
+ isPointOnControl(objectKey: string, coord: Vector2, deviceType = DeviceType.Mouse): boolean {
+ const group = this._transformerControlMap.get(objectKey);
+ if (!group?.visible || !this._scene.getActiveViewportByCoord(coord)) return false;
+ this._updateRotationControls();
+ const hit = this._scene.pick(coord, deviceType);
+ return group.getObjects().some((object) => object === hit && object instanceof Control);
}
updateZeroPoint(left: number, top: number) {
@@ -364,6 +380,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
clearSelectedObjects() {
this._selectedObjectMap.clear();
+ this._rotationSides.clear();
this._cancelFocusSubscription?.unsubscribe();
this._cancelFocusSubscription = null;
this._clearControls(true);
@@ -392,168 +409,69 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._createControl(realApplyObject);
}
- // eslint-disable-next-line max-lines-per-function, complexity
private _getConfig(applyObject: BaseObject) {
- const objectTransformerConfig = applyObject.transformerConfig;
- let {
- isCropper,
- hoverEnabled,
- hoverEnterFunc,
- hoverLeaveFunc,
- moveEnabled,
- moveOnlyWhenSelected,
- resizeEnabled,
- rotateEnabled,
- rotationSnaps,
- rotationSnapTolerance,
- rotateAnchorOffset,
- rotateAnchorPosition,
- rotateLineEnabled,
- rotateSize,
- rotateCornerRadius,
- rotateFill,
- rotateStroke,
- rotateStrokeWidth,
- rotateIconEnabled,
- rotateIconStroke,
- rotateIconStrokeWidth,
- borderEnabled,
- borderStroke,
- borderStrokeWidth,
- borderDash,
- borderSpacing,
- anchorFill,
- anchorStroke,
- anchorStrokeWidth,
- anchorSize,
- anchorCornerRadius,
- anchorStyle,
- anchorSideLongSize,
- anchorSideShortSize,
- anchorSideCornerRadius,
- anchorShadowColor,
- anchorShadowBlur,
- anchorShadowOffsetX,
- anchorShadowOffsetY,
- keepRatio,
- centeredScaling,
- enabledAnchors,
- flipEnabled,
- ignoreStroke,
- boundBoxFunc,
- useSingleNodeRotation,
- shouldOverdrawWholeArea,
- moveBoundaryEnabled,
- } = this;
- if (objectTransformerConfig != null) {
- isCropper = objectTransformerConfig.isCropper ?? isCropper;
- hoverEnabled = objectTransformerConfig.hoverEnabled ?? hoverEnabled;
- hoverEnterFunc = objectTransformerConfig.hoverEnterFunc ?? hoverEnterFunc;
- hoverLeaveFunc = objectTransformerConfig.hoverLeaveFunc ?? hoverLeaveFunc;
- moveEnabled = objectTransformerConfig.moveEnabled ?? moveEnabled;
- moveOnlyWhenSelected = objectTransformerConfig.moveOnlyWhenSelected ?? moveOnlyWhenSelected;
- resizeEnabled = objectTransformerConfig.resizeEnabled ?? resizeEnabled;
- rotateEnabled = objectTransformerConfig.rotateEnabled ?? rotateEnabled;
- rotationSnaps = objectTransformerConfig.rotationSnaps ?? rotationSnaps;
- rotationSnapTolerance = objectTransformerConfig.rotationSnapTolerance ?? rotationSnapTolerance;
- rotateAnchorOffset = objectTransformerConfig.rotateAnchorOffset ?? rotateAnchorOffset;
- rotateAnchorPosition = objectTransformerConfig.rotateAnchorPosition ?? rotateAnchorPosition;
- rotateLineEnabled = objectTransformerConfig.rotateLineEnabled ?? rotateLineEnabled;
- rotateSize = objectTransformerConfig.rotateSize ?? rotateSize;
- rotateCornerRadius = objectTransformerConfig.rotateCornerRadius ?? rotateCornerRadius;
- rotateFill = objectTransformerConfig.rotateFill ?? rotateFill;
- rotateStroke = objectTransformerConfig.rotateStroke ?? rotateStroke;
- rotateStrokeWidth = objectTransformerConfig.rotateStrokeWidth ?? rotateStrokeWidth;
- rotateIconEnabled = objectTransformerConfig.rotateIconEnabled ?? rotateIconEnabled;
- rotateIconStroke = objectTransformerConfig.rotateIconStroke ?? rotateIconStroke;
- rotateIconStrokeWidth = objectTransformerConfig.rotateIconStrokeWidth ?? rotateIconStrokeWidth;
- borderEnabled = objectTransformerConfig.borderEnabled ?? borderEnabled;
- borderStroke = objectTransformerConfig.borderStroke ?? borderStroke;
- borderStrokeWidth = objectTransformerConfig.borderStrokeWidth ?? borderStrokeWidth;
- borderDash = objectTransformerConfig.borderDash ?? borderDash;
- borderSpacing = objectTransformerConfig.borderSpacing ?? borderSpacing;
- anchorFill = objectTransformerConfig.anchorFill ?? anchorFill;
- anchorStroke = objectTransformerConfig.anchorStroke ?? anchorStroke;
- anchorStrokeWidth = objectTransformerConfig.anchorStrokeWidth ?? anchorStrokeWidth;
- anchorSize = objectTransformerConfig.anchorSize ?? anchorSize;
- anchorCornerRadius = objectTransformerConfig.anchorCornerRadius ?? anchorCornerRadius;
- anchorStyle = objectTransformerConfig.anchorStyle ?? anchorStyle;
- anchorSideLongSize = objectTransformerConfig.anchorSideLongSize ?? anchorSideLongSize;
- anchorSideShortSize = objectTransformerConfig.anchorSideShortSize ?? anchorSideShortSize;
- anchorSideCornerRadius = objectTransformerConfig.anchorSideCornerRadius ?? anchorSideCornerRadius;
- anchorShadowColor = objectTransformerConfig.anchorShadowColor ?? anchorShadowColor;
- anchorShadowBlur = objectTransformerConfig.anchorShadowBlur ?? anchorShadowBlur;
- anchorShadowOffsetX = objectTransformerConfig.anchorShadowOffsetX ?? anchorShadowOffsetX;
- anchorShadowOffsetY = objectTransformerConfig.anchorShadowOffsetY ?? anchorShadowOffsetY;
- keepRatio = objectTransformerConfig.keepRatio ?? keepRatio;
- centeredScaling = objectTransformerConfig.centeredScaling ?? centeredScaling;
- enabledAnchors = objectTransformerConfig.enabledAnchors ?? enabledAnchors;
- flipEnabled = objectTransformerConfig.flipEnabled ?? flipEnabled;
- ignoreStroke = objectTransformerConfig.ignoreStroke ?? ignoreStroke;
- boundBoxFunc = objectTransformerConfig.boundBoxFunc ?? boundBoxFunc;
- useSingleNodeRotation = objectTransformerConfig.useSingleNodeRotation ?? useSingleNodeRotation;
- shouldOverdrawWholeArea = objectTransformerConfig.shouldOverdrawWholeArea ?? shouldOverdrawWholeArea;
- moveBoundaryEnabled = objectTransformerConfig.moveBoundaryEnabled ?? moveBoundaryEnabled;
- }
-
- return {
- isCropper,
- hoverEnabled,
- hoverEnterFunc,
- hoverLeaveFunc,
- moveEnabled,
- moveOnlyWhenSelected,
- resizeEnabled,
- rotateEnabled,
- rotationSnaps,
- rotationSnapTolerance,
- rotateAnchorOffset,
- rotateAnchorPosition,
- rotateLineEnabled,
- rotateSize,
- rotateCornerRadius,
- rotateFill,
- rotateStroke,
- rotateStrokeWidth,
- rotateIconEnabled,
- rotateIconStroke,
- rotateIconStrokeWidth,
- borderEnabled,
- borderStroke,
- borderStrokeWidth,
- borderDash,
- borderSpacing,
- anchorFill,
- anchorStroke,
- anchorStrokeWidth,
- anchorSize,
- anchorCornerRadius,
- anchorStyle,
- anchorSideLongSize,
- anchorSideShortSize,
- anchorSideCornerRadius,
- anchorShadowColor,
- anchorShadowBlur,
- anchorShadowOffsetX,
- anchorShadowOffsetY,
- keepRatio,
- centeredScaling,
- enabledAnchors,
- flipEnabled,
- ignoreStroke,
- boundBoxFunc,
- useSingleNodeRotation,
- shouldOverdrawWholeArea,
- moveBoundaryEnabled,
+ const config = {
+ isCropper: this.isCropper,
+ controlLayerIndex: this.controlLayerIndex,
+ hoverEnabled: this.hoverEnabled,
+ hoverEnterFunc: this.hoverEnterFunc,
+ hoverLeaveFunc: this.hoverLeaveFunc,
+ moveEnabled: this.moveEnabled,
+ moveOnlyWhenSelected: this.moveOnlyWhenSelected,
+ resizeEnabled: this.resizeEnabled,
+ rotateEnabled: this.rotateEnabled,
+ rotationSnaps: this.rotationSnaps,
+ rotationSnapTolerance: this.rotationSnapTolerance,
+ rotateAnchorOffset: this.rotateAnchorOffset,
+ rotateAnchorPosition: this.rotateAnchorPosition,
+ rotateLineEnabled: this.rotateLineEnabled,
+ rotateSize: this.rotateSize,
+ rotateCornerRadius: this.rotateCornerRadius,
+ rotateFill: this.rotateFill,
+ rotateStroke: this.rotateStroke,
+ rotateStrokeWidth: this.rotateStrokeWidth,
+ rotateIconEnabled: this.rotateIconEnabled,
+ rotateIconStroke: this.rotateIconStroke,
+ rotateIconStrokeWidth: this.rotateIconStrokeWidth,
+ borderEnabled: this.borderEnabled,
+ borderStroke: this.borderStroke,
+ borderStrokeWidth: this.borderStrokeWidth,
+ borderDash: this.borderDash,
+ borderSpacing: this.borderSpacing,
+ anchorFill: this.anchorFill,
+ anchorStroke: this.anchorStroke,
+ anchorStrokeWidth: this.anchorStrokeWidth,
+ anchorSize: this.anchorSize,
+ anchorCornerRadius: this.anchorCornerRadius,
+ anchorStyle: this.anchorStyle,
+ anchorSideLongSize: this.anchorSideLongSize,
+ anchorSideShortSize: this.anchorSideShortSize,
+ anchorSideCornerRadius: this.anchorSideCornerRadius,
+ anchorShadowColor: this.anchorShadowColor,
+ anchorShadowBlur: this.anchorShadowBlur,
+ anchorShadowOffsetX: this.anchorShadowOffsetX,
+ anchorShadowOffsetY: this.anchorShadowOffsetY,
+ keepRatio: this.keepRatio,
+ centeredScaling: this.centeredScaling,
+ enabledAnchors: this.enabledAnchors,
+ flipEnabled: this.flipEnabled,
+ ignoreStroke: this.ignoreStroke,
+ boundBoxFunc: this.boundBoxFunc,
+ useSingleNodeRotation: this.useSingleNodeRotation,
+ shouldOverdrawWholeArea: this.shouldOverdrawWholeArea,
+ moveBoundaryEnabled: this.moveBoundaryEnabled,
};
+ for (const key of Object.keys(config) as Array<keyof typeof config>) {
+ const value = applyObject.transformerConfig?.[key];
+ if (value != null) Object.assign(config, { [key]: value });
+ }
+ return config;
}
- // eslint-disable-next-line max-lines-per-function
attachTo(applyObject: BaseObject) {
// First check if there is an old subscription to avoid duplicate subscriptions
this.detachFrom(applyObject);
- // eslint-disable-next-line max-lines-per-function
const observer = applyObject.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
this.finishTransform();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
@@ -563,45 +481,16 @@ export class Transformer extends Disposable implements ITransformerConfig {
const { isCropper, moveEnabled, moveOnlyWhenSelected } = this._getConfig(applyObject);
if (!isCropper && moveOnlyWhenSelected && !this._selectedObjectMap.has(this._findGroupObject(applyObject).oKey)) {
- const scene = this._getTopScene();
- if (!scene) {
- this._updateActiveObjectList(applyObject, evt);
- return;
- }
-
- let moved = false;
- let moveSubscription: Nullable<Subscription>;
- let upSubscription: Nullable<Subscription>;
- let cancelSubscription: Nullable<Subscription>;
- const disposeGesture = () => {
- moveSubscription?.unsubscribe();
- upSubscription?.unsubscribe();
- cancelSubscription?.unsubscribe();
- };
-
- moveSubscription = scene.onPointerMove$.subscribeEvent((moveEvent: IPointerEvent | IMouseEvent) => {
- moved ||= Math.hypot(moveEvent.offsetX - evtOffsetX, moveEvent.offsetY - evtOffsetY) >= Transformer._selectionTapMovementThreshold;
- });
- upSubscription = scene.onPointerUp$.subscribeEvent(() => {
- disposeGesture();
- if (!moved) {
- this._updateActiveObjectList(applyObject, evt);
- }
- });
- cancelSubscription = scene.onPointerCancel$.subscribeEvent(disposeGesture);
- return;
+ return this._selectOnPointerUp(applyObject, evt);
}
if (!isCropper && !moveEnabled) {
- this._updateActiveObjectList(applyObject, evt);
- return;
+ return this._updateActiveObjectList(applyObject, evt);
}
const scene = this._getTopScene();
- if (!scene) {
- return;
- }
+ if (!scene) return;
this._addCancelObserver(scene);
@@ -618,21 +507,10 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._viewportScrollX = scrollX;
this._viewportScrollY = scrollY;
- if (!isCropper) {
- this._updateActiveObjectList(applyObject, evt);
- this._changeStart$.next({
- target: applyObject,
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_START,
- });
- } else {
- this._copperSelectedObject = applyObject;
- this._changeStart$.next({
- target: applyObject,
- objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
- type: MoveObserverType.MOVE_START,
- });
- }
+ if (!isCropper) this._updateActiveObjectList(applyObject, evt);
+ else this._copperSelectedObject = applyObject;
+ const objects = isCropper ? new Map([[applyObject.oKey, applyObject]]) : this._selectedObjectMap;
+ this._changeStart$.next({ target: applyObject, objects, type: MoveObserverType.MOVE_START });
this._moveBufferSkip = false;
@@ -655,23 +533,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
const { offsetX, offsetY } = event;
- if (!isCropper) {
- this._changeEnd$.next({
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_END,
- offsetX,
- offsetY,
- event,
- });
- } else {
- this._changeEnd$.next({
- objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
- type: MoveObserverType.MOVE_END,
- offsetX,
- offsetY,
- event,
- });
- }
+ this._changeEnd$.next({ objects, type: MoveObserverType.MOVE_END, offsetX, offsetY, event });
});
state.stopPropagation();
@@ -687,6 +549,35 @@ export class Transformer extends Disposable implements ITransformerConfig {
return applyObject;
}
+ private _selectOnPointerUp(applyObject: BaseObject, evt: IPointerEvent | IMouseEvent) {
+ const scene = this._getTopScene();
+ if (!scene) {
+ this._updateActiveObjectList(applyObject, evt);
+ return;
+ }
+
+ let moved = false;
+ let moveSubscription: Nullable<Subscription>;
+ let upSubscription: Nullable<Subscription>;
+ let cancelSubscription: Nullable<Subscription>;
+ const disposeGesture = () => {
+ moveSubscription?.unsubscribe();
+ upSubscription?.unsubscribe();
+ cancelSubscription?.unsubscribe();
+ };
+
+ moveSubscription = scene.onPointerMove$.subscribeEvent((moveEvent: IPointerEvent | IMouseEvent) => {
+ moved ||= Math.hypot(moveEvent.offsetX - evt.offsetX, moveEvent.offsetY - evt.offsetY) >= Transformer._selectionTapMovementThreshold;
+ });
+ upSubscription = scene.onPointerUp$.subscribeEvent(() => {
+ disposeGesture();
+ if (!moved) {
+ this._updateActiveObjectList(applyObject, evt);
+ }
+ });
+ cancelSubscription = scene.onPointerCancel$.subscribeEvent(disposeGesture);
+ }
+
detachFrom(applyObject: BaseObject) {
const subscription = this._subscriptionObjectMap.get(applyObject.oKey);
if (subscription) {
@@ -712,6 +603,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._transformerControlMap.forEach((control) => control.dispose());
this._selectedObjectMap.forEach((control) => control.dispose());
+ this._rotationControls.clear();
+ this._rotationSides.clear();
this._changeStart$.complete();
this._changing$.complete();
this._changeEnd$.complete();
@@ -732,41 +625,27 @@ export class Transformer extends Disposable implements ITransformerConfig {
return true;
}
- (this as Record<string, any>)[key] = props[key as keyof ITransformerConfig];
+ Object.assign(this, { [key]: props[key as keyof ITransformerConfig] });
});
}
- private _checkMoveBoundary(moveObject: BaseObject, moveLeft: number, moveTop: number, ancestorLeft: number, ancestorTop: number, topSceneWidth: number, topSceneHeight: number) {
- if (this._getConfig(moveObject).moveBoundaryEnabled === false) {
- return {
- moveLeft,
- moveTop,
- };
- }
-
- const { left, top, width, height } = moveObject;
- let resultMoveLeft = moveLeft;
- let resultMoveTop = moveTop;
-
- if (resultMoveLeft + left + ancestorLeft < this.zeroLeft) {
- resultMoveLeft = -ancestorLeft;
- }
-
- if (resultMoveTop + top + ancestorTop < this.zeroTop) {
- resultMoveTop = -ancestorTop;
- }
-
- if (resultMoveLeft + left + width + ancestorLeft > topSceneWidth + this.zeroLeft) {
- resultMoveLeft = this.zeroLeft + topSceneWidth - width - left - ancestorLeft;
- }
-
- if (resultMoveTop + top + height + ancestorTop > topSceneHeight + this.zeroTop) {
- resultMoveTop = this.zeroTop + topSceneHeight - height - top - ancestorTop;
+ private _checkMoveBoundary(objects: BaseObject[], moveLeft: number, moveTop: number, ancestorLeft: number, ancestorTop: number, topSceneWidth: number, topSceneHeight: number) {
+ let minX = -Infinity;
+ let minY = -Infinity;
+ let maxX = Infinity;
+ let maxY = Infinity;
+ for (const object of objects) {
+ if (this._getConfig(object).moveBoundaryEnabled === false) continue;
+ minX = Math.max(minX, this.zeroLeft - object.left - ancestorLeft);
+ minY = Math.max(minY, this.zeroTop - object.top - ancestorTop);
+ maxX = Math.min(maxX, topSceneWidth - object.left - object.width - ancestorLeft);
+ maxY = Math.min(maxY, topSceneHeight - object.top - object.height - ancestorTop);
}
+ // Keep the leading edge reachable when the selection is larger than the scene.
return {
- moveLeft: resultMoveLeft,
- moveTop: resultMoveTop,
+ moveLeft: Math.max(minX, Math.min(moveLeft, maxX)),
+ moveTop: Math.max(minY, Math.min(moveTop, maxY)),
};
}
@@ -793,23 +672,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
if (!isCropper) {
const selectedObjects = Array.from(this._selectedObjectMap.values());
- // move boundary check
- for (let i = 0; i < selectedObjects.length; i++) {
- const moveObject = selectedObjects[i];
-
- const boundary = this._checkMoveBoundary(
- moveObject,
- moveLeft,
- moveTop,
- ancestorLeft,
- ancestorTop,
- topSceneWidth,
- topSceneHeight
- );
-
- moveLeft = boundary.moveLeft;
- moveTop = boundary.moveTop;
- }
+ const boundary = this._checkMoveBoundary(selectedObjects, moveLeft, moveTop, ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+ moveLeft = boundary.moveLeft;
+ moveTop = boundary.moveTop;
this._selectedObjectMap.forEach((moveObject) => {
moveObject.translate(moveLeft + moveObject.left, moveTop + moveObject.top);
@@ -825,7 +690,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
} else if (this._copperSelectedObject) {
const cropper = this._copperSelectedObject;
// move boundary check
- const boundary = this._checkMoveBoundary(cropper, moveLeft, moveTop, ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+ const boundary = this._checkMoveBoundary([cropper], moveLeft, moveTop, ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
moveLeft = boundary.moveLeft;
moveTop = boundary.moveTop;
@@ -978,44 +843,43 @@ export class Transformer extends Disposable implements ITransformerConfig {
};
}
- // eslint-disable-next-line complexity
private _updateCloseKeepRatioState(type: TransformerManagerType, left: number, top: number, width: number, height: number, moveLeft: number, moveTop: number) {
const state: ITransformState = { left, top, width, height };
switch (type) {
case TransformerManagerType.RESIZE_LT:
- state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
- state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.width = Math.max(MINI_WIDTH_LIMIT, width - moveLeft);
+ state.height = Math.max(MINI_HEIGHT_LIMIT, height - moveTop);
state.left = left + width - state.width;
state.top = top + height - state.height;
break;
case TransformerManagerType.RESIZE_CT:
- state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.height = Math.max(MINI_HEIGHT_LIMIT, height - moveTop);
state.top = top + height - state.height;
break;
case TransformerManagerType.RESIZE_RT:
- state.width = width + moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width + moveLeft;
- state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.width = Math.max(MINI_WIDTH_LIMIT, width + moveLeft);
+ state.height = Math.max(MINI_HEIGHT_LIMIT, height - moveTop);
state.top = top + height - state.height;
break;
case TransformerManagerType.RESIZE_LM:
- state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
+ state.width = Math.max(MINI_WIDTH_LIMIT, width - moveLeft);
state.left = left + width - state.width;
break;
case TransformerManagerType.RESIZE_RM:
- state.width = moveLeft + width < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : moveLeft + width;
+ state.width = Math.max(MINI_WIDTH_LIMIT, moveLeft + width);
break;
case TransformerManagerType.RESIZE_LB:
- state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
- state.height = height + moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height + moveTop;
+ state.width = Math.max(MINI_WIDTH_LIMIT, width - moveLeft);
+ state.height = Math.max(MINI_HEIGHT_LIMIT, height + moveTop);
state.left = state.width <= MINI_WIDTH_LIMIT ? left : left + moveLeft;
break;
case TransformerManagerType.RESIZE_CB:
- state.height = moveTop + height < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : moveTop + height;
+ state.height = Math.max(MINI_HEIGHT_LIMIT, moveTop + height);
break;
case TransformerManagerType.RESIZE_RB:
- state.width = moveLeft + width < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : moveLeft + width;
- state.height = moveTop + height < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : moveTop + height;
+ state.width = Math.max(MINI_WIDTH_LIMIT, moveLeft + width);
+ state.height = Math.max(MINI_HEIGHT_LIMIT, moveTop + height);
break;
}
@@ -1039,7 +903,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _resizeLeftTop(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
- const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const { width: originWidth = width, height: originHeight = height } = originState;
const aspectRatio = originWidth / originHeight;
const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLtRb(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
@@ -1065,7 +929,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _resizeRightBottom(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
- const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const { width: originWidth = width, height: originHeight = height } = originState;
const aspectRatio = originWidth / originHeight;
const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLtRb(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
@@ -1091,7 +955,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _resizeLeftBottom(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
- const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const { width: originWidth = width, height: originHeight = height } = originState;
const aspectRatio = originWidth / originHeight;
const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLbRt(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
@@ -1117,7 +981,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _resizeRightTop(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
- const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const { width: originWidth = width, height: originHeight = height } = originState;
const aspectRatio = originWidth / originHeight;
const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLbRt(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
@@ -1173,11 +1037,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
};
}
- // eslint-disable-next-line max-lines-per-function
private _attachEventToAnchor(anchor: BaseObject, type = TransformerManagerType.RESIZE_LT, applyObject: BaseObject) {
this.disposeWithMe(
toDisposable(
- // eslint-disable-next-line max-lines-per-function
anchor.onPointerDown$.subscribeEvent((evt, state) => {
this.finishTransform();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
@@ -1238,25 +1100,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._startStateMap.clear();
const { offsetX, offsetY } = event;
- if (!isCropper) {
- this._recoverySizeBoundary(Array.from(this._selectedObjectMap.values()), ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
- this._changeEnd$.next({
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_END,
- offsetX,
- offsetY,
- event,
- });
- } else {
- this._recoverySizeBoundary([applyObject], ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
- this._changeEnd$.next({
- objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
- type: MoveObserverType.MOVE_END,
- offsetX,
- offsetY,
- event,
- });
- }
+ const objects = isCropper ? new Map([[applyObject.oKey, applyObject]]) : this._selectedObjectMap;
+ this._recoverySizeBoundary(Array.from(objects.values()), ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+ this._changeEnd$.next({ objects, type: MoveObserverType.MOVE_END, offsetX, offsetY, event });
this.refreshControls();
});
state.stopPropagation();
@@ -1277,16 +1123,16 @@ export class Transformer extends Disposable implements ITransformerConfig {
if (left + ancestorLeft < this.zeroLeft) {
newTransform.left = this.zeroLeft - ancestorLeft;
- newTransform.width = width + left;
- } else if (left + width + ancestorLeft > topSceneWidth + this.zeroLeft) {
- newTransform.width = this.zeroLeft + topSceneWidth - left - ancestorLeft;
+ newTransform.width = width + left + ancestorLeft - this.zeroLeft;
+ } else if (left + width + ancestorLeft > topSceneWidth) {
+ newTransform.width = topSceneWidth - left - ancestorLeft;
}
if (top + ancestorTop < this.zeroTop) {
newTransform.top = this.zeroTop - ancestorTop;
- newTransform.height = height + top;
- } else if (top + height + ancestorTop > topSceneHeight + this.zeroTop) {
- newTransform.height = this.zeroTop + topSceneHeight - top - ancestorTop;
+ newTransform.height = height + top + ancestorTop - this.zeroTop;
+ } else if (top + height + ancestorTop > topSceneHeight) {
+ newTransform.height = topSceneHeight - top - ancestorTop;
}
moveObject.transformByState(newTransform);
@@ -1848,6 +1694,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
});
control.show();
control.makeDirty(true);
+ this._updateRotationControl(control as Group, applyObject);
});
}
@@ -1889,6 +1736,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
public clearControlByIds(ids: string[]) {
for (const id of ids) {
this._selectedObjectMap.delete(id);
+ this._rotationSides.delete(id);
}
this.refreshControls();
}
@@ -1898,27 +1746,15 @@ export class Transformer extends Disposable implements ITransformerConfig {
control.dispose();
});
this._transformerControlMap.clear();
+ this._rotationControls.clear();
}
- // eslint-disable-next-line max-lines-per-function, complexity
private _createControl(applyObject: BaseObject, isSkipOnCropper = true) {
const { left = 0, top = 0, height = 0, width = 0, angle = 0 } = this._getControlState(applyObject);
const {
isCropper,
resizeEnabled,
rotateEnabled,
- rotateAnchorOffset,
- rotateLineEnabled,
- rotateSize,
- rotateCornerRadius,
- rotateFill,
- rotateStroke,
- rotateStrokeWidth,
- rotateIconEnabled,
- anchorShadowColor,
- anchorShadowBlur,
- anchorShadowOffsetX,
- anchorShadowOffsetY,
borderEnabled,
borderStroke,
borderStrokeWidth,
@@ -1930,9 +1766,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
const oKey = applyObject.oKey;
const zIndex = this._selectedObjectMap.size + applyObject.maxZIndex + DEFAULT_CONTROL_PLUS_INDEX;
- const layerIndex = applyObject.transformerConfig?.controlLayerIndex ??
- this.controlLayerIndex ??
- (applyObject.getLayerIndex() || DEFAULT_TRANSFORMER_LAYER_INDEX);
+ const layerIndex = this._getConfig(applyObject).controlLayerIndex ?? (applyObject.getLayerIndex() || DEFAULT_TRANSFORMER_LAYER_INDEX);
const groupElements: BaseObject[] = [];
if (borderEnabled && !isCropper) {
@@ -1945,71 +1779,11 @@ export class Transformer extends Disposable implements ITransformerConfig {
});
groupElements.push(outline);
}
- if (resizeEnabled && !isCropper) {
- const { left: lineLeft, top: lineTop } = this._getRotateAnchorPosition(
- TransformerManagerType.ROTATE_LINE,
- height,
- width,
- applyObject
- );
- if (rotateEnabled) {
- const rotateLine = new Line(`${TransformerManagerType.ROTATE_LINE}_${zIndex}`, {
- zIndex: zIndex - 1,
- evented: false,
- startX: lineLeft,
- startY: lineTop,
- endX: lineLeft,
- endY: lineTop + rotateAnchorOffset,
- strokeWidth: borderStrokeWidth,
- strokeLineCap: 'butt',
- stroke: rotateStroke ?? borderStroke,
- });
-
- const { left: rotateLeft, top: rotateTop } = this._getRotateAnchorPosition(TransformerManagerType.ROTATE, height, width, applyObject);
-
- const cursor = this._getRotateAnchorCursor(TransformerManagerType.ROTATE);
- const rotate = new TransformerAnchor(`${TransformerManagerType.ROTATE}_${zIndex}`, {
- zIndex: zIndex - 1,
- left: rotateLeft,
- top: rotateTop,
- height: rotateSize,
- width: rotateSize,
- radius: rotateCornerRadius,
- fill: rotateFill,
- strokeWidth: rotateStrokeWidth ?? borderStrokeWidth * 2,
- stroke: rotateStroke ?? borderStroke,
- shadowColor: anchorShadowColor,
- shadowBlur: anchorShadowBlur,
- shadowOffsetX: anchorShadowOffsetX,
- shadowOffsetY: anchorShadowOffsetY,
- });
- this._attachEventToRotate(rotate, applyObject);
- this._attachHover(rotate, cursor, CURSOR_TYPE.DEFAULT);
- if (rotateLineEnabled) {
- groupElements.push(rotateLine);
- }
- groupElements.push(rotate);
- if (rotateIconEnabled) {
- groupElements.push(this._createRotateIcon(applyObject, zIndex, rotateLeft, rotateTop));
- }
- }
+ if (resizeEnabled && rotateEnabled && !isCropper) {
+ groupElements.push(...this._createRotationControls(applyObject, zIndex, width, height));
}
if (resizeEnabled) {
- for (let i = 0, len = enabledAnchors.length; i < len; i++) {
- const isEnable = enabledAnchors[i];
- if (isEnable !== 1) {
- continue;
- }
- const type = TransformerManagerTypeArray[i];
- let anchor: BaseObject;
- if (!isCropper) {
- anchor = this._createResizeAnchor(type, applyObject, zIndex);
- } else {
- anchor = this._createCopperResizeAnchor(type, applyObject, zIndex);
- }
- this._attachEventToAnchor(anchor, type, applyObject);
- groupElements.push(anchor);
- }
+ groupElements.push(...this._createResizeControls(applyObject, zIndex, isCropper, enabledAnchors));
}
const transformerControl = new Group(`${TransformerManagerType.GROUP}_${oKey}`, ...groupElements);
@@ -2027,10 +1801,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
scene.addObject(transformerControl, layerIndex);
if (!isCropper) {
- if (this._transformerControlMap.has(oKey)) {
- this._transformerControlMap.get(oKey)!.dispose();
- }
+ this._transformerControlMap.get(oKey)?.dispose();
this._transformerControlMap.set(oKey, transformerControl);
+ this._updateRotationControl(transformerControl, applyObject);
this._createControl$.next(transformerControl);
} else {
this._copperControl = transformerControl;
@@ -2039,6 +1812,191 @@ export class Transformer extends Disposable implements ITransformerConfig {
return transformerControl;
}
+ private _createResizeControls(applyObject: BaseObject, zIndex: number, isCropper: boolean, enabledAnchors: number[]): BaseObject[] {
+ const anchors: BaseObject[] = [];
+ for (let i = 0, len = enabledAnchors.length; i < len; i++) {
+ const isEnable = enabledAnchors[i];
+ if (isEnable !== 1) {
+ continue;
+ }
+ const type = TransformerManagerTypeArray[i];
+ let anchor: BaseObject;
+ if (!isCropper) {
+ anchor = this._createResizeAnchor(type, applyObject, zIndex);
+ } else {
+ anchor = this._createCopperResizeAnchor(type, applyObject, zIndex);
+ }
+ this._attachEventToAnchor(anchor, type, applyObject);
+ anchors.push(anchor);
+ }
+ return anchors;
+ }
+
+ private _createRotationControls(applyObject: BaseObject, zIndex: number, width: number, height: number): BaseObject[] {
+ const config = this._getConfig(applyObject);
+ const { rotateSize, borderStrokeWidth, borderStroke } = config;
+ const position = this._getRotateAnchorPosition(TransformerManagerType.ROTATE, height, width, applyObject);
+ const line = new Line(`${TransformerManagerType.ROTATE_LINE}_${zIndex}`, {
+ startX: 0,
+ startY: 0,
+ endX: 0,
+ endY: 0,
+ zIndex: zIndex - 1,
+ evented: false,
+ strokeWidth: borderStrokeWidth,
+ strokeLineCap: 'butt',
+ stroke: config.rotateStroke ?? borderStroke,
+ });
+ const handle = new TransformerAnchor(`${TransformerManagerType.ROTATE}_${zIndex}`, {
+ zIndex: zIndex - 1,
+ ...position,
+ width: rotateSize,
+ height: rotateSize,
+ radius: config.rotateCornerRadius,
+ fill: config.rotateFill,
+ strokeWidth: config.rotateStrokeWidth ?? borderStrokeWidth * 2,
+ stroke: config.rotateStroke ?? borderStroke,
+ shadowColor: config.anchorShadowColor,
+ shadowBlur: config.anchorShadowBlur,
+ shadowOffsetX: config.anchorShadowOffsetX,
+ shadowOffsetY: config.anchorShadowOffsetY,
+ });
+ const icon = config.rotateIconEnabled ? this._createRotateIcon(applyObject, zIndex, position.left, position.top) : undefined;
+ this._attachEventToRotate(handle, applyObject);
+ this._attachHover(handle, this._getRotateAnchorCursor(TransformerManagerType.ROTATE), CURSOR_TYPE.DEFAULT);
+ this._rotationControls.set(applyObject.oKey, { handle, icon, line });
+ return icon ? [line, handle, icon] : [line, handle];
+ }
+
+ private _updateRotationControls(): void {
+ if (this._finishGesture) return;
+ const obstaclesByViewport = new Map<Viewport, IRotationHandleObstacle[]>();
+ this._updateControlIterator((control, object) => this._updateRotationControl(control as Group, object, obstaclesByViewport));
+ }
+
+ private _getRotationViewport(control: Group): { viewport: Viewport; bounds: IBoundRectNoAngle; corners: Vector2[] } | undefined {
+ let best: ReturnType<Transformer['_getRotationViewport']>;
+ let maxArea = 0;
+ const corners = [new Vector2(0, 0), new Vector2(control.width, 0), new Vector2(control.width, control.height), new Vector2(0, control.height)]
+ .map((point) => control.ancestorTransform.applyPoint(point));
+ for (const viewport of this._scene.getViewports()) {
+ if (!viewport.shouldIntoRender()) continue;
+ const bar = viewport.getScrollBar();
+ const bounds = {
+ left: Math.max(viewport.left, this.zeroLeft * this._scene.scaleX),
+ top: Math.max(viewport.top, this.zeroTop * this._scene.scaleY),
+ right: viewport.left + (viewport.width ?? 0) - (bar?.enableVertical ? bar.totalSize : 0),
+ bottom: viewport.top + (viewport.height ?? 0) - (bar?.enableHorizontal ? bar.totalSize : 0),
+ };
+ const screenCorners = corners.map((point) => viewport.getAbsoluteVector(point.clone()));
+ const left = Math.max(bounds.left, Math.min(...screenCorners.map((point) => point.x)));
+ const top = Math.max(bounds.top, Math.min(...screenCorners.map((point) => point.y)));
+ const right = Math.min(bounds.right, Math.max(...screenCorners.map((point) => point.x)));
+ const bottom = Math.min(bounds.bottom, Math.max(...screenCorners.map((point) => point.y)));
+ const area = Math.max(0, right - left) * Math.max(0, bottom - top);
+ if (area > maxArea) {
+ maxArea = area;
+ best = { viewport, bounds, corners: screenCorners };
+ }
+ }
+ return best;
+ }
+
+ private _getRotationObstacles(viewport: Viewport) {
+ return this._scene.getAllObjectsByOrderForPick()
+ .filter((object) => object instanceof Control && object.visible && object.evented && !object.oKey.includes(TransformerManagerType.ROTATE))
+ .map((object) => {
+ const transform = object.ancestorTransform;
+ const center = viewport.getAbsoluteVector(transform.applyPoint(new Vector2(object.width / 2, object.height / 2)));
+ const corner = viewport.getAbsoluteVector(transform.applyPoint(new Vector2(0, 0)));
+ return { ...center, radius: Math.hypot(corner.x - center.x, corner.y - center.y) };
+ });
+ }
+
+ private _updateRotationControl(control: Group, applyObject: BaseObject, obstaclesByViewport = new Map<Viewport, IRotationHandleObstacle[]>()): void {
+ const controls = this._rotationControls.get(applyObject.oKey);
+ if (!controls) return;
+ const view = this._getRotationViewport(control);
+ if (!view) {
+ this._hideRotationControls(controls);
+ return;
+ }
+ const { viewport, bounds, corners } = view;
+ let obstacles = obstaclesByViewport.get(viewport);
+ if (!obstacles) {
+ obstacles = this._getRotationObstacles(viewport);
+ obstaclesByViewport.set(viewport, obstacles);
+ }
+ const config = this._getConfig(applyObject);
+ const transform = control.ancestorTransform;
+ const toScreen = (point: Vector2) => viewport.getAbsoluteVector(transform.applyPoint(point));
+ const candidate = (side: 'top' | 'bottom'): IRotationHandleCandidate => {
+ const direction = side === 'top' ? -1 : 1;
+ const edge = side === 'top' ? 0 : control.height;
+ return {
+ side,
+ center: toScreen(new Vector2(control.width / 2, edge + direction * (config.rotateAnchorOffset + config.borderSpacing + config.borderStrokeWidth * 2 + config.rotateSize / 2))),
+ attachment: toScreen(new Vector2(control.width / 2, edge + direction * (config.borderSpacing + config.borderStrokeWidth))),
+ };
+ };
+ const center = toScreen(new Vector2(control.width / 2, control.height / 2));
+ const scale = this._scene.getAncestorScale();
+ const artworkRadius = (config.rotateSize / 2 + controls.handle.strokeWidth) * Math.max(scale.scaleX, scale.scaleY);
+ const placement = placeRotationHandle({
+ bounds,
+ corners,
+ radius: Math.max(CONTROL_TOUCH_HIT_RADIUS, artworkRadius),
+ artworkRadius,
+ preferred: candidate(config.rotateAnchorPosition),
+ opposite: candidate(config.rotateAnchorPosition === 'top' ? 'bottom' : 'top'),
+ obstacles: [...obstacles, { ...center, radius: 0 }],
+ previousSide: this._rotationSides.get(applyObject.oKey),
+ });
+ if (!placement) {
+ this._hideRotationControls(controls);
+ return;
+ }
+ this._rotationSides.set(applyObject.oKey, placement.side);
+ const toLocal = (point: IPoint) => transform.clone().invert().applyPoint(viewport.transformVector2SceneCoord(new Vector2(point.x, point.y)));
+ this._positionRotationControls(controls, toLocal(placement.center), toLocal(placement.attachment), config.rotateLineEnabled || placement.adjusted);
+ }
+
+ private _hideRotationControls(controls: { handle: Control; icon?: Rect; line: Line }): void {
+ for (const control of Object.values(controls)) {
+ if (control?.visible) {
+ control.hide();
+ this._scene.makeDirty();
+ }
+ }
+ }
+
+ private _positionRotationControls(controls: { handle: Control; icon?: Rect; line: Line }, center: Vector2, attachment: Vector2, showLine: boolean): void {
+ const { handle, icon, line } = controls;
+ const left = center.x - handle.width / 2 - handle.strokeWidth / 2;
+ const top = center.y - handle.height / 2 - handle.strokeWidth / 2;
+ if (Math.abs(handle.left - left) > 0.01 || Math.abs(handle.top - top) > 0.01) {
+ this._scene.makeDirty();
+ handle.transformByState({ left, top });
+ icon?.transformByState({ left: center.x - icon.width / 2 - icon.strokeWidth / 2, top: center.y - icon.height / 2 - icon.strokeWidth / 2 });
+ }
+ if (!handle.visible) {
+ this._scene.makeDirty();
+ handle.show();
+ }
+ if (icon && !icon.visible) icon.show();
+ const distance = Math.hypot(center.x - attachment.x, center.y - attachment.y);
+ const t = Math.max(0, 1 - handle.width / 2 / Math.max(distance, 1));
+ const endX = attachment.x + (center.x - attachment.x) * t;
+ const endY = attachment.y + (center.y - attachment.y) * t;
+ if (line.startX !== attachment.x || line.startY !== attachment.y || line.endX !== endX || line.endY !== endY) {
+ this._scene.makeDirty();
+ line.setProps({ startX: attachment.x, startY: attachment.y, endX, endY });
+ }
+ if (showLine !== line.visible) this._scene.makeDirty();
+ if (showLine && !line.visible) line.show();
+ else if (!showLine && line.visible) line.hide();
+ }
+
private _getTopScene() {
const currentScene = this.getScene();
return currentScene.getEngine()?.activeScene as Nullable<Scene>;
@@ -2067,6 +2025,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
if (!evt.ctrlKey) {
this._selectedObjectMap.clear();
+ this._rotationSides.clear();
this._clearControlMap();
}
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index f636b87702..622847f787 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -15,6 +15,8 @@
*/
import type { Nullable } from '@univerjs/core';
+import { Disposable, EventSubject, sortRules, sortRulesByDesc, toDisposable, Tools } from '@univerjs/core';
+import { BehaviorSubject, Subject } from 'rxjs';
import type { BaseObject } from './base-object';
import type { IDragEvent, IMouseEvent, IPointerEvent, IWheelEvent } from './basics/i-events';
import type { ISceneTransformState, ITransformChangeState } from './basics/interfaces';
@@ -26,8 +28,6 @@ import type { Engine } from './engine';
import type { ILayerRenderOptions, IScrollRenderInfo } from './layer';
import type { SceneViewer } from './scene-viewer';
import type { Viewport } from './viewport';
-import { Disposable, EventSubject, sortRules, sortRulesByDesc, toDisposable, Tools } from '@univerjs/core';
-import { BehaviorSubject } from 'rxjs';
import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
import { DeviceType } from './basics/i-events';
import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
@@ -238,6 +238,9 @@ export class Scene extends Disposable {
onTripleClick$ = new EventSubject<IPointerEvent | IMouseEvent>();
onMouseWheel$ = new EventSubject<IWheelEvent>();
+ private readonly _prepareRender$ = new Subject<void>();
+ /** Layout updates before scroll-cache decisions; paint on the canvas in beforeRender$ instead. */
+ readonly prepareRender$ = this._prepareRender$.asObservable();
private _beforeRender$ = new BehaviorSubject<Nullable<Canvas>>(null);
readonly beforeRender$ = this._beforeRender$.asObservable();
private _afterRender$ = new BehaviorSubject<Nullable<Canvas>>(null);
@@ -1017,6 +1020,7 @@ export class Scene extends Disposable {
const layers = this._layers.sort(sortRules);
const canvasInstance = this.getEngine()?.getCanvas();
+ this._prepareRender$.next();
const shouldTryPreservingEngine = this._preserveEngineOnRender &&
!this._hasPostRenderCanvasMutation &&
parentCtx == null &&
@@ -1248,6 +1252,7 @@ export class Scene extends Disposable {
this._inputManager = null;
this._transformer?.dispose();
this._transformer = null;
+ this._prepareRender$.complete();
this.onFileLoaded$.complete();
this.onClick$.complete();
diff --git a/packages/engine-render/src/shape/control.ts b/packages/engine-render/src/shape/control.ts
index b7fc86364a..cb736d5c77 100644
--- a/packages/engine-render/src/shape/control.ts
+++ b/packages/engine-render/src/shape/control.ts
@@ -17,7 +17,7 @@
import { Vector2 } from '../basics/vector2';
import { Rect } from './rect';
-const CONTROL_TOUCH_HIT_RADIUS = 22;
+export const CONTROL_TOUCH_HIT_RADIUS = 22;
/** A precise mouse handle with a zoom-independent touch target. */
export class Control extends Rect {
diff --git a/packages/engine-render/src/transformer-rotation.ts b/packages/engine-render/src/transformer-rotation.ts
new file mode 100644
index 0000000000..9fe06ac6f1
--- /dev/null
+++ b/packages/engine-render/src/transformer-rotation.ts
@@ -0,0 +1,155 @@
+/**
+ * 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 { IBoundRectNoAngle, IPoint } from './basics/vector2';
+
+export interface IRotationHandleCandidate {
+ center: IPoint;
+ attachment: IPoint;
+ side: 'top' | 'bottom';
+}
+
+export interface IRotationHandlePlacement {
+ center: IPoint;
+ attachment: IPoint;
+ side: 'top' | 'bottom' | 'inset';
+ adjusted: boolean;
+}
+
+export interface IRotationHandleObstacle extends IPoint {
+ radius: number;
+}
+
+export interface IRotationHandleLayout {
+ bounds: IBoundRectNoAngle;
+ radius: number;
+ artworkRadius: number;
+ preferred: IRotationHandleCandidate;
+ opposite: IRotationHandleCandidate;
+ corners: IPoint[];
+ obstacles: IRotationHandleObstacle[];
+ previousSide?: IRotationHandlePlacement['side'];
+}
+
+const EDGE_GAP = 8;
+const RETURN_GAP = 12;
+const CONTROL_GAP = 4;
+
+function distanceSquared(a: IPoint, b: IPoint): number {
+ return (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
+}
+
+function contains(bounds: IBoundRectNoAngle, point: IPoint, margin = 0): boolean {
+ return point.x >= bounds.left + margin && point.x <= bounds.right - margin &&
+ point.y >= bounds.top + margin && point.y <= bounds.bottom - margin;
+}
+
+function isClear(point: IPoint, radius: number, obstacles: IRotationHandleObstacle[]): boolean {
+ return obstacles.every((obstacle) => distanceSquared(point, obstacle) >= (radius + obstacle.radius + CONTROL_GAP) ** 2);
+}
+
+function shorten(candidate: IRotationHandleCandidate, bounds: IBoundRectNoAngle): IPoint | undefined {
+ let start = 0;
+ let end = 1;
+ for (const axis of ['x', 'y'] as const) {
+ const from = candidate.attachment[axis];
+ const delta = candidate.center[axis] - from;
+ const min = axis === 'x' ? bounds.left : bounds.top;
+ const max = axis === 'x' ? bounds.right : bounds.bottom;
+ if (Math.abs(delta) < 1e-8) {
+ if (from < min || from > max) return;
+ continue;
+ }
+ const first = (min - from) / delta;
+ const last = (max - from) / delta;
+ start = Math.max(start, Math.min(first, last));
+ end = Math.min(end, Math.max(first, last));
+ }
+ if (start > end) return;
+ return {
+ x: candidate.attachment.x + (candidate.center.x - candidate.attachment.x) * end,
+ y: candidate.attachment.y + (candidate.center.y - candidate.attachment.y) * end,
+ };
+}
+
+function nearestAttachment(point: IPoint, corners: IPoint[]): IPoint {
+ const projections = corners.map((a, index) => {
+ const b = corners[(index + 1) % corners.length];
+ const length = distanceSquared(a, b);
+ const t = length ? Math.max(0, Math.min(1, ((point.x - a.x) * (b.x - a.x) + (point.y - a.y) * (b.y - a.y)) / length)) : 0;
+ return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
+ });
+ return projections.reduce((best, next) => distanceSquared(next, point) < distanceSquared(best, point) ? next : best);
+}
+
+function insetCandidates(layout: IRotationHandleLayout, bounds: IBoundRectNoAngle): IPoint[] {
+ const { preferred, opposite, obstacles, artworkRadius } = layout;
+ const clamp = (point: IPoint) => ({
+ x: Math.max(bounds.left, Math.min(bounds.right, point.x)),
+ y: Math.max(bounds.top, Math.min(bounds.bottom, point.y)),
+ });
+ const candidates = [preferred.center, opposite.center];
+ for (const x of [bounds.left, (bounds.left + bounds.right) / 2, bounds.right]) {
+ for (const y of [bounds.top, (bounds.top + bounds.bottom) / 2, bounds.bottom]) {
+ candidates.push({ x, y });
+ }
+ }
+ for (const obstacle of obstacles) {
+ const gap = artworkRadius + obstacle.radius + CONTROL_GAP;
+ candidates.push(
+ { x: obstacle.x - gap, y: obstacle.y },
+ { x: obstacle.x + gap, y: obstacle.y },
+ { x: obstacle.x, y: obstacle.y - gap },
+ { x: obstacle.x, y: obstacle.y + gap }
+ );
+ }
+ return candidates.map(clamp);
+}
+
+/** Keep the complete interaction target inside the viewport; all distances are screen pixels. */
+export function placeRotationHandle(layout: IRotationHandleLayout): IRotationHandlePlacement | undefined {
+ const { radius, artworkRadius, preferred, opposite, obstacles, previousSide } = layout;
+ const inset = radius + EDGE_GAP;
+ const bounds = {
+ left: layout.bounds.left + inset,
+ top: layout.bounds.top + inset,
+ right: layout.bounds.right - inset,
+ bottom: layout.bounds.bottom - inset,
+ };
+ if (bounds.left > bounds.right || bounds.top > bounds.bottom) return;
+
+ const canReturn = !previousSide || previousSide === preferred.side || contains(bounds, preferred.center, RETURN_GAP);
+ const candidates = canReturn ? [preferred, opposite] : [opposite, preferred];
+ for (const candidate of candidates) {
+ const center = shorten(candidate, bounds);
+ if (center && isClear(center, artworkRadius, obstacles)) {
+ return { ...candidate, center, adjusted: candidate !== preferred || distanceSquared(center, preferred.center) > 0.01 };
+ }
+ }
+
+ let center: IPoint | undefined;
+ let nearestDistance = Infinity;
+ for (const point of insetCandidates(layout, bounds)) {
+ const distance = distanceSquared(point, preferred.center);
+ // A farther candidate cannot improve placement, so skip its collision scan.
+ if (distance < nearestDistance && isClear(point, artworkRadius, obstacles)) {
+ center = point;
+ nearestDistance = distance;
+ }
+ }
+ if (!center) return;
+ return { center, attachment: nearestAttachment(center, layout.corners), side: 'inset', adjusted: true };
+}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-command-test-utils.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-command-test-utils.ts
new file mode 100644
index 0000000000..1554255799
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-command-test-utils.ts
@@ -0,0 +1,67 @@
+/**
+ * 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 { ISheetDrawing } from '@univerjs/sheets-drawing';
+import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import { InsertSheetDrawingCommand } from '@univerjs/sheets-drawing';
+import type { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+
+export function createSheetDrawing(drawingId: string, left: number, top: number): ISheetDrawing {
+ return {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.URL,
+ source: `https://example.com/${drawingId}.png`,
+ transform: {
+ left,
+ top,
+ width: 100,
+ height: 80,
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ },
+ sheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
+ },
+ axisAlignSheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
+ },
+ };
+}
+
+export async function insertDrawings(testBed: ReturnType<typeof createSheetsDrawingUiTestBed>, drawings: ISheetDrawing[]) {
+ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings,
+ });
+}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
deleted file mode 100644
index 4062accaa5..0000000000
--- a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
+++ /dev/null
@@ -1,423 +0,0 @@
-/**
- * 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 { ISheetDrawing } from '@univerjs/sheets-drawing';
-import { Direction, DrawingTypeEnum, ImageSourceType, IUndoRedoService } from '@univerjs/core';
-import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
-import { insertGroupObject } from '@univerjs/drawing-ui';
-import {
- DrawingGroupObject,
- Engine,
- Image,
- IRenderManagerService,
- MAIN_VIEW_PORT_KEY,
- Rect,
- Scene,
- Vector2,
- Viewport,
-} from '@univerjs/engine-render';
-import { InsertSheetDrawingCommand, ISheetDrawingService, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
-import { FlipSheetDrawingCommand } from '../flip-drawings.command';
-import { GroupSheetDrawingCommand } from '../group-sheet-drawing.command';
-import { MoveDrawingsCommand } from '../move-drawings.command';
-import { UngroupSheetDrawingCommand } from '../ungroup-sheet-drawing.command';
-
-function createSheetDrawing(drawingId: string, left: number, top: number): ISheetDrawing {
- return {
- unitId: 'test',
- subUnitId: 'sheet1',
- drawingId,
- drawingType: DrawingTypeEnum.DRAWING_IMAGE,
- imageSourceType: ImageSourceType.URL,
- source: `https://example.com/${drawingId}.png`,
- transform: {
- left,
- top,
- width: 100,
- height: 80,
- angle: 0,
- flipX: false,
- flipY: false,
- skewX: 0,
- skewY: 0,
- },
- sheetTransform: {
- angle: 0,
- flipX: false,
- flipY: false,
- skewX: 0,
- skewY: 0,
- from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
- to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
- },
- axisAlignSheetTransform: {
- angle: 0,
- flipX: false,
- flipY: false,
- skewX: 0,
- skewY: 0,
- from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
- to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
- },
- };
-}
-
-async function insertDrawings(testBed: ReturnType<typeof createSheetsDrawingUiTestBed>, drawings: ISheetDrawing[]) {
- await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
- unitId: testBed.unitId,
- drawings,
- });
-}
-
-class TestRenderManagerService {
- private _srcRect: { left?: number; top?: number; right?: number; bottom?: number } | undefined;
-
- setImageSrcRect(srcRect: { left?: number; top?: number; right?: number; bottom?: number }): void {
- this._srcRect = srcRect;
- }
-
- getRenderUnitById() {
- return {
- scene: {
- getObject: () => ({
- srcRect: this._srcRect,
- }),
- },
- };
- }
-}
-
-describe('sheet drawing UI commands', () => {
- it.each([[false, false], [true, false], [false, true], [true, true]])('restores sheet group picking and stacking with flips %s/%s', async (flipX, flipY) => {
- const contextSpy = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
- return { canvas: this, setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D;
- });
- const testBed = createSheetsDrawingUiTestBed();
- const engine = new Engine('group-engine', { elementWidth: 800, elementHeight: 500, dpr: 1 });
- const scene = new Scene('group-scene', engine);
- const viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, { left: 0, top: 0, width: 800, height: 500, active: true });
- try {
- testBed.commandService.registerCommand(GroupSheetDrawingCommand);
- const children = [createSheetDrawing('child-1', 0, 0), createSheetDrawing('child-2', 100, 80)];
- await insertDrawings(testBed, [createSheetDrawing('background', 0, 0), ...children]);
- const parent = {
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'group-1',
- drawingType: DrawingTypeEnum.DRAWING_GROUP,
- transform: { left: 100, top: 100, width: 200, height: 160, flipX, flipY },
- groupBaseBound: { left: 0, top: 0, width: 200, height: 160 },
- };
- expect(await testBed.commandService.executeCommand(GroupSheetDrawingCommand.id, [{
- parent,
- children: children.map((child) => ({ ...child, groupId: parent.drawingId })),
- }])).toBe(true);
- const manager = testBed.get(IDrawingManagerService);
- for (const child of children) {
- const object = new Image(getDrawingShapeKeyByDrawingSearch(child), { ...child.transform });
- scene.addObject(object, 7);
- insertGroupObject(parent, object, scene, manager);
- }
- const group = scene.getObjectIncludeInGroup(getDrawingShapeKeyByDrawingSearch(parent)) as DrawingGroupObject;
- expect(group).toBeInstanceOf(DrawingGroupObject);
- expect(group.getObjects()).toHaveLength(2);
- expect(group.layer?.zIndex).toBe(7);
- expect(group.zIndex).toBe(manager.getDrawingOrder(parent.unitId, parent.subUnitId).indexOf(parent.drawingId));
- const point = new Vector2(flipX ? 275 : 125, flipY ? 240 : 120);
- expect(scene.pick(point)).toBe(group);
- const overlay = new Rect('overlay', { left: 100, top: 100, width: 200, height: 160, fill: '#993333' });
- overlay.zIndex = group.zIndex + 1;
- scene.addObject(overlay, 7);
- expect(scene.pick(point)).toBe(overlay);
- overlay.zIndex = group.zIndex - 1;
- expect(scene.pick(point)).toBe(group);
- if (flipX !== flipY) {
- expect(group.isHit(new Vector2(125, 120))).toBe(false);
- }
- } finally {
- viewport.dispose();
- scene.dispose();
- engine.dispose();
- testBed.univer.dispose();
- contextSpy.mockRestore();
- }
- });
-
- afterEach(() => {
- // each test disposes its own univer instance
- });
-
- it('persists an online OLE link with symmetric drawing mutations', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- const service = testBed.get(ISheetDrawingService);
- const drawing = { ...createSheetDrawing('ole-1', 10, 20), drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained' };
- await insertDrawings(testBed, [drawing]);
- const online = { unitId: 'child', type: 1 };
- expect(await testBed.commandService.executeCommand(SetSheetDrawingCommand.id, { unitId: testBed.unitId, drawings: [{ ...drawing, oleOnlineUnit: online, oleFileName: '预算.xlsx' }] })).toBe(true);
- expect(JSON.parse(JSON.stringify(service.getDrawingByParam(drawing)))).toMatchObject({ oleAttachmentId: 'retained', oleOnlineUnit: online, oleFileName: '预算.xlsx' });
- const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;
- for (const mutation of history.undoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
- expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleOnlineUnit');
- expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleFileName');
- for (const mutation of history.redoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
- expect(service.getDrawingByParam(drawing)).toMatchObject({ oleOnlineUnit: online, oleFileName: '预算.xlsx' });
- testBed.univer.dispose();
- });
-
- it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE])('moves drawing type %s and replays geometry through undo and redo', async (drawingType) => {
- const testBed = createSheetsDrawingUiTestBed();
- const sheetDrawingService = testBed.get(ISheetDrawingService);
- testBed.commandService.registerCommand(MoveDrawingsCommand);
- const drawing = { ...createSheetDrawing('drawing-1', 10, 20), drawingType, oleAttachmentId: 'retained-attachment' };
- await insertDrawings(testBed, [drawing]);
- sheetDrawingService.focusDrawing([{
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'drawing-1',
- }]);
-
- expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.RIGHT })).toBe(true);
-
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'drawing-1',
- })?.transform).toMatchObject({
- left: 11,
- top: 20,
- });
-
- const param = { unitId: testBed.unitId, subUnitId: testBed.subUnitId, drawingId: 'drawing-1' };
- const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;
- for (const mutation of history.undoMutations) {
- testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
- }
- expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 10, top: 20 } });
- for (const mutation of history.redoMutations) {
- testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
- }
- expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 11, top: 20 } });
-
- testBed.univer.dispose();
- });
-
- it('keeps drawing positions unchanged when move is triggered without a focused drawing', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- const sheetDrawingService = testBed.get(ISheetDrawingService);
- testBed.commandService.registerCommand(MoveDrawingsCommand);
- await insertDrawings(testBed, [createSheetDrawing('drawing-2', 30, 40)]);
-
- expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.UP })).toBe(false);
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'drawing-2',
- })?.transform).toMatchObject({
- left: 30,
- top: 40,
- });
-
- testBed.univer.dispose();
- });
-
- it('returns false when flip is triggered without command parameters', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- testBed.commandService.registerCommand(FlipSheetDrawingCommand);
-
- expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id)).toBe(false);
-
- testBed.univer.dispose();
- });
-
- it('skips drawings that are missing from the drawing model or lack a sheet skeleton', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- testBed.commandService.registerCommand(FlipSheetDrawingCommand);
- await insertDrawings(testBed, [
- {
- ...createSheetDrawing('detached-drawing', 5, 6),
- unitId: 'detached-unit',
- },
- ]);
-
- expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
- unitId: testBed.unitId,
- drawings: [
- {
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'missing-drawing',
- },
- {
- unitId: 'detached-unit',
- subUnitId: testBed.subUnitId,
- drawingId: 'detached-drawing',
- },
- ],
- flipH: true,
- })).toBe(false);
-
- testBed.univer.dispose();
- });
-
- it('flips a drawing horizontally and vertically in the sheet drawing model', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- const sheetDrawingService = testBed.get(ISheetDrawingService);
- testBed.commandService.registerCommand(FlipSheetDrawingCommand);
- await insertDrawings(testBed, [createSheetDrawing('drawing-3', 50, 60)]);
-
- expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
- unitId: testBed.unitId,
- drawings: [{
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'drawing-3',
- }],
- flipH: true,
- flipV: true,
- })).toBe(true);
-
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'drawing-3',
- })?.transform).toMatchObject({
- flipX: true,
- flipY: true,
- });
-
- testBed.univer.dispose();
- });
-
- it('updates the image crop rectangle when flipping a cropped drawing', async () => {
- const testBed = createSheetsDrawingUiTestBed(undefined, [
- [IRenderManagerService, { useClass: TestRenderManagerService as never }],
- ]);
- const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
- const sheetDrawingService = testBed.get(ISheetDrawingService);
- renderManagerService.setImageSrcRect({ right: 24, bottom: 36 });
- testBed.commandService.registerCommand(FlipSheetDrawingCommand);
- await insertDrawings(testBed, [createSheetDrawing('cropped-drawing', 50, 60)]);
-
- expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
- unitId: testBed.unitId,
- drawings: [{
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'cropped-drawing',
- }],
- flipH: true,
- flipV: true,
- })).toBe(true);
-
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'cropped-drawing',
- })).toMatchObject({
- srcRect: {
- left: 0,
- top: 0,
- right: 24,
- bottom: 36,
- },
- transform: {
- flipX: true,
- flipY: true,
- },
- });
-
- testBed.univer.dispose();
- });
-
- it('groups two drawings and then ungroups them back to standalone drawings', async () => {
- const testBed = createSheetsDrawingUiTestBed();
- const sheetDrawingService = testBed.get(ISheetDrawingService);
- testBed.commandService.registerCommand(GroupSheetDrawingCommand);
- testBed.commandService.registerCommand(UngroupSheetDrawingCommand);
- await insertDrawings(testBed, [
- createSheetDrawing('child-1', 10, 20),
- createSheetDrawing('child-2', 40, 60),
- ]);
-
- const parent = {
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'group-1',
- drawingType: DrawingTypeEnum.DRAWING_GROUP,
- transform: { left: 0, top: 0, width: 140, height: 120 },
- groupBaseBound: { left: 0, top: 0, width: 140, height: 120 },
- };
- const groupedChildren = [
- {
- ...createSheetDrawing('child-1', 10, 20),
- groupId: 'group-1',
- },
- {
- ...createSheetDrawing('child-2', 40, 60),
- groupId: 'group-1',
- },
- ];
-
- expect(await testBed.commandService.executeCommand(GroupSheetDrawingCommand.id, [{
- parent,
- children: groupedChildren,
- }])).toBe(true);
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'group-1',
- })).toMatchObject({
- drawingType: DrawingTypeEnum.DRAWING_GROUP,
- });
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'child-1',
- })).toMatchObject({
- groupId: 'group-1',
- });
-
- const ungroupedChildren = [
- {
- ...createSheetDrawing('child-1', 10, 20),
- groupId: undefined,
- },
- {
- ...createSheetDrawing('child-2', 40, 60),
- groupId: undefined,
- },
- ];
- expect(await testBed.commandService.executeCommand(UngroupSheetDrawingCommand.id, [{
- parent,
- children: ungroupedChildren,
- }])).toBe(true);
-
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'group-1',
- })).toBeUndefined();
- expect(sheetDrawingService.getDrawingByParam({
- unitId: testBed.unitId,
- subUnitId: testBed.subUnitId,
- drawingId: 'child-1',
- })?.groupId).toBeUndefined();
-
- testBed.univer.dispose();
- });
-});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/flip-drawings.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/flip-drawings.command.spec.ts
new file mode 100644
index 0000000000..88dee1345f
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/flip-drawings.command.spec.ts
@@ -0,0 +1,151 @@
+/**
+ * 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 { IRenderManagerService } from '@univerjs/engine-render';
+import { ISheetDrawingService } from '@univerjs/sheets-drawing';
+import { describe, expect, it } from 'vitest';
+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { FlipSheetDrawingCommand } from '../flip-drawings.command';
+import { createSheetDrawing, insertDrawings } from './drawing-command-test-utils';
+
+class TestRenderManagerService {
+ private _srcRect: { left?: number; top?: number; right?: number; bottom?: number } | undefined;
+
+ setImageSrcRect(srcRect: { left?: number; top?: number; right?: number; bottom?: number }): void {
+ this._srcRect = srcRect;
+ }
+
+ getRenderUnitById() {
+ return {
+ scene: {
+ getObject: () => ({
+ srcRect: this._srcRect,
+ }),
+ },
+ };
+ }
+}
+
+describe('FlipSheetDrawingCommand', () => {
+ it('returns false when flip is triggered without command parameters', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);
+
+ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id)).toBe(false);
+
+ testBed.univer.dispose();
+ });
+
+ it('skips drawings that are missing from the drawing model or lack a sheet skeleton', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);
+ await insertDrawings(testBed, [
+ {
+ ...createSheetDrawing('detached-drawing', 5, 6),
+ unitId: 'detached-unit',
+ },
+ ]);
+
+ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings: [
+ {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'missing-drawing',
+ },
+ {
+ unitId: 'detached-unit',
+ subUnitId: testBed.subUnitId,
+ drawingId: 'detached-drawing',
+ },
+ ],
+ flipH: true,
+ })).toBe(false);
+
+ testBed.univer.dispose();
+ });
+
+ it('flips a drawing horizontally and vertically in the sheet drawing model', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);
+ await insertDrawings(testBed, [createSheetDrawing('drawing-3', 50, 60)]);
+
+ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings: [{
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-3',
+ }],
+ flipH: true,
+ flipV: true,
+ })).toBe(true);
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-3',
+ })?.transform).toMatchObject({
+ flipX: true,
+ flipY: true,
+ });
+
+ testBed.univer.dispose();
+ });
+
+ it('updates the image crop rectangle when flipping a cropped drawing', async () => {
+ const testBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ ]);
+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ renderManagerService.setImageSrcRect({ right: 24, bottom: 36 });
+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);
+ await insertDrawings(testBed, [createSheetDrawing('cropped-drawing', 50, 60)]);
+
+ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings: [{
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'cropped-drawing',
+ }],
+ flipH: true,
+ flipV: true,
+ })).toBe(true);
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'cropped-drawing',
+ })).toMatchObject({
+ srcRect: {
+ left: 0,
+ top: 0,
+ right: 24,
+ bottom: 36,
+ },
+ transform: {
+ flipX: true,
+ flipY: true,
+ },
+ });
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/group-sheet-drawing.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/group-sheet-drawing.command.spec.ts
new file mode 100644
index 0000000000..9f519eadca
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/group-sheet-drawing.command.spec.ts
@@ -0,0 +1,160 @@
+/**
+ * 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 { DrawingTypeEnum } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
+import { insertGroupObject } from '@univerjs/drawing-ui';
+import { DrawingGroupObject, Engine, Image, MAIN_VIEW_PORT_KEY, Rect, Scene, Vector2, Viewport } from '@univerjs/engine-render';
+import { ISheetDrawingService } from '@univerjs/sheets-drawing';
+import { describe, expect, it, vi } from 'vitest';
+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { GroupSheetDrawingCommand } from '../group-sheet-drawing.command';
+import { UngroupSheetDrawingCommand } from '../ungroup-sheet-drawing.command';
+import { createSheetDrawing, insertDrawings } from './drawing-command-test-utils';
+
+describe('GroupSheetDrawingCommand', () => {
+ it.each([[false, false], [true, false], [false, true], [true, true]])('restores sheet group picking and stacking with flips %s/%s', async (flipX, flipY) => {
+ const contextSpy = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
+ return { canvas: this, setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D;
+ });
+ const testBed = createSheetsDrawingUiTestBed();
+ const engine = new Engine('group-engine', { elementWidth: 800, elementHeight: 500, dpr: 1 });
+ const scene = new Scene('group-scene', engine);
+ const viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, { left: 0, top: 0, width: 800, height: 500, active: true });
+ try {
+ testBed.commandService.registerCommand(GroupSheetDrawingCommand);
+ const children = [createSheetDrawing('child-1', 0, 0), createSheetDrawing('child-2', 100, 80)];
+ await insertDrawings(testBed, [createSheetDrawing('background', 0, 0), ...children]);
+ const parent = {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: { left: 100, top: 100, width: 200, height: 160, flipX, flipY },
+ groupBaseBound: { left: 0, top: 0, width: 200, height: 160 },
+ };
+ expect(await testBed.commandService.executeCommand(GroupSheetDrawingCommand.id, [{
+ parent,
+ children: children.map((child) => ({ ...child, groupId: parent.drawingId })),
+ }])).toBe(true);
+ const manager = testBed.get(IDrawingManagerService);
+ for (const child of children) {
+ const object = new Image(getDrawingShapeKeyByDrawingSearch(child), { ...child.transform });
+ scene.addObject(object, 7);
+ insertGroupObject(parent, object, scene, manager);
+ }
+ const group = scene.getObjectIncludeInGroup(getDrawingShapeKeyByDrawingSearch(parent)) as DrawingGroupObject;
+ expect(group).toBeInstanceOf(DrawingGroupObject);
+ expect(group.getObjects()).toHaveLength(2);
+ expect(group.layer?.zIndex).toBe(7);
+ expect(group.zIndex).toBe(manager.getDrawingOrder(parent.unitId, parent.subUnitId).indexOf(parent.drawingId));
+ const point = new Vector2(flipX ? 275 : 125, flipY ? 240 : 120);
+ expect(scene.pick(point)).toBe(group);
+ const overlay = new Rect('overlay', { left: 100, top: 100, width: 200, height: 160, fill: '#993333' });
+ overlay.zIndex = group.zIndex + 1;
+ scene.addObject(overlay, 7);
+ expect(scene.pick(point)).toBe(overlay);
+ overlay.zIndex = group.zIndex - 1;
+ expect(scene.pick(point)).toBe(group);
+ if (flipX !== flipY) {
+ expect(group.isHit(new Vector2(125, 120))).toBe(false);
+ }
+ } finally {
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ testBed.univer.dispose();
+ contextSpy.mockRestore();
+ }
+ });
+
+ it('groups two drawings and then ungroups them back to standalone drawings', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(GroupSheetDrawingCommand);
+ testBed.commandService.registerCommand(UngroupSheetDrawingCommand);
+ await insertDrawings(testBed, [
+ createSheetDrawing('child-1', 10, 20),
+ createSheetDrawing('child-2', 40, 60),
+ ]);
+
+ const parent = {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: { left: 0, top: 0, width: 140, height: 120 },
+ groupBaseBound: { left: 0, top: 0, width: 140, height: 120 },
+ };
+ const groupedChildren = [
+ {
+ ...createSheetDrawing('child-1', 10, 20),
+ groupId: 'group-1',
+ },
+ {
+ ...createSheetDrawing('child-2', 40, 60),
+ groupId: 'group-1',
+ },
+ ];
+
+ expect(await testBed.commandService.executeCommand(GroupSheetDrawingCommand.id, [{
+ parent,
+ children: groupedChildren,
+ }])).toBe(true);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'group-1',
+ })).toMatchObject({
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ });
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'child-1',
+ })).toMatchObject({
+ groupId: 'group-1',
+ });
+
+ const ungroupedChildren = [
+ {
+ ...createSheetDrawing('child-1', 10, 20),
+ groupId: undefined,
+ },
+ {
+ ...createSheetDrawing('child-2', 40, 60),
+ groupId: undefined,
+ },
+ ];
+ expect(await testBed.commandService.executeCommand(UngroupSheetDrawingCommand.id, [{
+ parent,
+ children: ungroupedChildren,
+ }])).toBe(true);
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'group-1',
+ })).toBeUndefined();
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'child-1',
+ })?.groupId).toBeUndefined();
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/move-drawings.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/move-drawings.command.spec.ts
new file mode 100644
index 0000000000..b57d7ba520
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/move-drawings.command.spec.ts
@@ -0,0 +1,126 @@
+/**
+ * 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 { Direction, DrawingTypeEnum, IUndoRedoService } from '@univerjs/core';
+import { SheetSkeletonService } from '@univerjs/sheets';
+import { ISheetDrawingService } from '@univerjs/sheets-drawing';
+import { describe, expect, it } from 'vitest';
+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { MoveDrawingsCommand } from '../move-drawings.command';
+import { createSheetDrawing, insertDrawings } from './drawing-command-test-utils';
+
+describe('MoveDrawingsCommand', () => {
+ it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE, DrawingTypeEnum.DRAWING_SHAPE])('moves drawing type %s and replays geometry through undo and redo', async (drawingType) => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(MoveDrawingsCommand);
+ const drawing = { ...createSheetDrawing('drawing-1', 100, 100), drawingType, oleAttachmentId: 'retained-attachment' };
+ await insertDrawings(testBed, [drawing]);
+ sheetDrawingService.focusDrawing([{
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-1',
+ }]);
+
+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.RIGHT })).toBe(true);
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-1',
+ })?.transform).toMatchObject({
+ left: 101,
+ top: 100,
+ });
+
+ const param = { unitId: testBed.unitId, subUnitId: testBed.subUnitId, drawingId: 'drawing-1' };
+ const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;
+ for (const mutation of history.undoMutations) {
+ testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
+ }
+ expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 100, top: 100 } });
+ for (const mutation of history.redoMutations) {
+ testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
+ }
+ expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 101, top: 100 } });
+
+ testBed.univer.dispose();
+ });
+
+ it.each([Direction.LEFT, Direction.UP, Direction.RIGHT, Direction.DOWN])('stops keyboard movement at worksheet edge %s without adding undo history', async (direction) => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const service = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(MoveDrawingsCommand);
+ try {
+ const skeleton = testBed.get(SheetSkeletonService).getSkeleton(testBed.unitId, testBed.subUnitId)!;
+ const left = direction === Direction.RIGHT
+ ? skeleton.rowHeaderWidthAndMarginLeft + skeleton.columnTotalWidth - 100
+ : skeleton.rowHeaderWidthAndMarginLeft;
+ const top = direction === Direction.DOWN
+ ? skeleton.columnHeaderHeightAndMarginTop + skeleton.rowTotalHeight - 80
+ : skeleton.columnHeaderHeightAndMarginTop;
+ const drawing = createSheetDrawing('edge', left, top);
+ await insertDrawings(testBed, [drawing]);
+ service.focusDrawing([drawing]);
+ const history = testBed.get(IUndoRedoService).pitchTopUndoElement();
+
+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction })).toBe(false);
+ expect(service.getDrawingByParam(drawing)?.transform).toMatchObject({ left, top });
+ expect(testBed.get(IUndoRedoService).pitchTopUndoElement()).toBe(history);
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+
+ it('keeps the relative positions of selected drawings when one reaches an edge', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const service = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(MoveDrawingsCommand);
+ try {
+ const skeleton = testBed.get(SheetSkeletonService).getSkeleton(testBed.unitId, testBed.subUnitId)!;
+ const left = skeleton.rowHeaderWidthAndMarginLeft + 0.5;
+ const first = createSheetDrawing('first', left, 100);
+ const second = createSheetDrawing('second', left + 200, 200);
+ await insertDrawings(testBed, [first, second]);
+ service.focusDrawing([second, first]);
+
+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.LEFT })).toBe(true);
+ expect(service.getDrawingByParam(first)?.transform).toMatchObject({ left: left - 0.5, top: 100 });
+ expect(service.getDrawingByParam(second)?.transform).toMatchObject({ left: left + 199.5, top: 200 });
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+
+ it('keeps drawing positions unchanged when move is triggered without a focused drawing', async () => {
+ const testBed = createSheetsDrawingUiTestBed();
+ const sheetDrawingService = testBed.get(ISheetDrawingService);
+ testBed.commandService.registerCommand(MoveDrawingsCommand);
+ await insertDrawings(testBed, [createSheetDrawing('drawing-2', 30, 40)]);
+
+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.UP })).toBe(false);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-2',
+ })?.transform).toMatchObject({
+ left: 30,
+ top: 40,
+ });
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
index 48d482a99e..7ed4fa9bcd 100644
--- a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
+++ b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
@@ -43,26 +43,34 @@ export const MoveDrawingsCommand: ICommand = {
}
const unitId = drawings[0].unitId;
+ const positionedDrawings = drawings.flatMap((drawing) => {
+ const skeleton = sheetSkeletonService.getSkeleton(drawing.unitId, drawing.subUnitId);
+ return drawing.transform && skeleton ? [{ drawing: drawing as ISheetDrawing, skeleton }] : [];
+ });
+ if (positionedDrawings.length === 0) return false;
- const newDrawings = drawings.map((drawing) => {
- const { transform, unitId, subUnitId } = drawing as ISheetDrawing;
- const skeleton = sheetSkeletonService.getSkeleton(unitId, subUnitId);
- if (!transform || !skeleton) {
- return null;
- }
+ let moveX = direction === Direction.LEFT ? -1 : direction === Direction.RIGHT ? 1 : 0;
+ let moveY = direction === Direction.UP ? -1 : direction === Direction.DOWN ? 1 : 0;
+ let minX = -Infinity;
+ let minY = -Infinity;
+ let maxX = Infinity;
+ let maxY = Infinity;
+ for (const { drawing, skeleton } of positionedDrawings) {
+ const { left = 0, top = 0, width = 0, height = 0 } = drawing.transform!;
+ const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop, columnTotalWidth, rowTotalHeight } = skeleton;
+ minX = Math.max(minX, rowHeaderWidthAndMarginLeft - left);
+ minY = Math.max(minY, columnHeaderHeightAndMarginTop - top);
+ maxX = Math.min(maxX, rowHeaderWidthAndMarginLeft + columnTotalWidth - left - width);
+ maxY = Math.min(maxY, columnHeaderHeightAndMarginTop + rowTotalHeight - top - height);
+ }
+ moveX = Math.max(minX, Math.min(moveX, maxX));
+ moveY = Math.max(minY, Math.min(moveY, maxY));
+ if (moveX === 0 && moveY === 0) return false;
- const newTransform = { ...transform };
+ const newDrawings = positionedDrawings.map(({ drawing, skeleton }) => {
+ const transform = drawing.transform!;
const { left = 0, top = 0 } = transform;
-
- if (direction === Direction.UP) {
- newTransform.top = top - 1;
- } else if (direction === Direction.DOWN) {
- newTransform.top = top + 1;
- } else if (direction === Direction.LEFT) {
- newTransform.left = left - 1;
- } else if (direction === Direction.RIGHT) {
- newTransform.left = left + 1;
- }
+ const newTransform = { ...transform, left: left + moveX, top: top + moveY };
return {
...drawing,
@@ -70,7 +78,7 @@ export const MoveDrawingsCommand: ICommand = {
sheetTransform: transformToDrawingPosition(newTransform, skeleton),
axisAlignSheetTransform: transformToAxisAlignPosition(newTransform, skeleton),
} as ISheetDrawing;
- }).filter((drawing) => drawing != null) as ISheetDrawing[];
+ });
const result = undoRedoGroupService.runTimed(
unitId,
diff --git a/packages/sheets-drawing/src/commands/commands/__tests__/set-sheet-drawing.command.spec.ts b/packages/sheets-drawing/src/commands/commands/__tests__/set-sheet-drawing.command.spec.ts
new file mode 100644
index 0000000000..424712caad
--- /dev/null
+++ b/packages/sheets-drawing/src/commands/commands/__tests__/set-sheet-drawing.command.spec.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { DrawingTypeEnum, IUndoRedoService } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { createSheetsDrawingTestBed } from '../../../__tests__/create-sheets-drawing-test-bed';
+import { ISheetDrawingService } from '../../../services/sheet-drawing.service';
+import { InsertSheetDrawingCommand } from '../insert-sheet-drawing.command';
+import { SetSheetDrawingCommand } from '../set-sheet-drawing.command';
+
+describe('SetSheetDrawingCommand', () => {
+ it('persists an online OLE link with symmetric drawing mutations', async () => {
+ const testBed = createSheetsDrawingTestBed();
+ const service = testBed.get(ISheetDrawingService);
+ const drawing = { unitId: testBed.workbook.getUnitId(), subUnitId: testBed.workbook.getActiveSheet()!.getSheetId(), drawingId: 'ole-1', drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained' };
+ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, { unitId: testBed.workbook.getUnitId(), drawings: [drawing] });
+ const online = { unitId: 'child', type: 1 };
+ expect(await testBed.commandService.executeCommand(SetSheetDrawingCommand.id, { unitId: testBed.workbook.getUnitId(), drawings: [{ ...drawing, oleOnlineUnit: online, oleFileName: '预算.xlsx' }] })).toBe(true);
+ expect(JSON.parse(JSON.stringify(service.getDrawingByParam(drawing)))).toMatchObject({ oleAttachmentId: 'retained', oleOnlineUnit: online, oleFileName: '预算.xlsx' });
+ const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;
+ for (const mutation of history.undoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
+ expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleOnlineUnit');
+ expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleFileName');
+ for (const mutation of history.redoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);
+ expect(service.getDrawingByParam(drawing)).toMatchObject({ oleOnlineUnit: online, oleFileName: '预算.xlsx' });
+ testBed.univer.dispose();
+ });
+});