481 lines
19 KiB
TypeScript
481 lines
19 KiB
TypeScript
// * Packages
|
|
import { useForm, usePage } from "@inertiajs/react";
|
|
import { BookTextIcon, CogIcon, EyeIcon, GavelIcon, ShieldAlertIcon } from "lucide-react";
|
|
import { route } from "ziggy-js";
|
|
import { FormEvent, useEffect, useState } from "react";
|
|
// * Components shadcn
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogDescription,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogFooter,
|
|
DialogTrigger,
|
|
} from "@/components/ui/dialog";
|
|
// * Other
|
|
import SimpleString from "@/back/Components/Inputs/SimpleString";
|
|
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
|
|
import SimpleWysiwyg from "@/back/Components/Inputs/SimpleWysiwyg";
|
|
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
|
|
import ModelSelect from "@/back/Components/Inputs/ModelSelect";
|
|
import DynamicInputs from "@/back/Components/DynamicPages/DynamicInputs";
|
|
import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
|
|
import ConfigTable from "@/back/Components/PageConfigs/ConfigTable";
|
|
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
|
|
import useTrans from "@/hooks/use-translations";
|
|
import InputError from "@/back/Components/InputError";
|
|
import str from "@/hooks/use-string";
|
|
import { useToast } from "@/hooks/use-toast";
|
|
import { Methods } from "@/lib/enums";
|
|
import { AppEnv, AuthProp, ConfigField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global";
|
|
import GoToFrontView from "@/back/Components/GoToFrontView";
|
|
|
|
export default function Form({
|
|
model,
|
|
modelName,
|
|
modelRoute,
|
|
action,
|
|
method,
|
|
}: {
|
|
model?: DynamicPageModel;
|
|
modelName: string;
|
|
modelRoute: string;
|
|
action: string;
|
|
method: number;
|
|
}) {
|
|
/** Set messages success/errors */
|
|
const messages = {} as Record<string, string>;
|
|
messages.titleSuccess = useTrans(
|
|
method === Methods.POST
|
|
? "Création réussie !"
|
|
: "Mise à jour réussie !",
|
|
);
|
|
messages.descriptionSuccess = str(
|
|
useTrans(
|
|
method === Methods.POST
|
|
? "crud.messages.has_been_created"
|
|
: "crud.messages.has_been_updated",
|
|
{
|
|
params: {
|
|
model: useTrans(`models.classes.${modelName}`, {
|
|
choice: 1,
|
|
}),
|
|
},
|
|
},
|
|
),
|
|
)
|
|
.ucFirst()
|
|
.value();
|
|
messages.titleError = useTrans(
|
|
method === Methods.POST
|
|
? "Création annulée !"
|
|
: "Mise à jour annulée !",
|
|
);
|
|
messages.descriptionError = str(
|
|
useTrans(
|
|
method === Methods.POST
|
|
? "crud.messages.cannot_be_created"
|
|
: "crud.messages.cannot_be_updated",
|
|
{
|
|
params: {
|
|
model: useTrans(`models.classes.${modelName}`, {
|
|
choice: 1,
|
|
}),
|
|
},
|
|
},
|
|
),
|
|
)
|
|
.ucFirst()
|
|
.value();
|
|
|
|
/** Global */
|
|
const { locale } = usePage().props.appEnv as AppEnv;
|
|
const userModel = (usePage().props.auth as AuthProp).user;
|
|
const enumUserRole = usePage().props.enumUserRole as LaravelEnum;
|
|
const enumDynamicPageStatus = usePage().props
|
|
.enumDynamicPageStatus as LaravelEnum;
|
|
const dynamicPageModels = usePage().props.dynamicPageModels as DynamicPageModel[];
|
|
const [selectedGroup, setSelectedGroup] = useState<string | null>(null);
|
|
|
|
const pageConfigModels = usePage().props
|
|
.pageConfigModels as Array<PageConfigModel>;
|
|
// Models filtered based on the presence of the locale.
|
|
const filteredPageConfigModels = pageConfigModels.filter(
|
|
(model) =>
|
|
model.label?.[locale] !== undefined &&
|
|
model.config?.[locale] !== undefined,
|
|
);
|
|
|
|
// Set empty config by default.
|
|
const defaultConfigId = 0;
|
|
const configOptions = [
|
|
{
|
|
id: defaultConfigId,
|
|
label: {},
|
|
config: {},
|
|
policies: {
|
|
view: true,
|
|
update: true,
|
|
duplicate: true,
|
|
delete: true,
|
|
},
|
|
view: null,
|
|
created_at: new Date(),
|
|
updated_at: new Date(),
|
|
deleted_at: new Date(),
|
|
} as PageConfigModel,
|
|
...filteredPageConfigModels,
|
|
];
|
|
configOptions[defaultConfigId].label[locale] = useTrans(
|
|
"back.config_none_selected",
|
|
);
|
|
|
|
// Set translations.
|
|
const contentAssociateToModel = str(
|
|
useTrans("back.form_associate_to", {
|
|
params: { attribute: useTrans("validation.attributes.content") },
|
|
choice: 1,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value();
|
|
const modalTitle = useTrans("back.config_modal_title");
|
|
const modalDescription = useTrans("back.config_modal_descripion");
|
|
const modalClose = useTrans("back.close");
|
|
const anchorAccessConfig = useTrans("back.access_model", {
|
|
params: {
|
|
model: useTrans("models.classes.page-config", { choice: 1 }),
|
|
},
|
|
});
|
|
const getConfig = (id: number) =>
|
|
configOptions.find((objet) => objet.id == id)?.config[
|
|
locale
|
|
] as ConfigField[];
|
|
const { toast } = useToast();
|
|
|
|
/** Form section */
|
|
const { post, setData, data, reset } = useForm({
|
|
_method: method === Methods.POST ? "post" : "put",
|
|
title: model?.title ? model?.title[locale] : "",
|
|
slug: model?.slug ? model?.slug[locale] : "",
|
|
content: model?.content ? model?.content[locale] : "",
|
|
page_id: model?.page_id ?? null,
|
|
config_id: model?.config_id ?? configOptions[defaultConfigId].id,
|
|
status: model?.status ?? enumDynamicPageStatus.draft.value,
|
|
isLocked: model?.isLocked ?? false,
|
|
});
|
|
|
|
const submit = (e: FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
const routeUrl = route(`back.${modelRoute}.${action}`, model?.id);
|
|
if (method !== Methods.PATCH && method !== Methods.POST)
|
|
throw new Error("The method must be post or patch");
|
|
post(routeUrl, {
|
|
preserveScroll: true,
|
|
onSuccess: () => {
|
|
toast({
|
|
title: messages.titleSuccess,
|
|
description: messages.descriptionSuccess,
|
|
});
|
|
},
|
|
onError: () => {
|
|
toast({
|
|
variant: "destructive",
|
|
title: messages.titleError,
|
|
description: messages.descriptionError,
|
|
});
|
|
},
|
|
});
|
|
};
|
|
|
|
function getFullSlugPath(
|
|
models: DynamicPageModel[],
|
|
selectedGroup: string | null,
|
|
locale: string = "fr",
|
|
): string | null {
|
|
if (!selectedGroup) return null;
|
|
|
|
// Trouver le modèle sélectionné à partir de son title
|
|
const current = models.find(
|
|
(m) =>
|
|
m.title[locale]?.toLowerCase() === selectedGroup.toLowerCase(),
|
|
);
|
|
|
|
if (!current) return null;
|
|
|
|
// Fonction récursive pour reconstruire le chemin
|
|
const buildPath = (model: DynamicPageModel): string => {
|
|
const parent = model.page_id
|
|
? models.find((m) => m.id === model.page_id)
|
|
: null;
|
|
|
|
const currentTranslatedModelSlug = model.slug[locale] ?? "";
|
|
|
|
if (!parent) return currentTranslatedModelSlug;
|
|
|
|
return [buildPath(parent), currentTranslatedModelSlug].filter(Boolean).join("/");
|
|
};
|
|
|
|
return buildPath(current);
|
|
}
|
|
|
|
useEffect(() => {
|
|
const modelTitleValue = model?.title ? model?.title[locale] : "";
|
|
setData("title", modelTitleValue);
|
|
setData(
|
|
"slug",
|
|
model?.slug
|
|
? model?.slug[locale]
|
|
: str(modelTitleValue).slug().value(),
|
|
);
|
|
setData("content", model?.content ? model?.content[locale] : "");
|
|
setData(
|
|
"config_id",
|
|
model?.config_id ?? configOptions[defaultConfigId].id,
|
|
);
|
|
setData("status", model?.status ?? enumDynamicPageStatus.draft.value);
|
|
setData("isLocked", model?.isLocked ?? false);
|
|
}, [locale]);
|
|
|
|
return (
|
|
<form onSubmit={submit}>
|
|
<InputError all />
|
|
<FieldsetWrapper
|
|
title={useTrans("back.form_title_global")}
|
|
icon={<BookTextIcon className="mr-1" />}
|
|
description={useTrans("back.form_subtitle_global")}
|
|
className="sm:grid-cols-2 gap-4"
|
|
>
|
|
<SimpleString
|
|
name="title"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans(
|
|
"validation.attributes.title",
|
|
),
|
|
},
|
|
choice: 1,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value()}
|
|
value={data.title}
|
|
setData={setData}
|
|
/>
|
|
<EnumSelect
|
|
name="status"
|
|
options={enumDynamicPageStatus}
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans("validation.custom.status"),
|
|
},
|
|
choice: 1,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value()}
|
|
placeholder={`ex: ${enumDynamicPageStatus.draft.label}`}
|
|
selected={String(data.status)}
|
|
setData={setData}
|
|
/>
|
|
<ModelSelect
|
|
name="page_id"
|
|
options={dynamicPageModels}
|
|
field="title"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans("validation.custom.parent_page"),
|
|
},
|
|
choice: 2,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value()}
|
|
placeholder="ex: "
|
|
selected={data.page_id}
|
|
required={false}
|
|
setData={setData}
|
|
onSelectValue={(value) => setSelectedGroup(value)}
|
|
/>
|
|
<div className="flex items-end gap-1">
|
|
<SimpleString
|
|
name="slug"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans("validation.custom.slug"),
|
|
},
|
|
choice: 1,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value()}
|
|
wordCounter={false}
|
|
value={data.slug}
|
|
pattern="[a-z0-9\-]{3,255}"
|
|
setData={setData}
|
|
/>
|
|
<BtnOptionnalLinkWithTooltip
|
|
content={<GavelIcon className="w-4 h-4 m-auto" />}
|
|
tooltipContent={str(useTrans('back.slugify')).ucFirst().value()}
|
|
type="button"
|
|
variant="secondary"
|
|
onClick={() => {
|
|
setData("slug", str(data.title).slug().value());
|
|
}}
|
|
/>
|
|
</div>
|
|
<div className="col-span-1 md:col-span-2">
|
|
<GoToFrontView
|
|
model={model}
|
|
modelName="dynamic-page"
|
|
pathField={data.slug}
|
|
additionalGroupPath={getFullSlugPath(dynamicPageModels, selectedGroup, locale) ?? undefined}
|
|
isAvailable={model?.status === enumDynamicPageStatus.published.value}
|
|
/>
|
|
</div>
|
|
</FieldsetWrapper>
|
|
<FieldsetWrapper
|
|
title={useTrans("back.form_title_page")}
|
|
icon={<CogIcon className="mr-1" />}
|
|
description={useTrans("back.form_subtitle_page")}
|
|
className="gap-4"
|
|
>
|
|
<div className="grid sm:grid-cols-2 gap-4 border-b border-input pb-4">
|
|
<div className="flex justify-start items-end gap-1.5">
|
|
<ModelSelect
|
|
name="config_id"
|
|
options={configOptions}
|
|
field="label"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans(
|
|
"validation.custom.config",
|
|
),
|
|
},
|
|
choice: 2,
|
|
}),
|
|
)
|
|
.ucFirst()
|
|
.value()}
|
|
placeholder={"ex: "}
|
|
selected={data.config_id}
|
|
setData={setData}
|
|
/>
|
|
{userModel.role === enumUserRole.conceptor.value &&
|
|
Number(data.config_id) !== defaultConfigId && (
|
|
<Dialog>
|
|
<DialogTrigger asChild>
|
|
<Button
|
|
variant="secondary"
|
|
type="button"
|
|
size="icon"
|
|
>
|
|
<EyeIcon />
|
|
</Button>
|
|
</DialogTrigger>
|
|
<DialogContent className="max-w-4xl w-full max-h-[100vh]">
|
|
<DialogHeader>
|
|
<DialogTitle>
|
|
{modalTitle}
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
{modalDescription}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="max-h-[25rem] overflow-y-auto">
|
|
<ConfigTable
|
|
config={getConfig(
|
|
Number(data.config_id),
|
|
)}
|
|
/>
|
|
</div>
|
|
<DialogFooter>
|
|
<BtnOptionnalLinkWithTooltip
|
|
link={route(
|
|
"back.page-configs.show",
|
|
data.config_id,
|
|
)}
|
|
content={<CogIcon />}
|
|
tooltipContent={
|
|
anchorAccessConfig
|
|
}
|
|
variant="secondary"
|
|
/>
|
|
<DialogClose asChild>
|
|
<Button variant="secondary">
|
|
{modalClose}
|
|
</Button>
|
|
</DialogClose>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)}
|
|
</div>
|
|
</div>
|
|
{Number(data.config_id) === defaultConfigId ? (
|
|
<SimpleWysiwyg
|
|
name="content"
|
|
model="DynamicPage"
|
|
label={contentAssociateToModel}
|
|
value={String(
|
|
typeof data.content === "string"
|
|
? data.content
|
|
: "",
|
|
)}
|
|
setData={setData}
|
|
/>
|
|
) : (
|
|
<DynamicInputs
|
|
name="content"
|
|
config={getConfig(Number(data.config_id))}
|
|
content={
|
|
typeof data.content === "object" ? data.content : null
|
|
}
|
|
setData={setData}
|
|
// @ts-ignore
|
|
reset={reset}
|
|
/>
|
|
)}
|
|
</FieldsetWrapper>
|
|
{userModel.role === enumUserRole.conceptor.value && (
|
|
<FieldsetWrapper
|
|
className="gap-4"
|
|
title={useTrans("back.form_title_isLocked")}
|
|
icon={<ShieldAlertIcon className="mr-1" />}
|
|
description={useTrans("back.form_subtitle_isLocked")}
|
|
inline
|
|
>
|
|
<SimpleSwitch
|
|
name="isLocked"
|
|
checked={data.isLocked}
|
|
setData={setData}
|
|
/>
|
|
</FieldsetWrapper>
|
|
)}
|
|
<div className="text-center">
|
|
<BtnOptionnalLinkWithTooltip
|
|
content={str(useTrans("crud.actions.save"))
|
|
.ucFirst()
|
|
.value()}
|
|
tooltipContent={useTrans("crud.helpers.save_model", {
|
|
params: {
|
|
model: useTrans("models.classes.dynamic-page", {
|
|
choice: 1,
|
|
}),
|
|
},
|
|
})}
|
|
type="submit"
|
|
size="default"
|
|
/>
|
|
</div>
|
|
</form>
|
|
);
|
|
}
|