Merge branch 'json-feature' into 'develop'

feat: ✨ add json export/import feature for page configuration

See merge request ldc-web/projets/ldc!84
This commit is contained in:
karl.muller 2025-12-16 15:25:47 +00:00
commit 623e6db64e
10 changed files with 519 additions and 16 deletions

View file

@ -2,6 +2,7 @@
namespace App\Enums\Contact;
use App\Helpers\RouteHelper;
use Uwil\LaravelCommon\Traits\Enums\BaseEnum;
enum ContactFormType: int
@ -187,8 +188,10 @@ enum ContactFormType: int
return match (true) {
in_array($this, $commonRoutes, true) => route('front.contact.show', ['slug' => $this->slug()]),
$this === self::professional => null,
$this === self::press => route('front.dynamic-pages.espace-presse') . '#page-press-form',
$this === self::restauration => $locale === "fr" ? route('front.contact.show', ['slug' => $this->slug()]) : 'https://www.legauloisprofessionnel.fr/contactez-nous',
$this === self::press => RouteHelper::routeNameChecker('front.dynamic-pages.espace-presse') . '#page-press-form',
$this === self::restauration => $locale === "fr"
? RouteHelper::routeNameChecker('front.contact.show', ['slug' => $this->slug()])
: 'https://www.legauloisprofessionnel.fr/contactez-nous',
default => null,
};
}

View file

@ -202,6 +202,42 @@ return [
],
],
],
"json_editor" => [
"item_single" => "1 item",
"item_multiple" => "{{count}} items",
"key_new" => "New key",
"key_select" => "Select a key",
"no_key_options" => "No options available",
"error_key_exists" => "The key already exists",
"error_invalid_json" => "Invalid JSON",
"error_update" => "Unable to update",
"error_delete" => "Unable to delete",
"error_add" => "Unable to add",
"default_string" => "New value",
"default_new_key" => "Key",
"show_less" => "Show less",
"empty_string" => "Empty",
"delete" => "Delete",
"copy" => "Copy",
"edit" => "Edit",
"add" => "Add",
"modal_title" => "Edit JSON file",
"modal_description" => "Edit the JSON data before validation.",
"cancel" => "Cancel",
"validate" => "Validate",
"tooltip_cancel" => "Cancel import",
"tooltip_validate" => "Confirm import",
"export_tooltip" => "Export configuration as JSON file",
"select-file" => "Drag and drop a file or click to select one",
"allowed_format" => "Allowed format: :format",
"rules_weight" => "Max size: :size",
"validation" => [
"mimes" => "The file must be of type: :values.",
"max_size" => "The file must not exceed :value",
"invalid_file_json" => "Invalid JSON file or incorrect structure.",
"invalid_content_json" => "Invalid JSON content or incorrect structure.",
],
],
"news" => [
"categories" => [
"placeholder" => "select your article's categories"

View file

@ -203,6 +203,42 @@ return [
],
],
],
"json_editor" => [
"item_single" => "1 élément",
"item_multiple" => "{{count}} éléments",
"key_new" => "Nouvelle clé",
"key_select" => "Sélectionner une clé",
"no_key_options" => "Aucune option",
"error_key_exists" => "La clé existe déjà",
"error_invalid_json" => "JSON invalide",
"error_update" => "Impossible de mettre à jour",
"error_delete" => "Impossible de supprimer",
"error_add" => "Impossible d’ajouter",
"default_string" => "Nouvelle donnée",
"default_new_key" => "Clé",
"show_less" => "Réduire",
"empty_string" => "Vide",
"delete" => "Supprimer",
"copy" => "Copier",
"edit" => "Modifier",
"add" => "Ajouter",
"modal_title" => "Éditer un fichier JSON",
"modal_description" => "Modifier les données du JSON avant validation.",
"cancel" => "Annuler",
"validate" => "Valider",
"tooltip_cancel" => "Annuler l'importation",
"tooltip_validate" => "Valider l'importation",
"export_tooltip" => "Exporter la configuration sous forme de fichier JSON",
"select-file" => "Glisser-déposer un fichier ou cliquez pour en sélectionner un",
"allowed_format" => "Format autorisé: :format",
"rules_weight" => "Taille max: :size",
"validation" => [
"mimes" => "Le fichier doit être de type : :values.",
"max_size" => "Le fichier ne doit pas dépasser : :value",
"invalid_file_json" => "Fichier JSON invalide ou structure incorrecte.",
"invalid_content_json" => "Contenu JSON invalide ou structure incorrecte.",
],
],
"news" => [
"categories" => [
"placeholder" => "sélectionnez les catégories de votre article",

26
package-lock.json generated
View file

@ -25,6 +25,7 @@
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"json-edit-react": "^1.29.0",
"laravel-vite-plugin": "^1.3.0",
"lucide-react": "^0.503.0",
"motion": "^12.23.12",
@ -11132,6 +11133,19 @@
"dev": true,
"license": "MIT"
},
"node_modules/json-edit-react": {
"version": "1.29.0",
"resolved": "https://registry.npmjs.org/json-edit-react/-/json-edit-react-1.29.0.tgz",
"integrity": "sha512-qxho/m0w6GCaKLic6XsZgmCrKKwluMvoy92teRBRus1PRHJQiP4pkFQJ90lmrno1KNgSePYIG0mcscS0GjdH3A==",
"license": "MIT",
"dependencies": {
"object-property-assigner": "^1.3.5",
"object-property-extractor": "^1.0.13"
},
"peerDependencies": {
"react": ">=16.0.0"
}
},
"node_modules/json-parse-even-better-errors": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
@ -12700,6 +12714,18 @@
"node": ">= 0.4"
}
},
"node_modules/object-property-assigner": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/object-property-assigner/-/object-property-assigner-1.3.5.tgz",
"integrity": "sha512-DIzHzNSTnpoG8QPQCDNrHa6O3vLMhktK3Igirqpk523UYIVe8JNCKcn5C9WyLQxJc58EGsAIiiEu10gqPrud8w==",
"license": "MIT"
},
"node_modules/object-property-extractor": {
"version": "1.0.13",
"resolved": "https://registry.npmjs.org/object-property-extractor/-/object-property-extractor-1.0.13.tgz",
"integrity": "sha512-9kgEjTWDhTPuPn7nyof+5mLmCKBPKdU0c7IVpTbOvYKYSdXQ5skH4Pa/8MPbZXeyXBGrqS82JyWecsh6tMxiLw==",
"license": "MIT"
},
"node_modules/object.assign": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz",

View file

@ -82,6 +82,7 @@
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"json-edit-react": "^1.29.0",
"laravel-vite-plugin": "^1.3.0",
"lucide-react": "^0.503.0",
"motion": "^12.23.12",

View file

@ -210,3 +210,20 @@ html {
.table-of-contents-scroll::-webkit-scrollbar-thumb:hover {
background-color: hsl(var(--border) / 60%);
}
// JSON editor.
.jer-edit-buttons > div {
transition: 0.2s;
}
.jer-edit-buttons > div:hover {
opacity: 80%;
}
.jer-copy-pulse:hover {
transform: initial !important;
}
.jer-collection-item-count {
@apply cursor-pointer;
}

View file

@ -10,12 +10,12 @@ import { Button } from "@/components/ui/button";
// * Other
import InputError from "@/back/Components/InputError";
import ImageCropper from "@/back/Components/Inputs/ImageCropper";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import { useToast } from "@/hooks/use-toast";
import { AppEnv, DynamicFieldTypes, FileValidation } from "@/back/types/global";
import { cn } from "@/lib/utils";
import BtnOptionnalLinkWithTooltip from "../BtnOptionnalLinkWithTooltip";
type FileWithPreview = FileWithPath & {
preview: string;

View file

@ -0,0 +1,56 @@
// * Packages
import { FileDownIcon } from "lucide-react";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
type ExportConfigJsonProps<T> = {
// The data in string.
data: T;
// Name of the downloaded file.
filename?: string;
// String present in the tooltip.
tooltipContent: string;
// Disable the button or not.
disabled?: boolean;
};
export default function ExportConfigJson<T>({
data,
filename = "config.json",
tooltipContent,
disabled = false,
}: ExportConfigJsonProps<T>) {
const handleExport = () => {
try {
// Transform data into json structure.
const json = JSON.stringify(data, null);
// Create blob from the json.
const blob = new Blob([json], {
type: "application/json;charset=utf-8",
});
// Creates a link on the fly and opens it.
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error("Error during JSON export:", error);
}
};
return (
<BtnOptionnalLinkWithTooltip
content={<FileDownIcon className="w-4 h-4 m-auto" />}
tooltipContent={tooltipContent}
type="button"
variant="outline"
size="icon"
disabled={disabled}
onClick={handleExport}
/>
);
}

View file

@ -0,0 +1,295 @@
// * Packages
import { useRef, useState } from "react";
import { JsonEditor, IconReplacements, LocalisedStrings } from "json-edit-react";
import { CheckIcon, ChevronDownIcon, CopyIcon, PencilIcon, PlusIcon, Trash2Icon, UploadIcon, XIcon } from "lucide-react";
import z from "zod";
// * Components shadcn
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import { cn } from "@/lib/utils";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import InputError from "../InputError";
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
type ImportConfigJsonProps = {
onConfirm: (data: JsonValue) => void;
};
export default function ImportConfigJson({
onConfirm,
}: ImportConfigJsonProps) {
// Json content.
const [jsonText, setJsonText] = useState<JsonValue>({});
// Modale state.
const [isOpen, setIsOpen] = useState(false);
// Event state.
const [isDragging, setIsDragging] = useState(false);
// Local errors.
const [globalErrors, setGlobalErrors] = useState<Record<string, string>>({});
const [editorErrors, setEditorErrors] = useState<Record<string, string>>({});
// Input file reference.
const inputRef = useRef<HTMLInputElement>(null);
// Maximum file size accepted (2MB).
const maxSize = 2 * 1024 * 1024;
// JSON valide: string | number | boolean | null | array | object
const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(jsonValueSchema),
z.record(z.string(), jsonValueSchema),
])
);
/**
* Get translation of specific key.
*
* @param key string
* @return string
*/
const getTranslation = (key: string): string => str(useTrans(key)).ucFirst().value();
// Custom icons.
const icons: IconReplacements = {
add: <PlusIcon className="w-4 h-4" />,
edit: <PencilIcon className="w-4 h-4" />,
delete: <Trash2Icon className="w-4 h-4" />,
copy: <CopyIcon className="w-4 h-4" />,
ok: <CheckIcon className="w-4 h-4" />,
cancel: <XIcon className="w-4 h-4" />,
chevron: <ChevronDownIcon className="cursor-pointer w-4 h-4" />,
};
// Custom translations.
const translations: LocalisedStrings = {
ITEM_SINGLE: getTranslation('back.json_editor.item_single'),
ITEMS_MULTIPLE: getTranslation('back.json_editor.item_multiple'),
KEY_NEW: getTranslation('back.json_editor.key_new'),
KEY_SELECT: getTranslation('back.json_editor.key_select'),
NO_KEY_OPTIONS: getTranslation('back.json_editor.no_key_options'),
ERROR_KEY_EXISTS: getTranslation('back.json_editor.error_key_exists'),
ERROR_INVALID_JSON: getTranslation('back.json_editor.error_invalid_json'),
ERROR_UPDATE: getTranslation('back.json_editor.error_update'),
ERROR_DELETE: getTranslation('back.json_editor.error_delete'),
ERROR_ADD: getTranslation('back.json_editor.error_add'),
DEFAULT_STRING: getTranslation('back.json_editor.default_string'),
DEFAULT_NEW_KEY: getTranslation('back.json_editor.default_new_key'),
SHOW_LESS: getTranslation('back.json_editor.show_less'),
EMPTY_STRING: getTranslation('back.json_editor.empty_string'),
TOOLTIP_COPY: getTranslation('back.json_editor.copy'),
TOOLTIP_EDIT: getTranslation('back.json_editor.edit'),
TOOLTIP_DELETE: getTranslation('back.json_editor.delete'),
TOOLTIP_ADD: getTranslation('back.json_editor.add'),
};
/**
* Simulates click on input file.
*
* @return void
*/
const openFilePicker = (): void => {
inputRef.current?.click();
};
/**
* Set json from content file.
*
* @param file File
* @return Promise<void>
*/
const processFile = async (file: File): Promise<void> => {
if (file.size > maxSize) {
setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.max_size', {
params: { value: '2MB' }
}) }));
return;
}
if (!file.name.endsWith(".json")) {
setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.mimes', {
params: { values: '.json' }
}) }));
return;
}
try {
const text = await file.text();
const parsed = JSON.parse(text);
// Validate json with zod.
jsonValueSchema.parse(parsed);
setJsonText(parsed);
setGlobalErrors({});
setIsOpen(true);
} catch {
setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.invalid_file_json') }));
}
};
/**
* Action when changing file.
*
* @param event
* @return void
*/
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file) processFile(file);
};
/**
* Action when droping file.
*
* @param event
* @return void
*/
const handleDrop = (event: React.DragEvent<HTMLDivElement>): void => {
event.preventDefault();
setIsDragging(false);
const file = event.dataTransfer.files?.[0];
if (file) processFile(file);
};
/**
* Confirm the json.
*
* @return void
*/
const handleConfirm = (): void => {
try {
// Validate json with zod.
jsonValueSchema.parse(jsonText);
onConfirm(jsonText);
resetComponent();
} catch {
setEditorErrors(prev => ({ ...prev, 'editor-error': useTrans('back.json_editor.validation.invalid_content_json') }));
}
};
/**
* Reset component.
*
* @return void
*/
const resetComponent = (): void => {
setIsOpen(false);
setTimeout(() => {
setJsonText(null);
setGlobalErrors({});
setEditorErrors({});
}, 200);
}
return (
<>
{/* Dropzone */}
<Button
variant="ghost"
type="button"
className={cn(
"flex border border-dashed overflow-hidden whitespace-normal [&_svg]:!pointer-events-auto [&_svg]:!size-auto [&_svg]:!shrink text-muted-foreground w-full h-36",
{ "text-accent-foreground bg-accent": isDragging },
{ "border-destructive mb-1.5": Object.values(globalErrors).length }
)}
onClick={openFilePicker}
onDragOver={(e) => {
e.preventDefault();
setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
// @ts-ignore
onDrop={handleDrop}
>
<input
ref={inputRef}
type="file"
accept=".json,application/json"
className="hidden"
onChange={handleFileChange}
/>
<div className="flex flex-col justify-center items-center">
<UploadIcon />
<p className="text-center break-normal w-full mt-2">
{useTrans('back.json_editor.select-file')}
</p>
<small>
{str(
useTrans("back.json_editor.allowed_format", {
params: { format: ".json" },
})
).ucFirst().value()}
.{" "}
{str(
useTrans("back.json_editor.rules_weight", {
params: { size: "2MB" },
})
).ucFirst().value()}
</small>
</div>
</Button>
<InputError message={globalErrors["global-error"]} />
{/* Modal */}
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>{getTranslation('back.json_editor.modal_title')}</DialogTitle>
<DialogDescription>
{getTranslation('back.json_editor.modal_description')}
</DialogDescription>
</DialogHeader>
<div className="rounded-md w-full max-h-[350px] overflow-scroll">
{/* JSON editor */}
<JsonEditor
data={jsonText}
setData={(val) => setJsonText(val as JsonValue)}
icons={icons}
translations={translations}
showIconTooltips={true}
collapseAnimationTime={200}
maxWidth="100%"
searchFilter="all"
/>
</div>
<InputError message={editorErrors["editor-error"]} />
<DialogFooter>
<BtnOptionnalLinkWithTooltip
content={getTranslation('back.json_editor.cancel')}
tooltipContent={getTranslation('back.json_editor.tooltip_cancel')}
type="button"
variant="secondary"
size="default"
onClick={resetComponent}
/>
<BtnOptionnalLinkWithTooltip
content={getTranslation('back.json_editor.validate')}
tooltipContent={getTranslation('back.json_editor.tooltip_validate')}
type="button"
size="default"
onClick={handleConfirm}
/>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View file

@ -24,13 +24,15 @@ import {
} 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, PageConfigModel } from "@/back/types/global";
import { AppEnv, AuthProp, ConfigField, LaravelEnum, PageConfigModel } from "@/back/types/global";
import SubmitButton from "@/back/Components/SubmitButton";
import { useCrudSubmit } from "@/hooks/use-crud-submit";
@ -47,16 +49,23 @@ export default function Form({
action: string;
method: number;
}) {
const { locale, fallbackLocale } = usePage().props.appEnv as AppEnv;
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 !== locale);
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(locale).upperCase().value() } });
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,
@ -67,9 +76,9 @@ export default function Form({
/** Form section */
const { post, setData, data } = useForm({
_method: method === Methods.POST ? 'post' : 'put',
label: model?.label ? model?.label[locale] : "",
label: model?.label ? model?.label[appEnv.locale] : "",
view: model?.view,
config: model?.config ? model?.config[locale] ?? [] : [],
config: model?.config ? model?.config[appEnv.locale] ?? [] : [],
});
const submit = useCrudSubmit({
@ -94,15 +103,15 @@ export default function Form({
return !route().current(`back.page-configs.create`)
&& model?.pages
&& model?.pages.length
&& data.config !== model?.config[locale]
&& data.config !== model?.config[appEnv.locale]
};
useEffect(() => {
setData("label", model?.label ? model?.label[locale] : "");
setData("label", model?.label ? model?.label[appEnv.locale] : "");
setData("view", model?.view ?? null);
resetConfig(locale);
resetConfig(appEnv.locale);
setSelectedConfig(null);
}, [locale]);
}, [appEnv.locale]);
useEffect(() => {
const isEmpty = data.config === null || (typeof data.config === "object" && Object.keys(data.config).length === 0);
@ -163,13 +172,16 @@ export default function Form({
icon={<CogIcon className="mr-1" />}
description={useTrans("back.form_subtitle_config")}
>
{otherConfigs.length >= 1 && !selectedConfig && (
<div className="pb-6">
{/* 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} />
@ -194,9 +206,30 @@ export default function Form({
})}
</SelectContent>
</Select>
{/* Button to export config */}
{auth.user.role === enumUserRole.conceptor.value && (
<ExportConfigJson
data={data.config}
filename="page-config.json"
tooltipContent={useTrans('back.json_editor.export_tooltip')}
disabled={!data.config.length}
/>
)}
</div>
)}
{/* Show only on creating page. */}
{auth.user.role === enumUserRole.conceptor.value && route().current('back.page-configs.create') && (
<div className="border-b pb-6 mb-6">
<ImportConfigJson
onConfirm={(value) => {
setData('config', value as ConfigField[])
setResetState(prev => prev + 1)
}}
/>
</div>
)}
<PageConfigDynamicFields
key={resetState}
name="config"
value={data.config}
setData={setData}
@ -228,7 +261,7 @@ export default function Form({
<ul className="list-disc pl-6 space-y-1">
{model?.pages.map((page, pageIndex) =>
<li key={pageIndex}>
{page.title[locale] ?? page.title[fallbackLocale]}
{page.title[appEnv.locale] ?? page.title[appEnv.fallbackLocale]}
</li>
)}
</ul>