Merge pull request #662 from Hexastack/refactor/category-dialog
Some checks are pending
Build and Push Docker API Image / build-and-push (push) Waiting to run
Build and Push Docker Base Image / build-and-push (push) Waiting to run
Build and Push Docker UI Image / build-and-push (push) Waiting to run

refactor(frontend): category dialog
This commit is contained in:
Med Marrouchi 2025-02-05 09:01:29 +01:00 committed by GitHub
commit 2afb813cee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 818 additions and 205 deletions

View File

@ -44,6 +44,8 @@
"account_disabled": "Your account has been either disabled or is pending confirmation.",
"success_invitation_sent": "Invitation to join has been successfully sent.",
"item_delete_confirm": "Are you sure you want to delete this item?",
"item_selected_delete_confirm": "Are you sure you want to delete this selected item?",
"items_selected_delete_confirm": "Are you sure you want to delete those {{0}} selected items?",
"item_delete_success": "Item has been deleted successfully",
"success_save": "Changes has been saved!",
"no_result_found": "No result found",

View File

@ -44,6 +44,8 @@
"account_disabled": "Votre compte a été désactivé ou est en attente de confirmation.",
"success_invitation_sent": "L'invitation a été envoyée avec succès.",
"item_delete_confirm": "Êtes-vous sûr de bien vouloir supprimer cet élément?",
"item_selected_delete_confirm": "Êtes-vous sûr de bien vouloir supprimer cet élément sélectionné?",
"items_selected_delete_confirm": "Êtes-vous sûr de bien vouloir supprimer ces {{0}} éléments sélectionnés?",
"item_delete_success": "L'élément a été supprimé avec succès",
"success_save": "Les modifications ont été enregistrées!",
"no_result_found": "Aucun résultat trouvé",

View File

@ -0,0 +1,44 @@
/*
* 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 CheckIcon from "@mui/icons-material/Check";
import CloseIcon from "@mui/icons-material/Close";
import { Button, Grid } from "@mui/material";
import { useTranslate } from "@/hooks/useTranslate";
import { FormButtonsProps } from "@/types/common/dialogs.types";
export const DialogFormButtons = ({ onCancel, onSubmit }: FormButtonsProps) => {
const { t } = useTranslate();
return (
<Grid
p="0.3rem 1rem"
width="100%"
display="flex"
justifyContent="space-between"
>
<Button
color="error"
variant="outlined"
onClick={onCancel}
startIcon={<CloseIcon />}
>
{t("button.cancel")}
</Button>
<Button
type="button"
variant="contained"
onClick={onSubmit}
startIcon={<CheckIcon />}
>
{t("button.submit")}
</Button>
</Grid>
);
};

View File

@ -1,5 +1,5 @@
/*
* 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.
@ -8,10 +8,10 @@
import CloseIcon from "@mui/icons-material/Close";
import {
IconButton,
DialogTitle as MuiDialogTitle,
Typography,
styled,
DialogTitle as MuiDialogTitle,
IconButton,
} from "@mui/material";
const StyledDialogTitle = styled(Typography)(() => ({
@ -28,8 +28,10 @@ export const DialogTitle = ({
}) => (
<MuiDialogTitle>
<StyledDialogTitle>{children}</StyledDialogTitle>
<IconButton size="small" aria-label="close" onClick={onClose}>
<CloseIcon />
</IconButton>
{onClose ? (
<IconButton size="small" aria-label="close" onClick={onClose}>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);

View File

@ -0,0 +1,33 @@
/*
* 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 { Dialog, DialogActions, DialogContent } from "@mui/material";
import { DialogTitle } from "@/app-components/dialogs";
import { FormDialogProps } from "@/types/common/dialogs.types";
import { DialogFormButtons } from "../buttons/FormButtons";
export const FormDialog = ({
title,
children,
onSubmit,
...rest
}: FormDialogProps) => {
const handleClose = () => rest.onClose?.({}, "backdropClick");
return (
<Dialog fullWidth {...rest}>
<DialogTitle onClose={handleClose}>{title}</DialogTitle>
<DialogContent>{children}</DialogContent>
<DialogActions style={{ padding: "0.5rem" }}>
<DialogFormButtons onCancel={handleClose} onSubmit={onSubmit} />
</DialogActions>
</Dialog>
);
};

View File

@ -0,0 +1,74 @@
/*
* 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 {
Button,
Dialog,
DialogActions,
DialogContent,
Grid,
} from "@mui/material";
import { cloneElement, FC, ReactNode } from "react";
import { useTranslate } from "@/hooks/useTranslate";
import { ConfirmOptions, DialogProps } from "@/types/common/dialogs.types";
import { DialogTitle } from "../DialogTitle";
import { useDialogLoadingButton } from "./hooks/useDialogLoadingButton";
export interface ConfirmDialogPayload extends ConfirmOptions {
msg: ReactNode;
}
export interface ConfirmDialogProps
extends DialogProps<ConfirmDialogPayload, boolean> {
mode?: "selection" | "click";
count?: number;
}
export const ConfirmDialog: FC<ConfirmDialogProps> = ({ payload, ...rest }) => {
const { t } = useTranslate();
const cancelButtonProps = useDialogLoadingButton(() => rest.onClose(false));
const okButtonProps = useDialogLoadingButton(() => rest.onClose(true));
// @ts-ignore
const messageReactNode = cloneElement(payload.msg, {
mode: rest.mode,
count: rest.count,
});
return (
<Dialog
maxWidth="sm"
fullWidth
{...rest}
onClose={() => rest.onClose(false)}
>
<DialogTitle onClose={() => rest.onClose(false)}>
{payload.title || t("title.warning")}
</DialogTitle>
<DialogContent>{messageReactNode}</DialogContent>
<DialogActions style={{ padding: "0.5rem" }}>
<Grid p="0.3rem 1rem" gap="0.5rem" display="flex">
<Button
color={payload.severity || "error"}
variant="contained"
disabled={!open}
autoFocus
{...okButtonProps}
>
{payload.okText || t("label.yes")}
</Button>
<Button variant="outlined" disabled={!open} {...cancelButtonProps}>
{payload.cancelText || t("label.no")}
</Button>
</Grid>
</DialogActions>
</Dialog>
);
};

View File

@ -0,0 +1,41 @@
/*
* 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 ErrorIcon from "@mui/icons-material/Error";
import { Grid, Typography } from "@mui/material";
import { useTranslate } from "@/hooks/useTranslate";
export const ConfirmDialogBody = ({
mode = "click",
count = 1,
}: {
mode?: "selection" | "click";
count?: number;
}) => {
const { t } = useTranslate();
const dialogBodyText =
mode === "selection"
? count === 1
? t("message.item_selected_delete_confirm")
: t("message.items_selected_delete_confirm", {
"0": count.toString(),
})
: t("message.item_delete_confirm");
return (
<Grid container gap={1}>
<Grid item height="1.75rem">
<ErrorIcon sx={{ fontSize: "1.75rem" }} color="error" />
</Grid>
<Grid item alignSelf="center">
<Typography>{dialogBodyText}</Typography>
</Grid>
</Grid>
);
};

View File

@ -0,0 +1,26 @@
/*
* 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 { useState } from "react";
export const useDialogLoadingButton = (onClose: () => Promise<void>) => {
const [loading, setLoading] = useState(false);
const handleClick = async () => {
try {
setLoading(true);
await onClose();
} finally {
setLoading(false);
}
};
return {
onClick: handleClick,
loading,
};
};

View File

@ -6,7 +6,10 @@
* 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).
*/
export * from "./confirm/ConfirmDialog";
export * from "./confirm/ConfirmDialogBody";
export * from "./DeleteDialog";
export * from "./DialogTitle";
export * from "./FormDialog";
export * from "./layouts/ContentContainer";
export * from "./layouts/ContentItem";

View File

@ -1,113 +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 { Dialog, DialogActions, DialogContent } from "@mui/material";
import { FC, useEffect } from "react";
import { 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 { useCreate } from "@/hooks/crud/useCreate";
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 { ICategory, ICategoryAttributes } from "@/types/category.types";
export type CategoryDialogProps = DialogControlProps<ICategory>;
export const CategoryDialog: FC<CategoryDialogProps> = ({
open,
data,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: createCategory } = useCreate(EntityType.CATEGORY, {
onError: (error) => {
toast.error(error);
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const { mutateAsync: updateCategory } = useUpdate(EntityType.CATEGORY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
reset,
register,
formState: { errors },
handleSubmit,
} = useForm<ICategoryAttributes>({
defaultValues: { label: data?.label || "" },
});
const validationRules = {
label: {
required: t("message.label_is_required"),
},
};
const onSubmitForm = async (params: ICategoryAttributes) => {
if (data) {
updateCategory({ id: data.id, params });
} else {
createCategory(params);
}
};
useEffect(() => {
if (open) reset();
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
label: data.label,
});
} else {
reset();
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{data ? t("title.edit_category") : t("title.new_category")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.label")}
{...register("label", validationRules.label)}
autoFocus
helperText={errors.label ? errors.label.message : null}
/>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,97 @@
/*
* 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 { FC, Fragment, useEffect } from "react";
import { useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import { useCreate } from "@/hooks/crud/useCreate";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ICategory, ICategoryAttributes } from "@/types/category.types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
export const CategoryForm: FC<ComponentFormProps<ICategory>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const options = {
onError: (error: Error) => {
rest.onError?.();
toast.error(error || t("message.internal_server_error"));
},
onSuccess: () => {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
};
const { mutate: createCategory } = useCreate(EntityType.CATEGORY, options);
const { mutate: updateCategory } = useUpdate(EntityType.CATEGORY, options);
const {
reset,
register,
formState: { errors },
handleSubmit,
} = useForm<ICategoryAttributes>({
defaultValues: { label: data?.label || "" },
});
const validationRules = {
label: {
required: t("message.label_is_required"),
},
};
const onSubmitForm = (params: ICategoryAttributes) => {
if (data) {
updateCategory({ id: data.id, params });
} else {
createCategory(params);
}
};
useEffect(() => {
if (data) {
reset({
label: data.label,
});
} else {
reset();
}
}, [data, reset]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.label")}
error={!!errors.label}
{...register("label", validationRules.label)}
required
autoFocus
helperText={errors.label ? errors.label.message : null}
/>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};
CategoryForm.displayName = "CategoryForm";

View File

@ -0,0 +1,37 @@
/*
* 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 { FC } from "react";
import { FormDialog } from "@/app-components/dialogs";
import { useTranslate } from "@/hooks/useTranslate";
import { ICategory } from "@/types/category.types";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { CategoryForm } from "./CategoryForm";
export const CategoryFormDialog: FC<ComponentFormDialogProps<ICategory>> = ({
payload,
...rest
}) => {
const { t } = useTranslate();
return (
<CategoryForm
data={payload}
onSuccess={() => {
rest.onClose(true);
}}
Wrapper={FormDialog}
WrapperProps={{
title: payload ? t("title.edit_category") : t("title.new_category"),
...rest,
}}
/>
);
};

View File

@ -1,5 +1,5 @@
/*
* 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.
@ -13,7 +13,7 @@ import { Button, Grid, Paper } from "@mui/material";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useState } from "react";
import { DeleteDialog } from "@/app-components/dialogs/DeleteDialog";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
import {
ActionColumnLabel,
@ -24,7 +24,7 @@ import { DataGrid } from "@/app-components/tables/DataGrid";
import { useDelete } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
import { useFind } from "@/hooks/crud/useFind";
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs";
import { useHasPermission } from "@/hooks/useHasPermission";
import { useSearch } from "@/hooks/useSearch";
import { useToast } from "@/hooks/useToast";
@ -36,14 +36,12 @@ import { getDateTimeFormatter } from "@/utils/date";
import { ICategory } from "../../types/category.types";
import { CategoryDialog } from "./CategoryDialog";
import { CategoryFormDialog } from "./CategoryFormDialog";
export const Categories = () => {
const { t } = useTranslate();
const { toast } = useToast();
const addDialogCtl = useDialog<ICategory>(false);
const editDialogCtl = useDialog<ICategory>(false);
const deleteDialogCtl = useDialog<string>(false);
const dialogs = useDialogs();
const hasPermission = useHasPermission();
const { onSearch, searchPayload } = useSearch<ICategory>({
$iLike: ["label"],
@ -54,38 +52,40 @@ export const Categories = () => {
params: searchPayload,
},
);
const { mutateAsync: deleteCategory } = useDelete(EntityType.CATEGORY, {
onError: (error) => {
const options = {
onError: (error: Error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess: () => {
deleteDialogCtl.closeDialog();
setSelectedCategories([]);
toast.success(t("message.item_delete_success"));
},
});
const { mutateAsync: deleteCategories } = useDeleteMany(EntityType.CATEGORY, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess: () => {
deleteDialogCtl.closeDialog();
setSelectedCategories([]);
toast.success(t("message.item_delete_success"));
},
});
};
const { mutate: deleteCategory } = useDelete(EntityType.CATEGORY, options);
const { mutate: deleteCategories } = useDeleteMany(
EntityType.CATEGORY,
options,
);
const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
const actionColumns = useActionColumns<ICategory>(
EntityType.CATEGORY,
[
{
label: ActionColumnLabel.Edit,
action: (row) => editDialogCtl.openDialog(row),
action: async (row) => {
await dialogs.open(CategoryFormDialog, row);
},
requires: [PermissionAction.UPDATE],
},
{
label: ActionColumnLabel.Delete,
action: (row) => deleteDialogCtl.openDialog(row.id),
action: async ({ id }) => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody);
if (isConfirmed) {
deleteCategory(id);
}
},
requires: [PermissionAction.DELETE],
},
],
@ -131,22 +131,6 @@ export const Categories = () => {
return (
<Grid container gap={3} flexDirection="column">
<CategoryDialog {...getDisplayDialogs(addDialogCtl)} />
<CategoryDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog
{...deleteDialogCtl}
callback={async () => {
if (selectedCategories.length > 0) {
deleteCategories(selectedCategories), setSelectedCategories([]);
deleteDialogCtl.closeDialog();
} else if (deleteDialogCtl?.data) {
{
deleteCategory(deleteDialogCtl.data);
deleteDialogCtl.closeDialog();
}
}
}}
/>
<Grid>
<PageHeader icon={FolderIcon} title={t("title.categories")}>
<Grid
@ -166,24 +150,30 @@ export const Categories = () => {
startIcon={<AddIcon />}
variant="contained"
sx={{ float: "right" }}
onClick={() => addDialogCtl.openDialog()}
onClick={() => dialogs.open(CategoryFormDialog, null)}
>
{t("button.add")}
</Button>
</Grid>
) : null}
{selectedCategories.length > 0 && (
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() => deleteDialogCtl.openDialog(undefined)}
>
{t("button.delete")}
</Button>
</Grid>
)}
<Button
color="error"
variant="contained"
onClick={async () => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody, {
mode: "selection",
count: selectedCategories.length,
});
if (isConfirmed) {
deleteCategories(selectedCategories);
}
}}
disabled={!selectedCategories.length}
startIcon={<DeleteIcon />}
>
{t("button.delete")}
</Button>
</Grid>
</PageHeader>
</Grid>

View File

@ -41,7 +41,7 @@ import { useQueryClient } from "react-query";
import { DeleteDialog } from "@/app-components/dialogs";
import { MoveDialog } from "@/app-components/dialogs/MoveDialog";
import { CategoryDialog } from "@/components/categories/CategoryDialog";
import { CategoryFormDialog } from "@/components/categories/CategoryFormDialog";
import { isSameEntity } from "@/hooks/crud/helpers";
import { useDeleteFromCache } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
@ -51,11 +51,11 @@ import { useUpdate, useUpdateCache } from "@/hooks/crud/useUpdate";
import { useUpdateMany } from "@/hooks/crud/useUpdateMany";
import useDebouncedUpdate from "@/hooks/useDebouncedUpdate";
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs";
import { useSearch } from "@/hooks/useSearch";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format, QueryType, RouterType } from "@/services/types";
import { IBlock } from "@/types/block.types";
import { ICategory } from "@/types/category.types";
import { BlockPorts } from "@/types/visual-editor.types";
import BlockDialog from "../BlockDialog";
@ -74,9 +74,9 @@ const Diagrams = () => {
const [engine, setEngine] = useState<DiagramEngine | undefined>();
const [canvas, setCanvas] = useState<JSX.Element | undefined>();
const [selectedBlockId, setSelectedBlockId] = useState<string | undefined>();
const dialogs = useDialogs();
const deleteDialogCtl = useDialog<string[]>(false);
const moveDialogCtl = useDialog<string[] | string>(false);
const addCategoryDialogCtl = useDialog<ICategory>(false);
const { mutateAsync: updateBlocks } = useUpdateMany(EntityType.BLOCK);
const {
buildDiagram,
@ -528,7 +528,6 @@ const Diagrams = () => {
}}
>
<Box sx={{ width: "100%" }}>
<CategoryDialog {...getDisplayDialogs(addCategoryDialogCtl)} />
<BlockDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog<string[]> {...deleteDialogCtl} callback={onDelete} />
<MoveDialog
@ -625,8 +624,8 @@ const Diagrams = () => {
width: "42px",
minWidth: "42px",
}}
onClick={(e) => {
addCategoryDialogCtl.openDialog();
onClick={async (e) => {
await dialogs.open(CategoryFormDialog, null);
e.preventDefault();
}}
>

View File

@ -0,0 +1,147 @@
/*
* 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 {
createContext,
useCallback,
useId,
useMemo,
useRef,
useState,
} from "react";
import {
CloseDialog,
DialogComponent,
DialogProviderProps,
DialogStackEntry,
OpenDialog,
OpenDialogOptions,
} from "@/types/common/dialogs.types";
export const DialogsContext = createContext<
| {
open: OpenDialog;
close: CloseDialog;
}
| undefined
>(undefined);
/**
* Provider for Dialog stacks. The subtree of this component can use the `useDialogs` hook to
* access the dialogs API. The dialogs are rendered in the order they are requested.
*
* Demos:
*
* - [useDialogs](https://mui.com/toolpad/core/react-use-dialogs/)
*
* API:
*
* - [DialogsProvider API](https://mui.com/toolpad/core/api/dialogs-provider)
*/
function DialogsProvider(props: DialogProviderProps) {
const { children, unmountAfter = 1000 } = props;
const [stack, setStack] = useState<DialogStackEntry<any, any>[]>([]);
const keyPrefix = useId();
const nextId = useRef(0);
const requestDialog = useCallback<OpenDialog>(
function open<P, R>(
Component: DialogComponent<P, R>,
payload: P,
options: OpenDialogOptions<R> = {},
) {
const { onClose = async () => {} } = options;
let resolve: ((result: R) => void) | undefined;
const promise = new Promise<R>((resolveImpl) => {
resolve = resolveImpl;
});
if (!resolve) {
throw new Error("resolve not set");
}
const key = `${keyPrefix}-${nextId.current}`;
nextId.current += 1;
const newEntry: DialogStackEntry<P, R> = {
key,
open: true,
promise,
Component,
payload,
onClose,
resolve,
msgProps: { count: options.count, mode: options.mode },
};
setStack((prevStack) => [...prevStack, newEntry]);
return promise;
},
[keyPrefix],
);
const closeDialogUi = useCallback(
function closeDialogUi<R>(dialog: Promise<R>) {
setStack((prevStack) =>
prevStack.map((entry) =>
entry.promise === dialog ? { ...entry, open: false } : entry,
),
);
setTimeout(() => {
// wait for closing animation
setStack((prevStack) =>
prevStack.filter((entry) => entry.promise !== dialog),
);
}, unmountAfter);
},
[unmountAfter],
);
const closeDialog = useCallback(
async function closeDialog<R>(dialog: Promise<R>, result: R) {
const entryToClose = stack.find((entry) => entry.promise === dialog);
if (!entryToClose) {
throw new Error("dialog not found");
}
await entryToClose.onClose(result);
entryToClose.resolve(result);
closeDialogUi(dialog);
return dialog;
},
[stack, closeDialogUi],
);
const contextValue = useMemo(
() => ({
open: requestDialog,
close: closeDialog,
}),
[requestDialog, closeDialog],
);
return (
<DialogsContext.Provider value={contextValue}>
{children}
{stack.map(({ key, open, Component, payload, promise, msgProps }) => (
<Component
key={key}
payload={payload}
open={open}
onClose={async (result) => {
await closeDialog(promise, result);
}}
{...msgProps}
/>
))}
</DialogsContext.Provider>
);
}
export { DialogsProvider };

View File

@ -0,0 +1,58 @@
/*
* 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 React, { useContext } from "react";
import { ConfirmDialog } from "@/app-components/dialogs";
import { DialogsContext } from "@/contexts/dialogs.context";
import {
CloseDialog,
OpenConfirmDialog,
OpenDialog,
} from "@/types/common/dialogs.types";
export interface DialogHook {
open: OpenDialog;
close: CloseDialog;
confirm: OpenConfirmDialog;
}
export const useDialogs = (): DialogHook => {
const context = useContext(DialogsContext);
if (!context) {
throw new Error("useDialogs must be used within a DialogsProvider");
}
const { open, close } = context;
const confirm = React.useCallback<OpenConfirmDialog>(
async (msg, { onClose, ...options } = {}) => {
const { count, mode, ...rest } = options;
return open(
ConfirmDialog,
{
...rest,
msg: React.createElement(msg),
},
{
mode,
count,
onClose,
},
);
},
[open],
);
return {
open,
close,
confirm,
};
};

View File

@ -21,6 +21,7 @@ import { ApiClientProvider } from "@/contexts/apiClient.context";
import { AuthProvider } from "@/contexts/auth.context";
import BroadcastChannelProvider from "@/contexts/broadcast-channel.context";
import { ConfigProvider } from "@/contexts/config.context";
import { DialogsProvider } from "@/contexts/dialogs.context";
import { PermissionProvider } from "@/contexts/permission.context";
import { SettingsProvider } from "@/contexts/setting.context";
import { ToastProvider } from "@/hooks/useToast";
@ -73,33 +74,37 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => {
<main className={roboto.className}>
<ConfigProvider>
<ThemeProvider theme={theme}>
<ToastProvider
maxSnack={3}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
action={(snackbarKey) => (
<SnackbarCloseButton snackbarKey={snackbarKey} />
)}
>
<StyledEngineProvider injectFirst>
<QueryClientProvider client={queryClient}>
<CssBaseline />
<ApiClientProvider>
<BroadcastChannelProvider channelName="main-channel">
<AuthProvider>
<PermissionProvider>
<SettingsProvider>
<SocketProvider>
{getLayout(<Component {...pageProps} />)}
</SocketProvider>
</SettingsProvider>
</PermissionProvider>
</AuthProvider>
</BroadcastChannelProvider>
</ApiClientProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</StyledEngineProvider>
</ToastProvider>
<DialogsProvider>
<ToastProvider
maxSnack={3}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
action={(snackbarKey) => (
<SnackbarCloseButton snackbarKey={snackbarKey} />
)}
>
<StyledEngineProvider injectFirst>
<QueryClientProvider client={queryClient}>
<CssBaseline />
<ApiClientProvider>
<DialogsProvider>
<BroadcastChannelProvider channelName="main-channel">
<AuthProvider>
<PermissionProvider>
<SettingsProvider>
<SocketProvider>
{getLayout(<Component {...pageProps} />)}
</SocketProvider>
</SettingsProvider>
</PermissionProvider>
</AuthProvider>
</BroadcastChannelProvider>
</DialogsProvider>
</ApiClientProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</StyledEngineProvider>
</ToastProvider>
</DialogsProvider>
</ThemeProvider>
</ConfigProvider>
</main>

View File

@ -0,0 +1,165 @@
/*
* 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 { DialogProps as MuiDialogProps } from "@mui/material";
import { BaseSyntheticEvent } from "react";
interface ConfirmDialogExtraOptions {
mode?: "click" | "selection";
count?: number;
}
// context
export interface OpenDialogOptions<R> extends ConfirmDialogExtraOptions {
/**
* A function that is called before closing the dialog closes. The dialog
* stays open as long as the returned promise is not resolved. Use this if
* you want to perform an async action on close and show a loading state.
*
* @param result The result that the dialog will return after closing.
* @returns A promise that resolves when the dialog can be closed.
*/
onClose?: (result: R) => Promise<void>;
}
/**
* The props that are passed to a dialog component.
*/
export interface DialogProps<P = undefined, R = void> {
/**
* The payload that was passed when the dialog was opened.
*/
payload: P;
/**
* Whether the dialog is open.
*/
open: boolean;
/**
* A function to call when the dialog should be closed. If the dialog has a return
* value, it should be passed as an argument to this function. You should use the promise
* that is returned to show a loading state while the dialog is performing async actions
* on close.
* @param result The result to return from the dialog.
* @returns A promise that resolves when the dialog can be fully closed.
*/
onClose: (result: R) => Promise<void>;
}
export type DialogComponent<P, R> = React.ComponentType<DialogProps<P, R>>;
export interface OpenDialog {
/**
* Open a dialog without payload.
* @param Component The dialog component to open.
* @param options Additional options for the dialog.
*/
<P extends undefined, R>(
Component: DialogComponent<P, R>,
payload?: P,
options?: OpenDialogOptions<R>,
): Promise<R>;
/**
* Open a dialog and pass a payload.
* @param Component The dialog component to open.
* @param payload The payload to pass to the dialog.
* @param options Additional options for the dialog.
*/
<P, R>(
Component: DialogComponent<P, R>,
payload: P,
options?: OpenDialogOptions<R>,
): Promise<R>;
}
export interface CloseDialog {
/**
* Close a dialog and return a result.
* @param dialog The dialog to close. The promise returned by `open`.
* @param result The result to return from the dialog.
* @returns A promise that resolves when the dialog is fully closed.
*/
<R>(dialog: Promise<R>, result: R): Promise<R>;
}
export interface ConfirmOptions extends OpenDialogOptions<boolean> {
/**
* A title for the dialog. Defaults to `'Confirm'`.
*/
title?: React.ReactNode;
/**
* The text to show in the "Ok" button. Defaults to `'Ok'`.
*/
okText?: React.ReactNode;
/**
* Denotes the purpose of the dialog. This will affect the color of the
* "Ok" button. Defaults to `undefined`.
*/
severity?: "error" | "info" | "success" | "warning";
/**
* The text to show in the "Cancel" button. Defaults to `'Cancel'`.
*/
cancelText?: React.ReactNode;
}
export interface OpenConfirmDialog {
/**
* Open a confirmation dialog. Returns a promise that resolves to true if
* the user confirms, false if the user cancels.
*
* @param msg The message to show in the dialog.
* @param options Additional options for the dialog.
* @returns A promise that resolves to true if the user confirms, false if the user cancels.
*/
(msg: React.ComponentType, options?: ConfirmOptions): Promise<boolean>;
}
export interface DialogHook {
// alert: OpenAlertDialog;
confirm: OpenConfirmDialog;
// prompt: OpenPromptDialog;
open: OpenDialog;
close: CloseDialog;
}
export interface DialogStackEntry<P, R> {
key: string;
open: boolean;
promise: Promise<R>;
Component: DialogComponent<P, R>;
payload: P;
onClose: (result: R) => Promise<void>;
resolve: (result: R) => void;
msgProps: ConfirmDialogExtraOptions;
}
export interface DialogProviderProps {
children?: React.ReactNode;
unmountAfter?: number;
}
// form dialog
export interface FormDialogProps extends MuiDialogProps {
title?: string;
children?: React.ReactNode;
onSubmit: (e: BaseSyntheticEvent) => void;
}
// form
export type ComponentFormProps<T> = {
data: T | null;
onError?: () => void;
onSuccess?: () => void;
Wrapper?: React.FC<FormDialogProps>;
WrapperProps?: Partial<FormDialogProps>;
};
export interface FormButtonsProps {
onCancel?: () => void;
onSubmit: (e: BaseSyntheticEvent) => void;
}
export type ComponentFormDialogProps<T> = DialogProps<T | null, boolean>;

View File

@ -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 { PropsWithChildren } from "react";
import Launcher from "./components/Launcher";