refactor(frontend): update menu dialogs

This commit is contained in:
yassinedorbozgithub 2025-02-06 11:50:48 +01:00
parent 09a506672e
commit 5722ae0f05
4 changed files with 231 additions and 276 deletions

View File

@ -1,188 +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,
DialogProps,
MenuItem,
} from "@mui/material";
import { FC, useEffect } 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 { ToggleableInput } from "@/app-components/inputs/ToggleableInput";
import { useTranslate } from "@/hooks/useTranslate";
import { IMenuItem, IMenuItemAttributes, MenuType } from "@/types/menu.types";
import { isAbsoluteUrl } from "@/utils/URL";
export type MenuDialogProps = DialogProps & {
open: boolean;
closeFunction?: () => void;
createFunction?: (_menu: IMenuItemAttributes) => void;
editFunction?: (_menu: IMenuItemAttributes) => void;
row?: IMenuItem;
parentId?: string;
};
const DEFAULT_VALUES = { title: "", type: MenuType.web_url, url: undefined };
export const MenuDialog: FC<MenuDialogProps> = ({
open,
closeFunction,
createFunction,
editFunction,
row,
parentId,
...rest
}) => {
const { t } = useTranslate();
const {
reset,
resetField,
control,
formState: { errors },
handleSubmit,
register,
watch,
} = useForm<IMenuItemAttributes>({
defaultValues: DEFAULT_VALUES,
});
const validationRules = {
type: {
required: t("message.type_is_required"),
},
title: { required: t("message.title_is_required") },
url: {
required: t("message.url_is_invalid"),
validate: (value: string = "") =>
isAbsoluteUrl(value) || t("message.url_is_invalid"),
},
payload: {},
};
const onSubmitForm = async (data: IMenuItemAttributes) => {
if (createFunction) {
createFunction({ ...data, parent: parentId });
} else if (editFunction) {
editFunction({ ...data, parent: parentId });
}
};
useEffect(() => {
if (open) {
if (row) {
reset(row);
} else {
reset(DEFAULT_VALUES);
}
}
}, [open, reset, row]);
const typeValue = watch("type");
const titleValue = watch("title");
return (
<Dialog open={open} fullWidth onClose={closeFunction} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeFunction}>
{createFunction
? t("title.add_menu_item")
: t("title.edit_menu_item")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentContainer flexDirection="row">
<ContentItem>
<Controller
name="type"
rules={validationRules.type}
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<Input
select
label={t("placeholder.type")}
error={!!errors.type}
inputRef={field.ref}
required
onChange={({ target: { value } }) => {
onChange(value);
resetField("url");
}}
helperText={errors.type ? errors.type.message : null}
{...rest}
>
{Object.keys(MenuType).map((value, key) => (
<MenuItem value={value} key={key}>
{t(`label.${value}`)}
</MenuItem>
))}
</Input>
);
}}
/>
</ContentItem>
<ContentItem flex={1}>
<Input
label={t("placeholder.title")}
error={!!errors.title}
required
autoFocus
helperText={errors.title ? errors.title.message : null}
{...register("title", validationRules.title)}
/>
</ContentItem>
</ContentContainer>
<ContentItem>
{typeValue === MenuType.web_url ? (
<Input
label={t("label.web_url")}
error={!!errors.url}
required
helperText={errors.url ? errors.url.message : null}
{...register("url", validationRules.url)}
/>
) : typeValue === MenuType.postback ? (
<Controller
name="payload"
control={control}
render={({ field }) => {
return (
<ToggleableInput
label={t("label.payload")}
error={!!errors.payload}
required
defaultValue={row?.payload || ""}
readOnlyValue={titleValue}
helperText={
errors.payload ? errors.payload.message : null
}
{...field}
/>
);
}}
/>
) : null}
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeFunction} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,181 @@
/*
* 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 } from "@mui/material";
import { FC, Fragment, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import { ToggleableInput } from "@/app-components/inputs/ToggleableInput";
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 { ComponentFormProps } from "@/types/common/dialogs.types";
import { IMenuItemAttributes, MenuType } from "@/types/menu.types";
import { isAbsoluteUrl } from "@/utils/URL";
import { MenuFormDialogProps } from "./MenuFormDialog";
const DEFAULT_VALUES = { title: "", type: MenuType.web_url, url: undefined };
export const MenuForm: FC<ComponentFormProps<MenuFormDialogProps>> = ({
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: createMenu } = useCreate(EntityType.MENU, options);
const { mutate: updateMenu } = useUpdate(EntityType.MENU, options);
const {
watch,
reset,
control,
register,
formState: { errors },
resetField,
handleSubmit,
} = useForm<IMenuItemAttributes>({
defaultValues: DEFAULT_VALUES,
});
const validationRules = {
type: {
required: t("message.type_is_required"),
},
title: { required: t("message.title_is_required") },
url: {
required: t("message.url_is_invalid"),
validate: (value: string = "") =>
isAbsoluteUrl(value) || t("message.url_is_invalid"),
},
payload: {},
};
const onSubmitForm = (params: IMenuItemAttributes) => {
if (data?.row?.id) {
updateMenu({
id: data.row.id,
params,
});
} else {
createMenu({ ...params, parent: data?.parentId });
}
};
useEffect(() => {
if (data?.row) {
reset(data.row);
} else {
reset(DEFAULT_VALUES);
}
}, [reset, data?.row]);
const typeValue = watch("type");
const titleValue = watch("title");
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentContainer flexDirection="row">
<ContentItem>
<Controller
name="type"
rules={validationRules.type}
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<Input
select
label={t("placeholder.type")}
error={!!errors.type}
inputRef={field.ref}
required
onChange={({ target: { value } }) => {
onChange(value);
resetField("url");
}}
helperText={errors.type ? errors.type.message : null}
{...rest}
>
{Object.keys(MenuType).map((value, key) => (
<MenuItem value={value} key={key}>
{t(`label.${value}`)}
</MenuItem>
))}
</Input>
);
}}
/>
</ContentItem>
<ContentItem flex={1}>
<Input
label={t("placeholder.title")}
error={!!errors.title}
required
autoFocus
helperText={errors.title ? errors.title.message : null}
{...register("title", validationRules.title)}
/>
</ContentItem>
</ContentContainer>
<ContentItem>
{typeValue === MenuType.web_url ? (
<Input
label={t("label.web_url")}
error={!!errors.url}
required
helperText={errors.url ? errors.url.message : null}
{...register("url", validationRules.url)}
/>
) : typeValue === MenuType.postback ? (
<Controller
name="payload"
control={control}
render={({ field }) => {
return (
<ToggleableInput
label={t("label.payload")}
error={!!errors.payload}
required
defaultValue={data?.row?.payload || ""}
readOnlyValue={titleValue}
helperText={
errors.payload ? errors.payload.message : null
}
{...field}
/>
);
}}
/>
) : null}
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,31 @@
/*
* 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 { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { IMenuItem } from "@/types/menu.types";
import { MenuForm } from "./MenuForm";
export type MenuFormDialogProps = {
row?: IMenuItem;
rowId?: string;
parentId?: string;
};
export const MenuFormDialog = <
T extends MenuFormDialogProps = MenuFormDialogProps,
>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={MenuForm}
addText="title.add_menu_item"
editText="title.edit_menu_item"
{...props}
/>
);

View File

@ -8,35 +8,26 @@
import { faBars } from "@fortawesome/free-solid-svg-icons";
import AddIcon from "@mui/icons-material/Add";
import { Grid, Paper, Button, Box, debounce } from "@mui/material";
import React, { useRef, useState } from "react";
import { Box, Button, debounce, Grid, Paper } from "@mui/material";
import { useRef, useState } from "react";
import { DeleteDialog } from "@/app-components/dialogs/DeleteDialog";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { NoDataOverlay } from "@/app-components/tables/NoDataOverlay";
import { useCreate } from "@/hooks/crud/useCreate";
import { useDelete } from "@/hooks/crud/useDelete";
import { useFind } from "@/hooks/crud/useFind";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useDialogs } from "@/hooks/useDialogs";
import { useHasPermission } from "@/hooks/useHasPermission";
import { useTranslate } from "@/hooks/useTranslate";
import { PageHeader } from "@/layout/content/PageHeader";
import { EntityType } from "@/services/types";
import { IMenuItem } from "@/types/menu.types";
import { PermissionAction } from "@/types/permission.types";
import MenuAccordion from "./MenuAccordion";
import { MenuDialog } from "./MenuDialog";
import { MenuFormDialog } from "./MenuFormDialog";
export const Menu = () => {
const { t } = useTranslate();
const [addDialogOpened, setAddDialogOpened] = useState(false);
const [editDialogOpened, setEditDialogOpened] = useState(false);
const [selectedMenuId, setSelectedMenuId] = useState<string | undefined>(
undefined,
);
const [editRow, setEditRow] = useState<IMenuItem | null>(null);
const [deleteDialogOpened, setDeleteDialogOpened] = useState(false);
const [deleteRowId, setDeleteRowId] = useState<string>();
const dialogs = useDialogs();
const hasPermission = useHasPermission();
const { data: menus, refetch } = useFind(
{ entity: EntityType.MENUTREE },
@ -44,38 +35,11 @@ export const Menu = () => {
hasCount: false,
},
);
const { mutateAsync: createMenu } = useCreate(EntityType.MENU, {
const { mutate: deleteMenu } = useDelete(EntityType.MENU, {
onSuccess: () => {
setAddDialogOpened(false);
refetch();
},
});
const { mutateAsync: updateMenu } = useUpdate(EntityType.MENU, {
onSuccess: () => {
setEditDialogOpened(false);
setEditRow(null);
refetch();
},
});
const { mutateAsync: deleteMenu } = useDelete(EntityType.MENU, {
onSuccess: () => {
setDeleteDialogOpened(false);
refetch();
},
});
const handleAppend = (menuId: string) => {
setSelectedMenuId(menuId);
setAddDialogOpened(true);
refetch();
};
const handleUpdate = (menu: IMenuItem) => {
setEditRow(menu);
setEditDialogOpened(true);
};
const handleDelete = (menu: IMenuItem) => {
setDeleteRowId(menu.id);
setDeleteDialogOpened(true);
};
const [position, setPosition] = useState(0);
const ref = useRef<HTMLDivElement>(null);
const [shadowVisible, setShadowVisible] = useState(false);
@ -95,10 +59,7 @@ export const Menu = () => {
{hasPermission(EntityType.MENU, PermissionAction.CREATE) ? (
<Button
variant="contained"
onClick={() => {
setSelectedMenuId(undefined);
setAddDialogOpened(true);
}}
onClick={() => dialogs.open(MenuFormDialog, null)}
disabled={menus?.length === 10}
startIcon={<AddIcon />}
>
@ -108,17 +69,16 @@ export const Menu = () => {
</Grid>
</Grid>
</PageHeader>
<Paper
ref={ref}
onMouseMove={debounce((e) => {
if (!ref.current) return;
const padding = 16;
const boxHeight = 56;
const mousePositonInsideElement =
const mousePositionInsideElement =
e.clientY - ref.current?.getBoundingClientRect().top - padding;
const currentBlock = Math.floor(
mousePositonInsideElement / boxHeight,
mousePositionInsideElement / boxHeight,
);
const maxBlock = Math.floor(
(ref.current.getBoundingClientRect().height - padding - 1) /
@ -137,41 +97,6 @@ export const Menu = () => {
onMouseLeave={() => setShadowVisible(false)}
onMouseEnter={() => setShadowVisible(true)}
>
<MenuDialog
open={addDialogOpened}
parentId={selectedMenuId}
closeFunction={() => {
setAddDialogOpened(false);
setEditDialogOpened(false);
}}
createFunction={createMenu}
/>
{editRow ? (
<MenuDialog
row={editRow}
open={editDialogOpened}
editFunction={(params) => {
if (editRow.id) updateMenu({ id: editRow.id, params });
}}
closeFunction={() => {
setEditDialogOpened(false);
setEditRow(null);
}}
/>
) : null}
<DeleteDialog
open={deleteDialogOpened}
openDialog={() => setDeleteDialogOpened(true)}
closeDialog={() => setDeleteDialogOpened(false)}
callback={() => {
if (deleteRowId) {
deleteMenu(deleteRowId);
}
}}
/>
{menus?.length > 0 && (
<Box
sx={{
@ -194,9 +119,15 @@ export const Menu = () => {
<MenuAccordion
key={menu.id}
menu={menu}
onAppend={handleAppend}
onUpdate={handleUpdate}
onDelete={handleDelete}
onAppend={(parentId) => dialogs.open(MenuFormDialog, { parentId })}
onUpdate={(row) => dialogs.open(MenuFormDialog, { row })}
onDelete={async (row) => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody);
if (isConfirmed) {
deleteMenu(row.id);
}
}}
/>
))}
</Paper>