298 lines
12 KiB
TypeScript
298 lines
12 KiB
TypeScript
// * Packages
|
|
import { useForm, usePage } from "@inertiajs/react";
|
|
import { BookTextIcon, CogIcon } from "lucide-react";
|
|
import { route } from "ziggy-js";
|
|
import { useEffect, useState } from "react";
|
|
// * Components shadcn
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
} from "@/components/ui/dialog";
|
|
// * Other
|
|
import PageConfigDynamicFields from "@/back/Components/PageConfigs/DynamicFields";
|
|
import ExportConfigJson from "@/back/Components/PageConfigs/ExportConfigJson";
|
|
import ImportConfigJson from "@/back/Components/PageConfigs/ImportConfigJson";
|
|
import SimpleString from "@/back/Components/Inputs/SimpleString";
|
|
import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
|
|
import useTrans from "@/hooks/use-translations";
|
|
import str from "@/hooks/use-string";
|
|
import InputError from "@/back/Components/InputError";
|
|
import { Methods } from "@/lib/enums";
|
|
import { AppEnv, AuthProp, ConfigField, LaravelEnum, PageConfigModel } from "@/back/types/global";
|
|
import SubmitButton from "@/back/Components/SubmitButton";
|
|
import { useCrudSubmit } from "@/hooks/use-crud-submit";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
export default function Form({
|
|
model,
|
|
modelName,
|
|
modelRoute,
|
|
action,
|
|
method,
|
|
}: {
|
|
model?: PageConfigModel;
|
|
modelName: string;
|
|
modelRoute: string;
|
|
action: string;
|
|
method: number;
|
|
}) {
|
|
const { appEnv, auth, enumUserRole } = usePage().props as unknown as {
|
|
appEnv: AppEnv;
|
|
auth: AuthProp;
|
|
enumUserRole: LaravelEnum;
|
|
};
|
|
|
|
// Hack to actualize states.
|
|
const [resetState, setResetState] = useState<number>(1);
|
|
|
|
/** Get configs in others locales */
|
|
const [selectedConfig, setSelectedConfig] = useState<string | null>(null);
|
|
const otherConfigs = Object.entries(model!.config ?? {}).filter(([configLocale]) => configLocale !== appEnv.locale);
|
|
|
|
// Translations.
|
|
const transSelectConfigLocale = useTrans('back.config_select_fields');
|
|
const transDialogTitle = useTrans("back.are_you_sure");
|
|
const transDialogParagraph = useTrans("back.config_save_warning", { params: { locale: str(appEnv.locale).upperCase().value() } });
|
|
const transDialogParagraphList = useTrans("back.config_save_warning_list", {
|
|
params: { models: useTrans('models.classes.dynamic-page', { choice: 2 }) },
|
|
choice: 2,
|
|
});
|
|
const transDialogCancel = useTrans("back.no_cancel");
|
|
const transDialogSave = useTrans("back.yes_update");
|
|
|
|
/** Form section */
|
|
const { post, setData, data } = useForm({
|
|
_method: method === Methods.POST ? 'post' : 'put',
|
|
label: model?.label ? model?.label[appEnv.locale] : "",
|
|
view: model?.view,
|
|
config: model?.config ? model?.config[appEnv.locale] ?? [] : [],
|
|
});
|
|
|
|
const submit = useCrudSubmit({
|
|
method,
|
|
modelRoute,
|
|
modelName,
|
|
action,
|
|
model,
|
|
post
|
|
});
|
|
|
|
const resetConfig = (localeData: string) => {
|
|
const customLocaleData = str(localeData).lowerCase().value()
|
|
setData("config", model?.config ? model?.config[customLocaleData] ?? [] : []);
|
|
}
|
|
|
|
/**
|
|
* Check if auth user must be notified when the config is updated.
|
|
* @return boolean
|
|
*/
|
|
const mustBeNotified = () => {
|
|
return !route().current(`back.page-configs.create`)
|
|
&& model?.pages
|
|
&& model?.pages.length
|
|
&& data.config !== model?.config[appEnv.locale]
|
|
};
|
|
|
|
useEffect(() => {
|
|
setData("label", model?.label ? model?.label[appEnv.locale] : "");
|
|
setData("view", model?.view ?? null);
|
|
resetConfig(appEnv.locale);
|
|
setSelectedConfig(null);
|
|
}, [appEnv.locale]);
|
|
|
|
useEffect(() => {
|
|
const isEmpty = data.config === null || (typeof data.config === "object" && Object.keys(data.config).length === 0);
|
|
|
|
if (isEmpty && selectedConfig !== null) {
|
|
setSelectedConfig(null);
|
|
}
|
|
}, [data.config]);
|
|
|
|
useEffect(() => {
|
|
if (selectedConfig !== null) {
|
|
const lowerSelectedLocale = str(selectedConfig ?? "FR").slug().lowerCase().value();
|
|
setData('config', model?.config[lowerSelectedLocale] ?? []);
|
|
}
|
|
}, [selectedConfig]);
|
|
|
|
return (
|
|
<form id="config-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="label"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans("validation.custom.label"),
|
|
},
|
|
choice: 1,
|
|
}),
|
|
).ucFirst().value()}
|
|
placeholder="ex: John Doe"
|
|
value={data.label}
|
|
setData={setData}
|
|
/>
|
|
<SimpleString
|
|
name="view"
|
|
label={str(
|
|
useTrans("back.form_associate_to", {
|
|
params: {
|
|
attribute: useTrans("validation.custom.view"),
|
|
},
|
|
choice: 2,
|
|
}),
|
|
).ucFirst().value()}
|
|
placeholder="ex: John Doe"
|
|
required={false}
|
|
value={data.view ?? ""}
|
|
setData={setData}
|
|
/>
|
|
</FieldsetWrapper>
|
|
<FieldsetWrapper
|
|
title={useTrans("back.form_title_config")}
|
|
icon={<CogIcon className="mr-1" />}
|
|
description={useTrans("back.form_subtitle_config")}
|
|
>
|
|
{/* Import configuration from json file. */}
|
|
{auth.user.role === enumUserRole.conceptor.value && (
|
|
<div className={cn('mb-3', { 'border-b pb-6 mb-6': !route().current('back.page-configs.edit') })}>
|
|
<ImportConfigJson
|
|
onConfirm={(value, overwrite) => {
|
|
const newConfig = (!overwrite) ? [...data.config, ...value] : value;
|
|
setData('config', newConfig as ConfigField[])
|
|
setResetState(prev => prev + 1)
|
|
}}
|
|
/>
|
|
</div>
|
|
)}
|
|
{/* Show only on editing page. */}
|
|
{route().current('back.page-configs.edit') && (
|
|
<div className="flex justify-center items-center border-b pb-6 mb-6 gap-1.5">
|
|
{/* Select config from another locale */}
|
|
<Select
|
|
onValueChange={(value) => {
|
|
setSelectedConfig(value);
|
|
resetConfig(value);
|
|
}}
|
|
disabled={!otherConfigs.length}
|
|
>
|
|
<SelectTrigger className="text-muted-foreground w-full">
|
|
<SelectValue placeholder={transSelectConfigLocale} />
|
|
</SelectTrigger>
|
|
<SelectContent
|
|
position="popper"
|
|
className="w-[var(--radix-select-trigger-width)]"
|
|
>
|
|
{otherConfigs.map(([configLocale, config]) => {
|
|
configLocale = str(configLocale).upperCase().value();
|
|
const localeFields = Object.values(config).map(field => field.label).join(", ");
|
|
return (
|
|
<SelectItem
|
|
key={configLocale}
|
|
value={configLocale}
|
|
className="truncate"
|
|
title={`${configLocale}: ${localeFields}`}
|
|
>
|
|
<b>{configLocale}:</b> {localeFields}
|
|
</SelectItem>
|
|
);
|
|
})}
|
|
</SelectContent>
|
|
</Select>
|
|
{/* Button to export config */}
|
|
{auth.user.role === enumUserRole.conceptor.value && (
|
|
<ExportConfigJson
|
|
data={data.config ?? []}
|
|
filename={`${str(data.label ?? "configuration").slug().value()}.json`}
|
|
tooltipContent={useTrans('back.json_editor.export_tooltip')}
|
|
disabled={!data.config.length}
|
|
/>
|
|
)}
|
|
</div>
|
|
)}
|
|
<PageConfigDynamicFields
|
|
key={resetState}
|
|
name="config"
|
|
value={data.config}
|
|
setData={setData}
|
|
selectedConfig={selectedConfig}
|
|
/>
|
|
</FieldsetWrapper>
|
|
<div className="text-center">
|
|
{mustBeNotified() ? (
|
|
<Dialog>
|
|
<DialogTrigger asChild>
|
|
<div className="w-fit mx-auto">
|
|
<SubmitButton
|
|
isInDialog={true}
|
|
modelTrans={
|
|
useTrans(`models.classes.${modelName}`, {
|
|
choice: 1,
|
|
})
|
|
} />
|
|
</div>
|
|
</DialogTrigger>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{transDialogTitle}</DialogTitle>
|
|
<DialogDescription asChild>
|
|
<div className="flex flex-col gap-y-1.5">
|
|
<p>{transDialogParagraph}</p>
|
|
<p>{transDialogParagraphList}</p>
|
|
<div className="max-h-[20rem] overflow-y-auto">
|
|
<ul className="list-disc pl-6 space-y-1">
|
|
{model?.pages.map((page, pageIndex) =>
|
|
<li key={pageIndex}>
|
|
{page.title[appEnv.locale] ?? page.title[appEnv.fallbackLocale]}
|
|
</li>
|
|
)}
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<DialogFooter className="items-center sm:justify-start">
|
|
<DialogClose asChild>
|
|
<Button variant="secondary" type="button">
|
|
{transDialogCancel}
|
|
</Button>
|
|
</DialogClose>
|
|
<DialogClose asChild>
|
|
<Button form="config-form" type="submit">
|
|
{transDialogSave}
|
|
</Button>
|
|
</DialogClose>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
) : (
|
|
<SubmitButton modelTrans={
|
|
useTrans(`models.classes.${modelName}`, {
|
|
choice: 1,
|
|
})
|
|
} />
|
|
)}
|
|
</div>
|
|
</form>
|
|
);
|
|
}
|