Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: duplicate block #743

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api/src/chat/controllers/block.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,9 @@ export class BlockController extends BaseController<
this.logger.log(`Successfully deleted blocks with IDs: ${ids}`);
return deleteResult;
}

@Post('/duplicate/:blockId')
async duplicateBlock(@Param('blockId') blockId: string) {
return this.blockService.duplicateBlock(blockId);
}
}
27 changes: 26 additions & 1 deletion api/src/chat/services/block.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { Injectable } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';

import { AttachmentService } from '@/attachment/services/attachment.service';
import EventWrapper from '@/channel/lib/EventWrapper';
Expand Down Expand Up @@ -55,6 +55,31 @@ export class BlockService extends BaseService<
super(repository);
}

async duplicateBlock(blockId: string) {
const block = await this.repository.findOne(blockId);
if (!block) {
throw new NotFoundException(`Unable to find ${blockId} to duplicate`);
}
const {
createdAt: _createdAt,
updatedAt: _updatedAt,
id: _id,
previousBlocks: _previousBlocks,
attachedBlock: _attachedBlock,
nextBlocks: _nextBlocks,
...blockData
} = block;

return await this.repository.create({
...blockData,
position: {
x: block.position.x,
y: block.position.y + 20,
},
name: `${block.name} (Copy)`,
});
}

/**
* Find a block whose patterns matches the received event
*
Expand Down
3 changes: 2 additions & 1 deletion frontend/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@
"invalid_file_type": "Invalid file type. Please select a file in the supported format.",
"select_category": "Select a flow",
"logout_failed": "Something went wrong during logout",
"duplicate_labels_not_allowed": "Duplicate labels are not allowed"
"duplicate_labels_not_allowed": "Duplicate labels are not allowed",
"duplicate_block_error": "Something went wrong while duplicating block"
},
"menu": {
"terms": "Terms of Use",
Expand Down
3 changes: 2 additions & 1 deletion frontend/public/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@
"invalid_file_type": "Type de fichier invalide. Veuillez choisir un fichier dans un format pris en charge.",
"select_category": "Sélectionner une catégorie",
"logout_failed": "Une erreur s'est produite lors de la déconnexion",
"duplicate_labels_not_allowed": "Les étiquettes en double ne sont pas autorisées"
"duplicate_labels_not_allowed": "Les étiquettes en double ne sont pas autorisées",
"duplicate_block_error": "Une erreur est survenue lors de la duplication du bloc"
},
"menu": {
"terms": "Conditions d'utilisation",
Expand Down
32 changes: 31 additions & 1 deletion frontend/src/components/visual-editor/v2/Diagrams.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/


import { Add, MoveUp } from "@mui/icons-material";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
Expand All @@ -28,6 +29,7 @@ import {
DiagramEngine,
DiagramModel,
DiagramModelGenerics,
NodeModel,
} from "@projectstorm/react-diagrams";
import { useRouter } from "next/router";
import { SyntheticEvent, useCallback, useEffect, useState } from "react";
Expand Down Expand Up @@ -56,6 +58,7 @@ import { ZOOM_LEVEL } from "../constants";
import { useVisualEditor } from "../hooks/useVisualEditor";

import { AdvancedLinkModel } from "./AdvancedLink/AdvancedLinkModel";
import { useDuplicateBlock } from "./hooks/useDuplicateBlock";

const Diagrams = () => {
const { t } = useTranslate();
Expand All @@ -80,6 +83,13 @@ const Diagrams = () => {
const { searchPayload } = useSearch<IBlock>({
$eq: [{ category: selectedCategoryId }],
});
const selectedEntities = engine?.getModel()?.getSelectedEntities();
const selectedLinks = (selectedEntities || []).filter(
(entity) => entity instanceof AdvancedLinkModel,
);
const selectedBlocks = (selectedEntities || []).filter(
(entity) => entity instanceof NodeModel,
);
const { data: categories } = useFind(
{ entity: EntityType.CATEGORY },
{
Expand Down Expand Up @@ -113,6 +123,7 @@ const Diagrams = () => {
setSelectedBlockId(undefined);
},
});
const { mutate: duplicateBlock, isLoading } = useDuplicateBlock();
const { mutate: updateBlock } = useUpdate(EntityType.BLOCK, {
invalidate: false,
});
Expand Down Expand Up @@ -513,6 +524,11 @@ const Diagrams = () => {
);
}
};
const handleDuplicateBlock = () => {
const ids = selectedBlocks[0].getID();

duplicateBlock({ blockId: ids });
};

return (
<div
Expand Down Expand Up @@ -670,6 +686,20 @@ const Diagrams = () => {
>
{t("button.move")}
</Button>
<Button
sx={{}}
size="small"
variant="contained"
startIcon={<DeleteIcon />}
onClick={handleDuplicateBlock}
disabled={
selectedBlocks.length > 1 ||
selectedBlocks.length === 0 ||
selectedLinks.length > 0 || isLoading
}
>
{t("button.duplicate")}
</Button>
<Button
sx={{}}
size="small"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { useMutation, useQueryClient } from "react-query";

import { useApiClient } from "@/hooks/useApiClient";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { TMutationOptions } from "@/services/types";
import { IBlock, IBlockStub } from "@/types/block.types";

interface IDuplicateBlockAttributes {
blockId: string;
}
export const useDuplicateBlock = (
options?: Omit<
TMutationOptions<IBlockStub, Error, IDuplicateBlockAttributes, unknown>,
"mutationFn"
>,
) => {
const { apiClient } = useApiClient();
const queryClient = useQueryClient();
const { toast } = useToast();
const { t } = useTranslate();

return useMutation<IBlock, Error, IDuplicateBlockAttributes>({
...options,
async mutationFn({ blockId }: IDuplicateBlockAttributes) {
return await apiClient.duplicateBlock(blockId);
},
onSuccess: (duplicatedBlock) => {
queryClient.invalidateQueries([
"collection",
"Block",
{ where: { category: `${duplicatedBlock.category}` } },
]);
},
onError: () => {
toast.error(t("message.duplicate_block_error"));
},
});
};
10 changes: 9 additions & 1 deletion frontend/src/services/api.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/


import { AxiosInstance, AxiosResponse } from "axios";

import { AttachmentResourceRef } from "@/types/attachment.types";
Expand Down Expand Up @@ -44,6 +43,7 @@ export const ROUTES = {
NLP_SAMPLE_IMPORT: "/nlpsample/import",
NLP_SAMPLE_PREDICT: "/nlpsample/message",
CONTENT_IMPORT: "/content/import",
DUPLICATE_BLOCK: "/block/duplicate",
// Entities
[EntityType.SUBSCRIBER]: "/subscriber",
[EntityType.LABEL]: "/label",
Expand Down Expand Up @@ -257,6 +257,14 @@ export class ApiClient {
return data;
}

async duplicateBlock(blockId: string) {
const { data } = await this.request.post(
`${ROUTES.DUPLICATE_BLOCK}/${blockId}`,
);

return data;
}

getRequest() {
return this.request;
}
Expand Down