refactor(frontend): update BlockEdit and BlockMove dialogs

This commit is contained in:
yassinedorbozgithub 2025-02-09 01:34:06 +01:00
parent 12fd65b774
commit 95a4182b8f
9 changed files with 414 additions and 321 deletions

View File

@ -1,211 +0,0 @@
/*
* Copyright © 2024 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 ChatBubbleOutlineOutlinedIcon from "@mui/icons-material/ChatBubbleOutlineOutlined";
import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import {
Dialog,
DialogActions,
DialogContent,
FormControlLabel,
Grid,
Switch,
Tab,
Tabs,
} from "@mui/material";
import { FC, useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import DialogButtons from "@/app-components/buttons/DialogButtons";
import { DialogTitle } from "@/app-components/dialogs/DialogTitle";
import { ContentContainer } from "@/app-components/dialogs/layouts/ContentContainer";
import { ContentItem } from "@/app-components/dialogs/layouts/ContentItem";
import { Input } from "@/app-components/inputs/Input";
import TriggerIcon from "@/app-components/svg/TriggerIcon";
import { TabPanel } from "@/app-components/tabs/TabPanel";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { OutgoingMessageFormat } from "@/types/message.types";
import { IBlock, IBlockAttributes } from "../../types/block.types";
import BlockFormProvider from "./form/BlockFormProvider";
import { MessageForm } from "./form/MessageForm";
import { OptionsForm } from "./form/OptionsForm";
import { TriggersForm } from "./form/TriggersForm";
export type BlockDialogProps = DialogControlProps<IBlock>;
type TSelectedTab = "triggers" | "options" | "messages";
const BlockDialog: FC<BlockDialogProps> = ({
open,
data: block,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const [selectedTab, setSelectedTab] = useState<TSelectedTab>("triggers");
const handleChange = (
_event: React.SyntheticEvent,
newValue: TSelectedTab,
) => {
setSelectedTab(newValue);
};
const { toast } = useToast();
const { mutateAsync: updateBlock } = useUpdate(EntityType.BLOCK, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const DEFAULT_VALUES = {
name: block?.name || "",
patterns: block?.patterns || [],
trigger_labels: block?.trigger_labels || [],
trigger_channels: block?.trigger_channels || [],
options: block?.options || {
typing: 0,
content: {
display: OutgoingMessageFormat.list,
top_element_style: "compact",
limit: 2,
},
assignTo: block?.options?.assignTo,
fallback: block?.options?.fallback || {
active: true,
message: [],
max_attempts: 1,
},
},
assign_labels: block?.assign_labels || [],
message: block?.message || [""],
capture_vars: block?.capture_vars || [],
} as IBlockAttributes;
const methods = useForm<IBlockAttributes>({
defaultValues: DEFAULT_VALUES,
});
const {
reset,
register,
formState: { errors },
handleSubmit,
control,
} = methods;
const validationRules = {
name: {
required: t("message.name_is_required"),
},
};
const onSubmitForm = async (params: IBlockAttributes) => {
if (block) {
updateBlock({ id: block.id, params });
}
};
useEffect(() => {
if (open) {
reset();
setSelectedTab("triggers");
}
}, [open, reset]);
useEffect(() => {
if (block && open) {
reset(DEFAULT_VALUES);
} else {
reset();
}
}, [block, reset]);
return (
<Dialog open={open} fullWidth maxWidth="md" onClose={closeDialog} {...rest}>
<BlockFormProvider methods={methods} block={block}>
<DialogTitle onClose={closeDialog}>{t("title.edit_block")}</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem display="flex" gap={5}>
<Input
label={t("placeholder.name")}
{...register("name", validationRules.name)}
error={!!errors.name}
autoFocus
helperText={errors.name ? errors.name.message : null}
/>
<Controller
name="starts_conversation"
control={control}
defaultValue={block?.starts_conversation}
render={({ field }) => (
<FormControlLabel
label={t(`label.starts_conversation`)}
{...field}
control={<Switch checked={field.value} />}
/>
)}
/>
</ContentItem>
<ContentItem>
<Tabs
orientation="horizontal"
value={selectedTab}
onChange={handleChange}
>
<Tab
value="triggers"
label={t("label.triggers")}
icon={<TriggerIcon />}
iconPosition="start"
/>
<Tab
value="options"
label={t("label.options")}
icon={<SettingsApplicationsIcon />}
iconPosition="start"
/>
<Tab
value="messages"
label={t("label.message")}
icon={<ChatBubbleOutlineOutlinedIcon />}
iconPosition="start"
/>
</Tabs>
<Grid sx={{ padding: 2 }}>
<TabPanel value={selectedTab} index="triggers">
<TriggersForm />
</TabPanel>
<TabPanel value={selectedTab} index="options">
<OptionsForm />
</TabPanel>
<TabPanel value={selectedTab} index="messages">
<MessageForm />
</TabPanel>
</Grid>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons
handleSubmit={handleSubmit(onSubmitForm)}
closeDialog={closeDialog}
/>
</DialogActions>
</BlockFormProvider>
</Dialog>
);
};
BlockDialog.displayName = "BlockDialog";
export default BlockDialog;

View File

@ -0,0 +1,178 @@
/*
* 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 ChatBubbleOutlineOutlinedIcon from "@mui/icons-material/ChatBubbleOutlineOutlined";
import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import { FormControlLabel, Grid, Switch, Tab, Tabs } from "@mui/material";
import { FC, Fragment, useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import TriggerIcon from "@/app-components/svg/TriggerIcon";
import { TabPanel } from "@/app-components/tabs/TabPanel";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { IBlock, IBlockAttributes } from "@/types/block.types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { OutgoingMessageFormat } from "@/types/message.types";
import BlockFormProvider from "./form/BlockFormProvider";
import { MessageForm } from "./form/MessageForm";
import { OptionsForm } from "./form/OptionsForm";
import { TriggersForm } from "./form/TriggersForm";
type TSelectedTab = "triggers" | "options" | "messages";
export const BlockEditForm: FC<ComponentFormProps<IBlock>> = ({
data: block,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const [selectedTab, setSelectedTab] = useState<TSelectedTab>("triggers");
const handleChange = (
_event: React.SyntheticEvent,
newValue: TSelectedTab,
) => {
setSelectedTab(newValue);
};
const { toast } = useToast();
const { mutateAsync: updateBlock } = useUpdate(EntityType.BLOCK, {
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
});
const DEFAULT_VALUES = {
name: block?.name || "",
patterns: block?.patterns || [],
trigger_labels: block?.trigger_labels || [],
trigger_channels: block?.trigger_channels || [],
options: block?.options || {
typing: 0,
content: {
display: OutgoingMessageFormat.list,
top_element_style: "compact",
limit: 2,
},
assignTo: block?.options?.assignTo,
fallback: block?.options?.fallback || {
active: true,
message: [],
max_attempts: 1,
},
},
assign_labels: block?.assign_labels || [],
message: block?.message || [""],
capture_vars: block?.capture_vars || [],
} as IBlockAttributes;
const methods = useForm<IBlockAttributes>({
defaultValues: DEFAULT_VALUES,
});
const {
reset,
register,
formState: { errors },
handleSubmit,
control,
} = methods;
const validationRules = {
name: {
required: t("message.name_is_required"),
},
};
const onSubmitForm = async (params: IBlockAttributes) => {
if (block) {
updateBlock({ id: block.id, params });
}
};
useEffect(() => {
if (block) {
reset(DEFAULT_VALUES);
} else {
reset();
}
}, [block, reset]);
return (
<Wrapper onSubmit={handleSubmit(onSubmitForm)} {...WrapperProps}>
<BlockFormProvider methods={methods} block={block || undefined}>
<ContentContainer>
<ContentItem display="flex" gap={5}>
<Input
label={t("placeholder.name")}
{...register("name", validationRules.name)}
error={!!errors.name}
autoFocus
helperText={errors.name ? errors.name.message : null}
/>
<Controller
name="starts_conversation"
control={control}
defaultValue={block?.starts_conversation}
render={({ field }) => (
<FormControlLabel
label={t(`label.starts_conversation`)}
{...field}
control={<Switch checked={field.value} />}
/>
)}
/>
</ContentItem>
<ContentItem>
<Tabs
orientation="horizontal"
value={selectedTab}
onChange={handleChange}
>
<Tab
value="triggers"
label={t("label.triggers")}
icon={<TriggerIcon />}
iconPosition="start"
/>
<Tab
value="options"
label={t("label.options")}
icon={<SettingsApplicationsIcon />}
iconPosition="start"
/>
<Tab
value="messages"
label={t("label.message")}
icon={<ChatBubbleOutlineOutlinedIcon />}
iconPosition="start"
/>
</Tabs>
<Grid sx={{ padding: 2 }}>
<TabPanel value={selectedTab} index="triggers">
<TriggersForm />
</TabPanel>
<TabPanel value={selectedTab} index="options">
<OptionsForm />
</TabPanel>
<TabPanel value={selectedTab} index="messages">
<MessageForm />
</TabPanel>
</Grid>
</ContentItem>
</ContentContainer>
</BlockFormProvider>
</Wrapper>
);
};

View File

@ -0,0 +1,25 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { IBlock } from "@/types/block.types";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { BlockEditForm } from "./BlockEditForm";
export const BlockEditFormDialog = <
T extends IBlock | undefined = IBlock | undefined,
>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={BlockEditForm}
editText="title.edit_block"
{...props}
/>
);

View File

@ -0,0 +1,65 @@
/*
* 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 { MenuItem, Select } from "@mui/material";
import { FC, Fragment, useState } from "react";
import { ContentContainer } from "@/app-components/dialogs/";
import { ICategory } from "@/types/category.types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
export type BlockMoveFormData = {
row?: never;
ids: string[];
onMove: (ids: string[], targetCategoryId: string) => void;
category: string;
categories: ICategory[];
};
export const BlockMoveForm: FC<ComponentFormProps<BlockMoveFormData>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const [selectedCategoryId, setSelectedCategoryId] = useState<string>(
data?.category || "",
);
const handleMove = () => {
if (selectedCategoryId) {
data?.onMove(data.ids, selectedCategoryId);
rest.onSuccess?.();
}
};
return (
<Wrapper
onSubmit={handleMove}
{...WrapperProps}
confirmButtonProps={{
...WrapperProps?.confirmButtonProps,
disabled: selectedCategoryId === data?.category,
}}
>
<ContentContainer>
<Select
value={selectedCategoryId}
onChange={(e) => setSelectedCategoryId(e.target.value as string)}
fullWidth
displayEmpty
>
{data?.categories.map((category) => (
<MenuItem key={category.id} value={category.id}>
{category.label}
</MenuItem>
))}
</Select>
</ContentContainer>
</Wrapper>
);
};

View File

@ -0,0 +1,28 @@
/*
* 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 { MoveUp } from "@mui/icons-material";
import { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { BlockMoveForm, BlockMoveFormData } from "./BlockMoveForm";
export const BlockMoveFormDialog = <
T extends BlockMoveFormData = BlockMoveFormData,
>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={BlockMoveForm}
rowKey="row"
addText="message.select_category"
confirmButtonProps={{ value: "button.move", startIcon: <MoveUp /> }}
{...props}
/>
);

View File

@ -30,18 +30,12 @@ import {
DiagramModelGenerics, DiagramModelGenerics,
} from "@projectstorm/react-diagrams"; } from "@projectstorm/react-diagrams";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { import { SyntheticEvent, useCallback, useEffect, useState } from "react";
SyntheticEvent,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { useQueryClient } from "react-query"; import { useQueryClient } from "react-query";
import { DeleteDialog } from "@/app-components/dialogs"; import { ConfirmDialogBody } from "@/app-components/dialogs";
import { MoveDialog } from "@/app-components/dialogs/MoveDialog";
import { CategoryFormDialog } from "@/components/categories/CategoryFormDialog"; import { CategoryFormDialog } from "@/components/categories/CategoryFormDialog";
import { BlockMoveFormDialog } from "@/components/visual-editor/BlockMoveFormDialog";
import { isSameEntity } from "@/hooks/crud/helpers"; import { isSameEntity } from "@/hooks/crud/helpers";
import { useDeleteFromCache } from "@/hooks/crud/useDelete"; import { useDeleteFromCache } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany"; import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
@ -50,7 +44,6 @@ import { useGetFromCache } from "@/hooks/crud/useGet";
import { useUpdate, useUpdateCache } from "@/hooks/crud/useUpdate"; import { useUpdate, useUpdateCache } from "@/hooks/crud/useUpdate";
import { useUpdateMany } from "@/hooks/crud/useUpdateMany"; import { useUpdateMany } from "@/hooks/crud/useUpdateMany";
import useDebouncedUpdate from "@/hooks/useDebouncedUpdate"; import useDebouncedUpdate from "@/hooks/useDebouncedUpdate";
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs"; import { useDialogs } from "@/hooks/useDialogs";
import { useSearch } from "@/hooks/useSearch"; import { useSearch } from "@/hooks/useSearch";
import { useTranslate } from "@/hooks/useTranslate"; import { useTranslate } from "@/hooks/useTranslate";
@ -58,7 +51,7 @@ import { EntityType, Format, QueryType, RouterType } from "@/services/types";
import { IBlock } from "@/types/block.types"; import { IBlock } from "@/types/block.types";
import { BlockPorts } from "@/types/visual-editor.types"; import { BlockPorts } from "@/types/visual-editor.types";
import BlockDialog from "../BlockDialog"; import { BlockEditFormDialog } from "../BlockEditFormDialog";
import { ZOOM_LEVEL } from "../constants"; import { ZOOM_LEVEL } from "../constants";
import { useVisualEditor } from "../hooks/useVisualEditor"; import { useVisualEditor } from "../hooks/useVisualEditor";
@ -75,9 +68,7 @@ const Diagrams = () => {
const [canvas, setCanvas] = useState<JSX.Element | undefined>(); const [canvas, setCanvas] = useState<JSX.Element | undefined>();
const [selectedBlockId, setSelectedBlockId] = useState<string | undefined>(); const [selectedBlockId, setSelectedBlockId] = useState<string | undefined>();
const dialogs = useDialogs(); const dialogs = useDialogs();
const deleteDialogCtl = useDialog<string[]>(false); const { mutate: updateBlocks } = useUpdateMany(EntityType.BLOCK);
const moveDialogCtl = useDialog<string[] | string>(false);
const { mutateAsync: updateBlocks } = useUpdateMany(EntityType.BLOCK);
const { const {
buildDiagram, buildDiagram,
setViewerZoom, setViewerZoom,
@ -86,7 +77,6 @@ const Diagrams = () => {
selectedCategoryId, selectedCategoryId,
createNode, createNode,
} = useVisualEditor(); } = useVisualEditor();
const editDialogCtl = useDialog<IBlock>(false);
const { searchPayload } = useSearch<IBlock>({ const { searchPayload } = useSearch<IBlock>({
$eq: [{ category: selectedCategoryId }], $eq: [{ category: selectedCategoryId }],
}); });
@ -97,7 +87,9 @@ const Diagrams = () => {
initialSortState: [{ field: "createdAt", sort: "asc" }], initialSortState: [{ field: "createdAt", sort: "asc" }],
}, },
{ {
onSuccess([{ id, zoom, offset }]) { onSuccess(categories) {
const { id, zoom, offset } = categories[0] || {};
if (flowId) { if (flowId) {
setSelectedCategoryId?.(flowId); setSelectedCategoryId?.(flowId);
} else if (id) { } else if (id) {
@ -113,12 +105,11 @@ const Diagrams = () => {
const currentCategory = categories.find( const currentCategory = categories.find(
({ id }) => id === selectedCategoryId, ({ id }) => id === selectedCategoryId,
); );
const { mutateAsync: updateCategory } = useUpdate(EntityType.CATEGORY, { const { mutate: updateCategory } = useUpdate(EntityType.CATEGORY, {
invalidate: false, invalidate: false,
}); });
const { mutateAsync: deleteBlocks } = useDeleteMany(EntityType.BLOCK, { const { mutate: deleteBlocks } = useDeleteMany(EntityType.BLOCK, {
onSuccess: () => { onSuccess: () => {
deleteDialogCtl.closeDialog();
setSelectedBlockId(undefined); setSelectedBlockId(undefined);
}, },
}); });
@ -159,9 +150,9 @@ const Diagrams = () => {
const getBlockFromCache = useGetFromCache(EntityType.BLOCK); const getBlockFromCache = useGetFromCache(EntityType.BLOCK);
const updateCachedBlock = useUpdateCache(EntityType.BLOCK); const updateCachedBlock = useUpdateCache(EntityType.BLOCK);
const deleteCachedBlock = useDeleteFromCache(EntityType.BLOCK); const deleteCachedBlock = useDeleteFromCache(EntityType.BLOCK);
const handleChange = (_event: SyntheticEvent, newValue: number) => { const onCategoryChange = (targetCategory: number) => {
if (categories) { if (categories) {
const { id } = categories[newValue]; const { id } = categories[targetCategory];
if (id) { if (id) {
setSelectedCategoryId?.(id); setSelectedCategoryId?.(id);
@ -171,6 +162,9 @@ const Diagrams = () => {
} }
} }
}; };
const handleChange = (_event: SyntheticEvent, newValue: number) => {
onCategoryChange(newValue);
};
const { data: blocks } = useFind( const { data: blocks } = useFind(
{ entity: EntityType.BLOCK, format: Format.FULL }, { entity: EntityType.BLOCK, format: Format.FULL },
{ hasCount: false, params: searchPayload }, { hasCount: false, params: searchPayload },
@ -178,7 +172,6 @@ const Diagrams = () => {
enabled: !!selectedCategoryId, enabled: !!selectedCategoryId,
}, },
); );
const deleteCallbackRef = useRef<() => void | null>(() => {});
useEffect(() => { useEffect(() => {
// Case when categories are already cached // Case when categories are already cached
@ -202,15 +195,14 @@ const Diagrams = () => {
data: blocks, data: blocks,
setter: setSelectedBlockId, setter: setSelectedBlockId,
updateFn: updateBlock, updateFn: updateBlock,
onRemoveNode: (ids, next) => { onRemoveNode: openDeleteDialog,
deleteDialogCtl.openDialog(ids);
deleteCallbackRef.current = next;
},
onDbClickNode: (event, id) => { onDbClickNode: (event, id) => {
if (id) { if (id) {
const block = getBlockFromCache(id); const block = getBlockFromCache(id);
editDialogCtl.openDialog(block); dialogs.open(BlockEditFormDialog, block, {
maxWidth: "md",
});
} }
}, },
targetPortChanged: ({ targetPortChanged: ({
@ -322,24 +314,24 @@ const Diagrams = () => {
), ),
]); ]);
const handleLinkDeletion = async (linkId: string) => { const handleLinkDeletion = (linkId: string, model: DiagramModel) => {
const link = model?.getLink(linkId) as any; const link = model?.getLink(linkId) as any;
const sourceId = link?.sourcePort.parent.options.id; const sourceId = link?.sourcePort.parent.options.id;
const targetId = link?.targetPort.parent.options.id; const targetId = link?.targetPort.parent.options.id;
if (link?.sourcePort.options.label === BlockPorts.nextBlocksOutPort) { if (link?.sourcePort.options.label === BlockPorts.nextBlocksOutPort) {
await removeNextBlockLink(sourceId, targetId); removeNextBlockLink(sourceId, targetId);
} else if ( } else if (
link?.sourcePort.options.label === BlockPorts.attachmentOutPort link?.sourcePort.options.label === BlockPorts.attachmentOutPort
) { ) {
await removeAttachmentLink(sourceId, targetId); removeAttachedLink(sourceId, targetId);
} }
}; };
const removeNextBlockLink = async (sourceId: string, targetId: string) => { const removeNextBlockLink = (sourceId: string, targetId: string) => {
const previousData = getBlockFromCache(sourceId); const previousData = getBlockFromCache(sourceId);
const nextBlocks = [...(previousData?.nextBlocks || [])]; const nextBlocks = [...(previousData?.nextBlocks || [])];
await updateBlock( updateBlock(
{ {
id: sourceId, id: sourceId,
params: { params: {
@ -361,8 +353,8 @@ const Diagrams = () => {
}, },
); );
}; };
const removeAttachmentLink = async (sourceId: string, targetId: string) => { const removeAttachedLink = (sourceId: string, targetId: string) => {
await updateBlock( updateBlock(
{ {
id: sourceId, id: sourceId,
params: { attachedBlock: null }, params: { attachedBlock: null },
@ -377,8 +369,8 @@ const Diagrams = () => {
}, },
); );
}; };
const handleBlocksDeletion = async (blockIds: string[]) => { const handleBlocksDeletion = (blockIds: string[]) => {
await deleteBlocks(blockIds, { deleteBlocks(blockIds, {
onSuccess: () => { onSuccess: () => {
blockIds.forEach((blockId) => { blockIds.forEach((blockId) => {
const block = getBlockFromCache(blockId); const block = getBlockFromCache(blockId);
@ -428,60 +420,76 @@ const Diagrams = () => {
} }
}); });
}; };
const cleanupAfterDeletion = () => { const getSelectedIds = () => {
deleteCallbackRef.current?.(); const entities = engine?.getModel().getSelectedEntities();
deleteCallbackRef.current = () => {}; const ids = entities?.map((model) => model.getID());
deleteDialogCtl.closeDialog();
};
const handleDeleteButton = () => {
const selectedEntities = engine?.getModel().getSelectedEntities();
const ids = selectedEntities?.map((model) => model.getID());
if (ids && selectedEntities && ids.length > 0) { return ids || [];
deleteCallbackRef.current = () => {
selectedEntities.forEach((model) => {
model.setLocked(false);
model.remove();
});
engine?.repaintCanvas();
}; };
deleteDialogCtl.openDialog(ids); const getGroupedIds = (ids: string[]) => {
return ids.reduce(
(acc, str) => ({
...acc,
...(str.length === 36
? { linkIds: [...acc.linkIds, str] }
: { blockIds: [...acc.blockIds, str] }),
}),
{ linkIds: [] as string[], blockIds: [] as string[] },
);
};
const hasSelectedBlock = () => {
const ids = getSelectedIds();
return getGroupedIds(ids).blockIds.length > 0;
};
const openDeleteDialog = async () => {
const ids = getSelectedIds();
const model = engine?.getModel();
if (ids.length) {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody, {
mode: "selection",
count: ids.length,
isSingleton: true,
});
if (isConfirmed && model) {
onDelete(ids, model);
}
} }
}; };
const handleMoveButton = () => { const handleMoveButton = () => {
const selectedEntities = engine?.getModel().getSelectedEntities().reverse(); const ids = getSelectedIds();
const ids = selectedEntities?.map((model) => model.getID()); const { blockIds } = getGroupedIds(ids);
if (ids && selectedEntities) { if (ids.length) {
moveDialogCtl.openDialog(ids); dialogs.open(BlockMoveFormDialog, {
ids: blockIds,
onMove,
category: selectedCategoryId,
categories,
});
} }
}; };
const onDelete = async () => { const onDelete = (ids: string[], model: DiagramModel) => {
const ids = deleteDialogCtl?.data;
if (!ids || ids?.length === 0) { if (!ids || ids?.length === 0) {
return; return;
} }
const isLink = ids[0].length === 36;
if (isLink) { const { linkIds, blockIds } = getGroupedIds(ids);
await handleLinkDeletion(ids[0]);
} else { if (linkIds.length && !blockIds.length) {
await handleBlocksDeletion(ids); linkIds.forEach((linkId) => handleLinkDeletion(linkId, model));
} else if (blockIds.length) {
handleBlocksDeletion(blockIds);
} }
cleanupAfterDeletion();
}; };
const onMove = async (newCategoryId?: string) => { const onMove = (ids: string[], targetCategoryId: string) => {
if (!newCategoryId) { if (ids.length) {
return; updateBlocks(
} { ids, payload: { category: targetCategoryId } },
{
const ids = moveDialogCtl?.data; onSuccess() {
if (ids?.length && Array.isArray(ids)) {
await updateBlocks({ ids, payload: { category: newCategoryId } });
queryClient.invalidateQueries({ queryClient.invalidateQueries({
predicate: ({ queryKey }) => { predicate: ({ queryKey }) => {
const [qType, qEntity] = queryKey; const [qType, qEntity] = queryKey;
@ -493,9 +501,12 @@ const Diagrams = () => {
}, },
}); });
setSelectedCategoryId(newCategoryId); onCategoryChange(
setSelectedBlockId(undefined); categories.findIndex(({ id }) => id === targetCategoryId),
moveDialogCtl.closeDialog(); );
},
},
);
} }
}; };
@ -528,15 +539,6 @@ const Diagrams = () => {
}} }}
> >
<Box sx={{ width: "100%" }}> <Box sx={{ width: "100%" }}>
<BlockDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog<string[]> {...deleteDialogCtl} callback={onDelete} />
<MoveDialog
open={moveDialogCtl.open}
openDialog={moveDialogCtl.openDialog}
callback={onMove}
closeDialog={moveDialogCtl.closeDialog}
categories={categories}
/>
<Grid sx={{ bgcolor: "#fff", padding: "0" }}> <Grid sx={{ bgcolor: "#fff", padding: "0" }}>
<Grid <Grid
sx={{ sx={{
@ -585,12 +587,10 @@ const Diagrams = () => {
backgroundColor: "#F8F8F8", backgroundColor: "#F8F8F8",
borderBottom: "none", borderBottom: "none",
minHeight: "30px", minHeight: "30px",
"&.Mui-selected": { "&.Mui-selected": {
backgroundColor: "#EAF1F1", backgroundColor: "#EAF1F1",
zIndex: 1, zIndex: 1,
color: "#000", color: "#000",
backgroundSize: "20px 20px", backgroundSize: "20px 20px",
backgroundAttachment: "fixed", backgroundAttachment: "fixed",
backgroundPosition: "-1px -1px", backgroundPosition: "-1px -1px",
@ -617,15 +617,14 @@ const Diagrams = () => {
ml: "5px", ml: "5px",
borderRadius: "0", borderRadius: "0",
minHeight: "30px", minHeight: "30px",
border: "1px solid #DDDDDD", border: "1px solid #DDDDDD",
backgroundColor: "#F8F8F8", backgroundColor: "#F8F8F8",
borderBottom: "none", borderBottom: "none",
width: "42px", width: "42px",
minWidth: "42px", minWidth: "42px",
}} }}
onClick={async (e) => { onClick={(e) => {
await dialogs.open(CategoryFormDialog, null); dialogs.open(CategoryFormDialog, null);
e.preventDefault(); e.preventDefault();
}} }}
> >
@ -653,10 +652,12 @@ const Diagrams = () => {
if (selectedBlockId) { if (selectedBlockId) {
const block = getBlockFromCache(selectedBlockId); const block = getBlockFromCache(selectedBlockId);
editDialogCtl.openDialog(block); dialogs.open(BlockEditFormDialog, block, {
maxWidth: "md",
});
} }
}} }}
disabled={!selectedBlockId || selectedBlockId.length !== 24} disabled={getSelectedIds().length > 1 || !hasSelectedBlock()}
> >
{t("button.edit")} {t("button.edit")}
</Button> </Button>
@ -665,7 +666,7 @@ const Diagrams = () => {
variant="contained" variant="contained"
startIcon={<MoveUp />} startIcon={<MoveUp />}
onClick={handleMoveButton} onClick={handleMoveButton}
disabled={!selectedBlockId || selectedBlockId.length !== 24} disabled={!hasSelectedBlock()}
> >
{t("button.move")} {t("button.move")}
</Button> </Button>
@ -675,8 +676,8 @@ const Diagrams = () => {
variant="contained" variant="contained"
color="secondary" color="secondary"
startIcon={<DeleteIcon />} startIcon={<DeleteIcon />}
onClick={handleDeleteButton} onClick={() => openDeleteDialog()}
disabled={!selectedBlockId} disabled={!getSelectedIds().length}
> >
{t("button.remove")} {t("button.remove")}
</Button> </Button>
@ -698,7 +699,6 @@ const Diagrams = () => {
"&.MuiButtonGroup-contained:hover": { "&.MuiButtonGroup-contained:hover": {
boxShadow: "0 0 8px #0005", boxShadow: "0 0 8px #0005",
}, },
"& .MuiButton-root": { "& .MuiButton-root": {
backgroundColor: "background.paper", backgroundColor: "background.paper",
}, },

View File

@ -47,6 +47,8 @@ export const DialogsContext = createContext<
function DialogsProvider(props: DialogProviderProps) { function DialogsProvider(props: DialogProviderProps) {
const { children, unmountAfter = 1000 } = props; const { children, unmountAfter = 1000 } = props;
const [stack, setStack] = useState<DialogStackEntry<any, any>[]>([]); const [stack, setStack] = useState<DialogStackEntry<any, any>[]>([]);
let selectComponent: (typeof stack)[number]["Component"] | undefined =
undefined;
const keyPrefix = useId(); const keyPrefix = useId();
const nextId = useRef(0); const nextId = useRef(0);
const requestDialog = useCallback<OpenDialog>( const requestDialog = useCallback<OpenDialog>(
@ -80,7 +82,10 @@ function DialogsProvider(props: DialogProviderProps) {
msgProps: rest, msgProps: rest,
}; };
if (selectComponent !== Component || !rest.isSingleton) {
selectComponent = Component;
setStack((prevStack) => [...prevStack, newEntry]); setStack((prevStack) => [...prevStack, newEntry]);
}
return promise; return promise;
}, },
@ -99,6 +104,7 @@ function DialogsProvider(props: DialogProviderProps) {
prevStack.filter((entry) => entry.promise !== dialog), prevStack.filter((entry) => entry.promise !== dialog),
); );
}, unmountAfter); }, unmountAfter);
selectComponent = undefined;
}, },
[unmountAfter], [unmountAfter],
); );

View File

@ -32,7 +32,7 @@ export const useDialogs = (): DialogHook => {
const { open, close } = context; const { open, close } = context;
const confirm = React.useCallback<OpenConfirmDialog>( const confirm = React.useCallback<OpenConfirmDialog>(
async (msg, { onClose, ...options } = {}) => { async (msg, { onClose, ...options } = {}) => {
const { count, mode, ...rest } = options; const { count, mode, isSingleton, ...rest } = options;
return open( return open(
ConfirmDialog, ConfirmDialog,
@ -44,6 +44,7 @@ export const useDialogs = (): DialogHook => {
mode, mode,
count, count,
onClose, onClose,
isSingleton,
}, },
); );
}, },

View File

@ -14,6 +14,7 @@ interface DialogExtraOptions {
count?: number; count?: number;
maxWidth?: MuiDialogProps["maxWidth"]; maxWidth?: MuiDialogProps["maxWidth"];
hasButtons?: boolean; hasButtons?: boolean;
isSingleton?: boolean;
} }
// context // context
export interface OpenDialogOptions<R> extends DialogExtraOptions { export interface OpenDialogOptions<R> extends DialogExtraOptions {