diff --git a/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx b/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx index 65cd784c..42b7afc8 100644 --- a/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx +++ b/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx @@ -7,19 +7,20 @@ import { Button, buttonVariants } from "@/components/ui/button" import useTrans from "@/hooks/use-translations" import { ConfigInternalField, DynamicInternalField } from "@/back/types/global"; -type ButtonVariant = VariantProps["variant"]; +type AddNewFieldBtnProps = { + array: ConfigInternalField[] | DynamicInternalField[] | undefined, + variant?: VariantProps["variant"], + limitMax?: number | undefined; + onClick: () => void, +} +// Get a button with some informations. export default function AddNewFieldBtn({ array = [], variant = "default", limitMax, onClick, -}: { - array: ConfigInternalField[] | DynamicInternalField[] | undefined, - variant?: ButtonVariant, - limitMax?: number | undefined; - onClick: () => void, -}) { +}: AddNewFieldBtnProps) { // Translations. const transNoMoreChildren = useTrans('back.no_more_children') const transNewField = useTrans("back.new_field"); @@ -33,6 +34,7 @@ export default function AddNewFieldBtn({ return (
+ {/* Check if the limit is achieved */} {limitMax && array.length >= limitMax ? (

{transNoMoreChildren}

) : ( @@ -45,6 +47,7 @@ export default function AddNewFieldBtn({ {transNewField} )} + {/* Indicate the current number of elements. */}

{(array?.length ?? 0) > 0 ? transEntriesCount : transEmptyWarning}

diff --git a/resources/ts/back/Components/PageConfigs/ConfigTable.tsx b/resources/ts/back/Components/PageConfigs/ConfigTable.tsx index d758fbe1..0dd01f63 100644 --- a/resources/ts/back/Components/PageConfigs/ConfigTable.tsx +++ b/resources/ts/back/Components/PageConfigs/ConfigTable.tsx @@ -21,11 +21,18 @@ type ConfigTableProps = { }; export default function ConfigTable({ config }: ConfigTableProps) { + // Enums. const enumDynamicFieldTypes = usePage().props .enumDynamicFieldTypes as DynamicFieldTypes; const getEnumDynamicFieldType = (value: number) => { return Object.values(enumDynamicFieldTypes).find((def) => def.value === value); }; + // Translations. + const transType = str(useTrans("validation.custom.type")).ucFirst().value(); + const transLabel = str(useTrans("validation.custom.label")).ucFirst().value() + const transValidation = str(useTrans("validation.custom.validation")).ucFirst().value(); + + // Recursive component. const GetChildrenRow = (fields: ConfigField[], depth: number = 0): ReactNode => { return Object.entries(fields).map( ([id, field]) => ( @@ -59,13 +66,13 @@ export default function ConfigTable({ config }: ConfigTableProps) { - {str(useTrans("validation.custom.type")).ucFirst().value()} + {transType} - {str(useTrans("validation.custom.label")).ucFirst().value()} + {transLabel} - {str(useTrans("validation.custom.validation")).ucFirst().value()} + {transValidation} diff --git a/resources/ts/back/Components/PageConfigs/DynamicFields.tsx b/resources/ts/back/Components/PageConfigs/DynamicFields.tsx index a8d437df..5baceb1e 100644 --- a/resources/ts/back/Components/PageConfigs/DynamicFields.tsx +++ b/resources/ts/back/Components/PageConfigs/DynamicFields.tsx @@ -40,10 +40,18 @@ export default function DynamicFields({ disabled = false, setData, }: DynamicFieldsProps) { + // Errors. const { errors } = usePage().props; const [localErrors, setLocalErrors] = useState>(errors) + + // Enums. const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes + + // Accordion open index. const [openIndex, setOpenIndex] = useState(""); + + // Local changes of fields (avoid loop between useEffects). + const prevValueRef = useRef(JSON.stringify(value ?? [])); // Sensitive fields. var [originalConfigKeys, setOriginalConfigKeys] = useState([]); @@ -65,7 +73,6 @@ export default function DynamicFields({ ? addIdsRecursively(field.children, currentParentKey, currentId) : undefined; - // Si on a ajouté des enfants, il faut récupérer le dernier ID utilisé if (field.children?.length) { currentId += field.children.length; } @@ -77,8 +84,13 @@ export default function DynamicFields({ } const [fields, setFields] = useState(() => addIdsRecursively(value ?? [])); - // Local changes of fields (avoid loop between useEffects). - const prevValueRef = useRef(JSON.stringify(value ?? [])); + // Sorted fields by order. + const sortedFields = useMemo( + () => [...fields].sort((a, b) => (a.order ?? 1) - (b.order ?? 1)), + [fields], + ); + + // Drag & drop module for user interactions (mouse, touch, keyboard or other). const sensors = useSensors(useSensor(PointerSensor)); // Translations needed. @@ -94,6 +106,9 @@ export default function DynamicFields({ const transDelete = useTrans("back.delete_field"); const transDragAndDrop = useTrans("back.dnd_field"); + // Set the depth limit of each list elements. + const MAX_DEPTH = 10; + /** * Get a translation for a specific input from trans constant. * @param field string @@ -107,12 +122,6 @@ export default function DynamicFields({ .value(); }; - // Sorted fields by order. - const sortedFields = useMemo( - () => [...fields].sort((a, b) => (a.order ?? 1) - (b.order ?? 1)), - [fields], - ); - /** * Add a new field. * @returns void @@ -177,11 +186,15 @@ export default function DynamicFields({ const removeField = (fieldId: number): void => { const targetField = fields.filter((field) => field.id === fieldId)[0]; - updateSensitiveField(targetField.key); + removeSensitiveField(targetField.key); setFields((prev) => prev.filter((field) => field.id !== fieldId)); }; - const updateSensitiveField = (keyToRemove: string): void => { + /** + * Remove sensitive field list. + * @param keyToRemove string + */ + const removeSensitiveField = (keyToRemove: string): void => { setOriginalConfigKeys(prev => prev.filter((key) => key !== keyToRemove)); setLocalErrors({}); }; @@ -208,6 +221,11 @@ export default function DynamicFields({ }); }; + /** + * Remove all local ids. + * @param fields ConfigInternalField[] + * @returns + */ const removeIds = (fields: ConfigInternalField[]): ConfigField[] => { return fields.map(({ id, children, ...rest }) => ({ ...rest, @@ -262,18 +280,19 @@ export default function DynamicFields({ getTransInput={getTransInput} transDelete={transDelete} transDragAndDrop={transDragAndDrop} - updateSensitiveField={updateSensitiveField} + removeSensitiveField={removeSensitiveField} localErrors={localErrors} setLocalErrors={setLocalErrors} parentAccordionState={openIndex} setParentAccordionState={setOpenIndex} + limitMaxChildren={MAX_DEPTH} /> ))} )} - +
); diff --git a/resources/ts/back/Components/PageConfigs/FieldGroup.tsx b/resources/ts/back/Components/PageConfigs/FieldGroup.tsx index dfe8075e..dacf8fd7 100644 --- a/resources/ts/back/Components/PageConfigs/FieldGroup.tsx +++ b/resources/ts/back/Components/PageConfigs/FieldGroup.tsx @@ -51,11 +51,12 @@ type FieldGroupProps = { transDelete: string; transDragAndDrop?: string; sensitiveField: string[]; - updateSensitiveField: (key: string) => void; + removeSensitiveField: (key: string) => void; localErrors: Record; setLocalErrors: Dispatch>>; parentAccordionState: string; setParentAccordionState: (key: string) => void; + limitMaxChildren: number; } export default function FieldGroup({ @@ -72,19 +73,25 @@ export default function FieldGroup({ transDelete, transDragAndDrop, sensitiveField, - updateSensitiveField, + removeSensitiveField, localErrors, setLocalErrors, parentAccordionState, setParentAccordionState, + limitMaxChildren, }: FieldGroupProps) { - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; - const [openIndex, setOpenIndex] = useState(""); + // Drag & drop module for user interactions (mouse, touch, keyboard or other). + const sensors = useSensors(useSensor(PointerSensor)); - // === Sortable pour cet item (utile pour les enfants et pour les racines si parent a fourni context) - const sortableId = String(currentId); - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: sortableId }); + // Provides the necessary props and helpers to make this item draggable and reorderable. + // Includes event listeners, accessibility attributes, DOM ref, drag transform/transition values, + // and a flag indicating whether the item is dragging. + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: String(currentId) }); + // Style applied to the sortable item: + // - handles drag movement (transform), + // - animations (transition), + // - and visual feedback (opacity, zIndex) while dragging. const style = { transform: CSS.Transform.toString(transform), transition, @@ -92,48 +99,43 @@ export default function FieldGroup({ zIndex: isDragging ? 50 : 0, }; - // calcul de la partie enum (ex: "string_") à partir du type actuel + // Get all enum values, labels and names. + const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; + + // Set the current state of the accordion. + const [openIndex, setOpenIndex] = useState(""); + + // Get the current enum value. const currentEnum = Object.values(enumDynamicFieldTypes).find( (def) => def.value === currentField.type ); + // Set a prefix related to the current enum. const enumCurrentBase = `${currentEnum?.name}_`; + // Set the editable part of the current key. const [editableKey, setEditableKey] = useState(() => { return (currentField.key.startsWith(enumCurrentBase)) ? currentField.key.split(enumCurrentBase)[1] : currentField.key; }); - // completeKey : clé finale qui sera envoyée au backend. + // Set the complete key (prefix + editable) that will be sent to the backend. const completeKey = `${enumCurrentBase}${editableKey}`; + // Set the state of copying key. const [copied, setCopied] = useState(false); - const MAX_DEPTH = 10; - const depth = (currentFieldKey.match(/children/g) || []).length; - const canAddChild = depth < MAX_DEPTH; - - // Translations - const transNewField = useTrans("back.new_field"); - const transEmptyWarning = useTrans("back.empty_warning"); - const transEntriesCount = useTrans("back.entries_count", { - params: { - length: String(currentField.children?.length ?? 0), - }, - choice: (currentField.children?.length ?? 0) > 1 ? 2 : 1 - }); - - // copie dans le presse-papier - const copyToClipBoard = (data: string) => navigator.clipboard.writeText(data); + // Copy the complete key in the clipboard. const handleClick = () => { - copyToClipBoard(completeKey); + navigator.clipboard.writeText(completeKey); setCopied(true); setTimeout(() => setCopied(false), 2000); }; - // capteur DnD pour les sous-éléments (list items) - const sensors = useSensors(useSensor(PointerSensor)); - - // === gestion du réordonnancement des enfants (pour les sous-champs list) - const handleDragEnd = (event: DragEndEvent) => { + /** + * Reorder the elements list. + * @param event DragEndEvent + * @return void + */ + const handleOnDragEnd = (event: DragEndEvent) => { const { active, over } = event; if (!over || active.id === over.id) return; @@ -149,9 +151,11 @@ export default function FieldGroup({ updateField(currentId, { children: reordered }); }; - // === création d'un enfant : on génère une clé basée sur la clé complète du parent - const handleAddChild = () => { - // déterminer suffixe numérique pour le nouveau champ + /** + * Add a new field to the list. + * @return void + */ + const handleAddNewChild = () => { const existing = currentField.children ?? []; const maxOrder = Math.max(0, ...existing.map((field) => field.order ?? 0)) + 1; const maxIndex = Math.max(0, ...existing.map((field) => field.id ?? 0)) + 1; @@ -169,16 +173,26 @@ export default function FieldGroup({ updateField(currentId, { children: newChildren }); }; + /** + * Remove a specific element from the list. + * @param childId number + * @return void + */ const handleDeleteChild = (childId: number) => { const children = (currentField.children ?? []); const targetChild = children.filter((child) => child.id === childId)[0]; - updateSensitiveField(`${parentFieldKey}.${targetChild.key}`); + removeSensitiveField(`${parentFieldKey}.${targetChild.key}`); const childrenUpdated = children.filter( (c) => c.id !== childId ); updateField(currentId, { children: childrenUpdated }); }; + /** + * Update the input type. + * @param value string + * @return void + */ const updatingType = (value: string) => { const selectedType = Object.values(enumDynamicFieldTypes).find( (def) => def.value === parseInt(value) @@ -201,7 +215,7 @@ export default function FieldGroup({ "border-destructive/50 dark:border-destructive": parentAccordionState !== `item-${currentId}` && Object.keys(localErrors).some(key => key.startsWith(`${currentFieldKey}.${currentIndex}`)), })}> - {/* === HEADER === */} + {/* HEADER */}
@@ -257,7 +271,7 @@ export default function FieldGroup({
- {/* === CONTENT === */} + {/* CONTENT */}
- {/* === SOUS-CHAMPS (si type is array) === */} + {/* CHILDREN */} {currentEnum?.isarray && ( <> - {canAddChild ? ( - + - String(c.id))} + strategy={verticalListSortingStrategy} > - String(c.id))} - strategy={verticalListSortingStrategy} - > - {(currentField.children ?? []).map((child: ConfigInternalField, i: number) => ( - ) => { - const newChildren = (currentField.children ?? []).map((c) => - c.id === childId ? { ...c, ...updatedChild } : c - ); - updateField(currentId, { children: newChildren }); - }} - removeField={handleDeleteChild} - transDelete={transDelete} - transDragAndDrop={transDragAndDrop} - sensitiveField={sensitiveField} - updateSensitiveField={updateSensitiveField} - localErrors={localErrors} - setLocalErrors={setLocalErrors} - parentAccordionState={openIndex} - setParentAccordionState={setOpenIndex} - /> - ))} - - - - - ) : ( -

- Profondeur maximale atteinte ({MAX_DEPTH}) -

- )} + {(currentField.children ?? []).map((child: ConfigInternalField, i: number) => ( + ) => { + const newChildren = (currentField.children ?? []).map((c) => + c.id === childId ? { ...c, ...updatedChild } : c + ); + updateField(currentId, { children: newChildren }); + }} + removeField={handleDeleteChild} + transDelete={transDelete} + transDragAndDrop={transDragAndDrop} + sensitiveField={sensitiveField} + removeSensitiveField={removeSensitiveField} + localErrors={localErrors} + setLocalErrors={setLocalErrors} + parentAccordionState={openIndex} + setParentAccordionState={setOpenIndex} + limitMaxChildren={limitMaxChildren} + /> + ))} + + + + )}