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(group): fix group shape copy paste (#6700)

VicKun6d9ee5287374
diff --git a/packages/core/src/types/interfaces/i-drawing.ts b/packages/core/src/types/interfaces/i-drawing.ts
index af09fa04ec..7d0383e85f 100644
--- a/packages/core/src/types/interfaces/i-drawing.ts
+++ b/packages/core/src/types/interfaces/i-drawing.ts
@@ -113,7 +113,7 @@ export interface ITransformStateDisableOption {
borderEnabled?: boolean;
}
-export interface ITransformState extends IAbsoluteTransform, IRotationSkewFlipTransform, ITransformStateDisableOption {}
+export interface ITransformState extends IAbsoluteTransform, IRotationSkewFlipTransform, ITransformStateDisableOption { }
export interface IDrawingParam extends IDrawingSearch {
drawingType: DrawingType;
@@ -131,4 +131,43 @@ export interface IDrawingParam extends IDrawingSearch {
groupBaseBound?: Nullable<IGroupBaseBound>;
}
+/**
+ * Describes a single group node's direct children in a group hierarchy.
+ */
+export interface IDrawingGroupNestedIds {
+ /** The drawing ID of the group itself. */
+ drawingId: string;
+ /**
+ * The drawing IDs of the direct children of this group (both group and
+ * non-group children). Does not include deeply-nested descendants.
+ */
+ children?: string[];
+}
+
+/**
+ * A flattened representation of a nested group hierarchy, produced by a
+ * post-order DFS traversal so that every child always appears before its
+ * parent in the respective arrays.
+ */
+export interface IDrawingGroupNestedParam {
+ /**
+ * A map from each group's drawingId to its {@link IDrawingGroupNestedIds}
+ * descriptor. Covers the root group and every nested sub-group. Look up
+ * any group's direct children in O(1) via `nestedIdRecord[groupId].children`.
+ */
+ nestedIdRecord: Record<string, IDrawingGroupNestedIds>;
+ /**
+ * All non-group (leaf) drawing params that belong anywhere in the group
+ * hierarchy. Post-order: a leaf always appears before the group that
+ * directly contains it.
+ */
+ flatChildren?: IDrawingParam[];
+ /**
+ * All group drawing params in the hierarchy (including the root group).
+ * Post-order: nested child groups appear before their parent group, so
+ * callers can safely iterate in order without dependency issues.
+ * The root group is always the last element.
+ */
+ groups: IDrawingParam[];
+}
// #endregion
diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.ts
index b113170edf..0355767eab 100644
--- a/packages/drawing/src/services/drawing-manager-impl.service.ts
+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { IDrawingParam, IDrawingSearch, Nullable } from '@univerjs/core';
+import type { IDrawingGroupNestedIds, IDrawingGroupNestedParam, IDrawingParam, IDrawingSearch, Nullable } from '@univerjs/core';
import type { JSONOp, JSONOpList } from 'ot-json1';
import type { Observable } from 'rxjs';
import type { IDrawingGroupUpdateParam, IDrawingMap, IDrawingMapItemData, IDrawingOrderMapParam, IDrawingOrderUpdateParam, IDrawingSubunitMap, IDrawingVisibleParam, IUnitDrawingService } from './drawing-manager.service';
-import { sortRules, sortRulesByDesc } from '@univerjs/core';
+import { DrawingTypeEnum, sortRules, sortRulesByDesc } from '@univerjs/core';
import * as json1 from 'ot-json1';
import { Subject } from 'rxjs';
@@ -352,6 +352,57 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
return children;
}
+ getDrawingsByGroupNested(groupSearch: IDrawingSearch): IDrawingGroupNestedParam | null {
+ const { unitId, subUnitId } = groupSearch;
+ const rootParam = this.getDrawingByParam(groupSearch);
+ if (!rootParam) {
+ return null;
+ }
+
+ // get all drawings in the same subUnit one time to avoid multiple times of data access when there are many drawings
+ const allDrawings = this._getDrawingData(unitId, subUnitId);
+ const groupDerivedDrawingsIdMap: Map<string, string[]> = new Map();
+ Object.values(allDrawings).forEach((drawing) => {
+ if (drawing.groupId != null) {
+ if (!groupDerivedDrawingsIdMap.has(drawing.groupId)) {
+ groupDerivedDrawingsIdMap.set(drawing.groupId, []);
+ }
+ groupDerivedDrawingsIdMap.get(drawing.groupId)!.push(drawing.drawingId);
+ }
+ });
+
+ const flatChildren: IDrawingParam[] = [];
+ const groups: IDrawingParam[] = [];
+ const nestedIdRecord: Record<string, IDrawingGroupNestedIds> = {};
+
+ // It stores all non-grouped child elements, while ensuring that each child element is always positioned before its parent element in the repository.
+ // `flatChildren` stores all non-grouped elements, satisfying the left-order traversal order.
+ const dfs = (param: IDrawingParam): void => {
+ const { drawingId } = param;
+ const childrenIds = groupDerivedDrawingsIdMap.get(drawingId) ?? [];
+ nestedIdRecord[drawingId] = { drawingId, children: childrenIds };
+ childrenIds.forEach((childId) => {
+ const childParam = allDrawings[childId];
+ if (!childParam) return;
+ if (childParam.drawingType === DrawingTypeEnum.DRAWING_GROUP) {
+ dfs(childParam);
+ groups.push(childParam);
+ } else {
+ flatChildren.push(childParam);
+ }
+ });
+ };
+
+ dfs(rootParam);
+ groups.push(rootParam); // root group is always last
+
+ return {
+ nestedIdRecord,
+ flatChildren,
+ groups,
+ };
+ }
+
private _getGroupDrawingOp(groupParam: IDrawingGroupUpdateParam): JSONOp {
const { parent, children } = groupParam;
const { unitId: groupUnitId, subUnitId: groupSubUnitId, drawingId: groupDrawingId } = parent;
@@ -793,4 +844,4 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
}
}
-export class DrawingManagerService extends UnitDrawingService<IDrawingParam> {}
+export class DrawingManagerService extends UnitDrawingService<IDrawingParam> { }
diff --git a/packages/drawing/src/services/drawing-manager.service.ts b/packages/drawing/src/services/drawing-manager.service.ts
index baab979c3b..9d379000a8 100644
--- a/packages/drawing/src/services/drawing-manager.service.ts
+++ b/packages/drawing/src/services/drawing-manager.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ArrangeTypeEnum, IDisposable, IDrawingParam, IDrawingSearch, Nullable } from '@univerjs/core';
+import type { ArrangeTypeEnum, IDisposable, IDrawingGroupNestedParam, IDrawingParam, IDrawingSearch, Nullable } from '@univerjs/core';
import type { Observable } from 'rxjs';
import { createIdentifier } from '@univerjs/core';
@@ -108,6 +108,7 @@ export interface IUnitGroupDrawingService {
groupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
ungroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
getDrawingsByGroup(groupParam: IDrawingSearch): IDrawingParam[];
+ getDrawingsByGroupNested(groupParam: IDrawingSearch): IDrawingGroupNestedParam | null;
featurePluginGroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
featurePluginUngroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
diff --git a/packages/sheets-drawing-ui/src/commands/commands/utils.ts b/packages/sheets-drawing-ui/src/commands/commands/utils.ts
index 6d1c7db842..c1e4a23fce 100644
--- a/packages/sheets-drawing-ui/src/commands/commands/utils.ts
+++ b/packages/sheets-drawing-ui/src/commands/commands/utils.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IDrawingParam } from '@univerjs/core';
+import type { IDrawingGroupNestedIds, IDrawingGroupNestedParam, IDrawingParam } from '@univerjs/core';
import type { IDrawingGroupUpdateParam } from '@univerjs/drawing';
-import { DrawingTypeEnum } from '@univerjs/core';
+import { DrawingTypeEnum, generateRandomId } from '@univerjs/core';
import { getGroupState, transformObjectOutOfGroup } from '@univerjs/engine-render';
export function ungroupToGroup(ungroupParams: IDrawingGroupUpdateParam[]) {
@@ -102,3 +102,64 @@ export function groupToUngroup(groupParams: IDrawingGroupUpdateParam[]) {
return newGroupParams;
}
+
+export interface ICloneGroupResult {
+ cloned: IDrawingGroupNestedParam;
+ /** Map from original drawingId → new drawingId, for updating connector/line relations */
+ idMap: Map<string, string>;
+}
+
+// only paste can use this function
+export function cloneGroupParams(groupParams: IDrawingGroupNestedParam): ICloneGroupResult {
+ const idMap = new Map<string, string>();
+
+ groupParams.flatChildren?.forEach((p) => idMap.set(p.drawingId, generateRandomId(10)));
+ groupParams.groups.forEach((p) => idMap.set(p.drawingId, generateRandomId(10)));
+
+ const clonedNestedIdRecord: Record<string, IDrawingGroupNestedIds> = {};
+ for (const [oldGroupId, entry] of Object.entries(groupParams.nestedIdRecord)) {
+ const newGroupId = idMap.get(oldGroupId) ?? oldGroupId;
+ clonedNestedIdRecord[newGroupId] = {
+ drawingId: newGroupId,
+ children: entry.children?.map((id) => idMap.get(id) ?? id),
+ };
+ }
+
+ const flatChildren: IDrawingParam[] = [];
+ const groups: IDrawingParam[] = [];
+
+ for (const group of groupParams.groups) {
+ const groupDrawingId = idMap.get(group.drawingId) ?? group.drawingId;
+ const parentGroupId = group.groupId ? idMap.get(group.groupId) ?? group.groupId : undefined;
+ groups.push(cloneDrawingParam(group, groupDrawingId, parentGroupId));
+ }
+
+ for (const child of groupParams.flatChildren || []) {
+ const childDrawingId = idMap.get(child.drawingId) ?? child.drawingId;
+ const parentGroupId = child.groupId ? idMap.get(child.groupId) ?? child.groupId : undefined;
+ flatChildren.push(cloneDrawingParam(child, childDrawingId, parentGroupId));
+ }
+
+ return {
+ cloned: {
+ nestedIdRecord: clonedNestedIdRecord,
+ flatChildren,
+ groups,
+ },
+ idMap,
+ };
+}
+
+function cloneDrawingParam(param: IDrawingParam, newDrawingId: string, parentGroupId: string | undefined): IDrawingParam {
+ const newParam = { ...param };
+ if (newDrawingId) {
+ newParam.drawingId = newDrawingId;
+ }
+ if (parentGroupId) {
+ newParam.groupId = parentGroupId;
+ } else {
+ delete newParam.groupId;
+ }
+
+ return JSON.parse(JSON.stringify(newParam)) as IDrawingParam;
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts
new file mode 100644
index 0000000000..a85bba9eb4
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts
@@ -0,0 +1,224 @@
+/**
+ * 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 { IDrawingGroupNestedParam, IMutationInfo, Nullable } from '@univerjs/core';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { ISheetDrawing } from '@univerjs/sheets-drawing';
+import type { IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import { Disposable, DrawingTypeEnum } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { discreteRangeToRange } from '@univerjs/sheets';
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets-drawing';
+import {
+ ISheetClipboardService,
+ ISheetSelectionRenderService,
+ PREDEFINED_HOOK_NAME_PASTE,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
+import { transformToAxisAlignPosition, transformToDrawingPosition } from '../basics/transform-position';
+import { cloneGroupParams } from '../commands/commands/utils';
+
+export interface IGroupFeaturePasteHookParams {
+ /** Unit ID of the copy source */
+ fromUnitId: string;
+ /** Sub-unit ID of the copy source */
+ fromSubUnitId: string;
+ /** Unit ID of the paste destination */
+ toUnitId: string;
+ /** Sub-unit ID of the paste destination */
+ toSubUnitId: string;
+ /** Maps original drawingId → new (cloned) drawingId */
+ idMap: Map<string, string>;
+ /** The fully cloned group param with remapped IDs */
+ cloned: IDrawingGroupNestedParam;
+}
+
+export type GroupFeaturePasteHook = (params: IGroupFeaturePasteHookParams) => { redos: IMutationInfo[]; undos: IMutationInfo[] };
+
+const specialPastes: IPasteHookValueType[] = [
+ PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH,
+ PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE,
+ PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,
+ PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA,
+];
+
+export class SheetsDrawingGroupCopyPasteController extends Disposable {
+ private readonly _featurePasteHooks: GroupFeaturePasteHook[] = [];
+
+ private _copyInfo: Nullable<{
+ unitId: string;
+ subUnitId: string;
+ groupNestedParam: IDrawingGroupNestedParam;
+ }>;
+
+ constructor(
+ @ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService
+ ) {
+ super();
+ this._initCopyPaste();
+ }
+
+ private get _focusedDrawings() {
+ return this._sheetDrawingService.getFocusDrawings() as ISheetDrawing[];
+ }
+
+ private _initCopyPaste() {
+ this._sheetClipboardService.addClipboardHook({
+ id: 'SHEET_DRAWING_GROUP',
+
+ onBeforeCopy: (_unitId, _subUnitId) => {
+ this._copyInfo = null;
+
+ const focusDrawings = this._focusedDrawings;
+ if (focusDrawings.length === 0) return;
+
+ // Only handle the first focused group drawing.
+ const groupDrawing = focusDrawings.find((d) => d.drawingType === DrawingTypeEnum.DRAWING_GROUP);
+ if (!groupDrawing) return;
+
+ const groupNestedParam = this._drawingManagerService.getDrawingsByGroupNested({
+ unitId: groupDrawing.unitId,
+ subUnitId: groupDrawing.subUnitId,
+ drawingId: groupDrawing.drawingId,
+ });
+ if (!groupNestedParam) return;
+
+ this._copyInfo = {
+ unitId: groupDrawing.unitId,
+ subUnitId: groupDrawing.subUnitId,
+ groupNestedParam,
+ };
+ },
+
+ onPasteCells: (_pasteFrom, pasteTo, _data, payload) => {
+ if (!this._copyInfo) return { redos: [], undos: [] };
+
+ const { pasteType } = payload;
+ if (specialPastes.includes(pasteType)) return { redos: [], undos: [] };
+
+ return this._generateGroupPasteMutations(pasteTo);
+ },
+
+ onPasteUnrecognized: (pasteTo) => {
+ if (!this._copyInfo) return { redos: [], undos: [] };
+ return this._generateGroupPasteMutations(pasteTo);
+ },
+ });
+ }
+
+ public registerFeaturePasteHook(hook: GroupFeaturePasteHook): void {
+ this._featurePasteHooks.push(hook);
+ }
+
+ private _getGroupFeaturePasteMutations(params: IGroupFeaturePasteHookParams): { redos: IMutationInfo[]; undos: IMutationInfo[] } {
+ const redos: IMutationInfo[] = [];
+ const undos: IMutationInfo[] = [];
+ for (const hook of this._featurePasteHooks) {
+ const result = hook(params);
+ redos.push(...result.redos);
+ undos.push(...result.undos);
+ }
+ return { redos, undos };
+ }
+
+ private _generateGroupPasteMutations(pasteTo: ISheetDiscreteRangeLocation): { redos: IMutationInfo[]; undos: IMutationInfo[] } {
+ const { unitId, subUnitId, range } = pasteTo;
+ const render = this._renderManagerService.getRenderById(unitId);
+ const skeletonManagerService = render?.with(SheetSkeletonManagerService);
+ const selectionRenderService = render?.with(ISheetSelectionRenderService);
+
+ if (!skeletonManagerService || !selectionRenderService || !this._copyInfo) {
+ return { redos: [], undos: [] };
+ }
+
+ const { groupNestedParam } = this._copyInfo;
+ // Root group is the last element of the post-order groups array.
+ const origRootGroup = groupNestedParam.groups[groupNestedParam.groups.length - 1] as ISheetDrawing;
+
+ // Clone all drawing IDs.
+ const { cloned, idMap } = cloneGroupParams(groupNestedParam);
+ const newRootGroupId = cloned.groups[cloned.groups.length - 1].drawingId;
+
+ // Resolve the paste destination rectangle.
+ const pasteRange = discreteRangeToRange(range);
+ const pasteRect = skeletonManagerService.attachRangeWithCoord({
+ startRow: pasteRange.startRow,
+ endRow: pasteRange.endRow,
+ startColumn: pasteRange.startColumn,
+ endColumn: pasteRange.endColumn,
+ });
+ if (!pasteRect) return { redos: [], undos: [] };
+
+ // Only the root group's absolute position changes; all other drawings keep their
+ // group-relative transforms as-is.
+ const newTransform = { ...(origRootGroup.transform), left: pasteRect.startX, top: pasteRect.startY };
+
+ const allDrawings: ISheetDrawing[] = [
+ ...(cloned.flatChildren ?? []).map((d) => ({ ...d, unitId, subUnitId } as ISheetDrawing)),
+ ...cloned.groups.map((d) => {
+ if (d.drawingId !== newRootGroupId) {
+ return { ...d, unitId, subUnitId } as ISheetDrawing;
+ }
+ return {
+ ...d,
+ unitId,
+ subUnitId,
+ transform: newTransform,
+ sheetTransform: transformToDrawingPosition(newTransform, selectionRenderService) ?? origRootGroup.sheetTransform,
+ axisAlignSheetTransform: transformToAxisAlignPosition(newTransform, selectionRenderService) ?? origRootGroup.sheetTransform,
+ } as ISheetDrawing;
+ }),
+ ];
+
+ // A single batch INSERT is sufficient: the shape rendering layer calls insertGroupObject()
+ // for each shape's groupId, which automatically reconstructs the full group hierarchy in
+ // the scene from the data that was just written by applyJson1.
+ const { undo: removeOp, redo: insertOp, objects } = this._sheetDrawingService.getBatchAddOp(allDrawings) as IDrawingJsonUndo1;
+
+ const redos: IMutationInfo[] = [{
+ id: SetDrawingApplyMutation.id,
+ params: { op: insertOp, unitId, subUnitId, objects, type: DrawingApplyType.INSERT },
+ }];
+
+ const undos: IMutationInfo[] = [{
+ id: SetDrawingApplyMutation.id,
+ params: { op: removeOp, unitId, subUnitId, objects, type: DrawingApplyType.REMOVE },
+ }];
+
+ const featureMutations = this._getGroupFeaturePasteMutations({
+ fromUnitId: this._copyInfo.unitId,
+ fromSubUnitId: this._copyInfo.subUnitId,
+ toUnitId: unitId,
+ toSubUnitId: subUnitId,
+ idMap,
+ cloned,
+ });
+ redos.push(...featureMutations.redos);
+ undos.push(...featureMutations.undos);
+
+ return { redos, undos };
+ }
+
+ override dispose(): void {
+ this._copyInfo = null;
+ this._featurePasteHooks.length = 0;
+ super.dispose();
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index 84c50277e6..bb81cdfca7 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -32,6 +32,7 @@ export { ClearSheetDrawingTransformerOperation } from './commands/operations/cle
export { EditSheetDrawingOperation } from './commands/operations/edit-sheet-drawing.operation';
export { SidebarSheetDrawingOperation } from './commands/operations/open-drawing-panel.operation';
export type { IUniverSheetsDrawingUIConfig } from './config/config';
+export { SheetsDrawingGroupCopyPasteController } from './controllers/sheet-drawing-group-copy-paste.controller';
export { SheetDrawingUpdateController } from './controllers/sheet-drawing-update.controller';
export { SHEETS_IMAGE_MENU_ID } from './menu/image.menu';
export { UniverSheetsDrawingUIPlugin } from './plugin';
diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.ts
index ad806e3548..8da18523f9 100644
--- a/packages/sheets-drawing-ui/src/plugin.ts
+++ b/packages/sheets-drawing-ui/src/plugin.ts
@@ -41,6 +41,7 @@ import { SheetCellImageAutofillController } from './controllers/sheet-cell-image
import { SheetCellImageCopyPasteController } from './controllers/sheet-cell-image-copy-paste.controller';
import { SheetCellImageController } from './controllers/sheet-cell-image.controller';
import { SheetsDrawingCopyPasteController } from './controllers/sheet-drawing-copy-paste.controller';
+import { SheetsDrawingGroupCopyPasteController } from './controllers/sheet-drawing-group-copy-paste.controller';
import { SheetDrawingPermissionController } from './controllers/sheet-drawing-permission.controller';
import { SheetDrawingPrintingController } from './controllers/sheet-drawing-printing.controller';
import { SheetDrawingTransformAffectedController } from './controllers/sheet-drawing-transform-affected.controller';
@@ -85,6 +86,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
[SheetDrawingPrintingController],
[SheetDrawingPermissionController],
[SheetsDrawingCopyPasteController],
+ [SheetsDrawingGroupCopyPasteController],
[SheetCellImageController],
[SheetCellImageAutofillController],
[SheetCellImageCopyPasteController],
@@ -101,6 +103,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
touchDependencies(this._injector, [
[SheetsDrawingCopyPasteController],
[SheetCellImageCopyPasteController],
+ [SheetsDrawingGroupCopyPasteController],
]);
}