From c31e55560b3e2fe30206bdd901b8999e63d536ce Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 16 Dec 2025 16:11:14 +0100 Subject: [PATCH] feat: :sparkles: add json export/import feature for page configuration --- app/Enums/Contact/ContactFormType.php | 7 +- lang/en/back.php | 36 +++ lang/fr/back.php | 36 +++ package-lock.json | 26 ++ package.json | 1 + resources/sass/back/app.scss | 17 + .../Components/Inputs/CompleteInputFile.tsx | 2 +- .../PageConfigs/ExportConfigJson.tsx | 56 ++++ .../PageConfigs/ImportConfigJson.tsx | 295 ++++++++++++++++++ resources/ts/back/Pages/PageConfigs/Form.tsx | 59 +++- 10 files changed, 519 insertions(+), 16 deletions(-) create mode 100644 resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx create mode 100644 resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx diff --git a/app/Enums/Contact/ContactFormType.php b/app/Enums/Contact/ContactFormType.php index 057fab4a..820e15ce 100644 --- a/app/Enums/Contact/ContactFormType.php +++ b/app/Enums/Contact/ContactFormType.php @@ -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, }; } diff --git a/lang/en/back.php b/lang/en/back.php index 03924be2..ec5cbc87 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -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" diff --git a/lang/fr/back.php b/lang/fr/back.php index 1d3c0a2c..b4d0080e 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -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", diff --git a/package-lock.json b/package-lock.json index e93bc38a..0099a46f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index fcea7f87..cbf74a2b 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/resources/sass/back/app.scss b/resources/sass/back/app.scss index 262daffc..821f00f1 100644 --- a/resources/sass/back/app.scss +++ b/resources/sass/back/app.scss @@ -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; +} \ No newline at end of file diff --git a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx index 88ae7a77..03334618 100644 --- a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx +++ b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx @@ -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; diff --git a/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx b/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx new file mode 100644 index 00000000..baa09f1d --- /dev/null +++ b/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx @@ -0,0 +1,56 @@ +// * Packages +import { FileDownIcon } from "lucide-react"; +// * Other +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; + +type ExportConfigJsonProps = { + // 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({ + data, + filename = "config.json", + tooltipContent, + disabled = false, +}: ExportConfigJsonProps) { + 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 ( + } + tooltipContent={tooltipContent} + type="button" + variant="outline" + size="icon" + disabled={disabled} + onClick={handleExport} + /> + ); +} diff --git a/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx b/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx new file mode 100644 index 00000000..abc4df2b --- /dev/null +++ b/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx @@ -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({}); + + // Modale state. + const [isOpen, setIsOpen] = useState(false); + // Event state. + const [isDragging, setIsDragging] = useState(false); + + // Local errors. + const [globalErrors, setGlobalErrors] = useState>({}); + const [editorErrors, setEditorErrors] = useState>({}); + + // Input file reference. + const inputRef = useRef(null); + + // Maximum file size accepted (2MB). + const maxSize = 2 * 1024 * 1024; + + // JSON valide: string | number | boolean | null | array | object + const jsonValueSchema: z.ZodType = 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: , + edit: , + delete: , + copy: , + ok: , + cancel: , + chevron: , + }; + + // 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 + */ + const processFile = async (file: File): Promise => { + 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): void => { + const file = e.target.files?.[0]; + if (file) processFile(file); + }; + + /** + * Action when droping file. + * + * @param event + * @return void + */ + const handleDrop = (event: React.DragEvent): 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 */} + + + {/* Modal */} + + + + {getTranslation('back.json_editor.modal_title')} + + {getTranslation('back.json_editor.modal_description')} + + +
+ {/* JSON editor */} + setJsonText(val as JsonValue)} + icons={icons} + translations={translations} + showIconTooltips={true} + collapseAnimationTime={200} + maxWidth="100%" + searchFilter="all" + /> +
+ + + + + +
+
+ + ); +} diff --git a/resources/ts/back/Pages/PageConfigs/Form.tsx b/resources/ts/back/Pages/PageConfigs/Form.tsx index 6be02990..47195d6f 100644 --- a/resources/ts/back/Pages/PageConfigs/Form.tsx +++ b/resources/ts/back/Pages/PageConfigs/Form.tsx @@ -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(1); /** Get configs in others locales */ const [selectedConfig, setSelectedConfig] = useState(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={} description={useTrans("back.form_subtitle_config")} > - {otherConfigs.length >= 1 && !selectedConfig && ( -
+ {/* Show only on editing page. */} + {route().current('back.page-configs.edit') && ( +
+ {/* Select config from another locale */} + {/* Button to export config */} + {auth.user.role === enumUserRole.conceptor.value && ( + + )} +
+ )} + {/* Show only on creating page. */} + {auth.user.role === enumUserRole.conceptor.value && route().current('back.page-configs.create') && ( +
+ { + setData('config', value as ConfigField[]) + setResetState(prev => prev + 1) + }} + />
)} {model?.pages.map((page, pageIndex) =>
  • - {page.title[locale] ?? page.title[fallbackLocale]} + {page.title[appEnv.locale] ?? page.title[appEnv.fallbackLocale]}
  • )}