fix: 🎨 clean & comment page configs components
This commit is contained in:
parent
c6b2e8482a
commit
ea3f40b3e3
4 changed files with 151 additions and 113 deletions
|
|
@ -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<typeof buttonVariants>["variant"];
|
||||
type AddNewFieldBtnProps = {
|
||||
array: ConfigInternalField[] | DynamicInternalField[] | undefined,
|
||||
variant?: VariantProps<typeof buttonVariants>["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 (
|
||||
<div className="flex flex-col lg:flex-row justify-center lg:justify-between items-center">
|
||||
{/* Check if the limit is achieved */}
|
||||
{limitMax && array.length >= limitMax ? (
|
||||
<p className="text-sm text-muted-foreground text-center">{transNoMoreChildren}</p>
|
||||
) : (
|
||||
|
|
@ -45,6 +47,7 @@ export default function AddNewFieldBtn({
|
|||
{transNewField}
|
||||
</Button>
|
||||
)}
|
||||
{/* Indicate the current number of elements. */}
|
||||
<p className="text-sm text-muted-foreground text-center my-2 xl:my-0">
|
||||
{(array?.length ?? 0) > 0 ? transEntriesCount : transEmptyWarning}
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -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) {
|
|||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>
|
||||
{str(useTrans("validation.custom.type")).ucFirst().value()}
|
||||
{transType}
|
||||
</TableHead>
|
||||
<TableHead>
|
||||
{str(useTrans("validation.custom.label")).ucFirst().value()}
|
||||
{transLabel}
|
||||
</TableHead>
|
||||
<TableHead>
|
||||
{str(useTrans("validation.custom.validation")).ucFirst().value()}
|
||||
{transValidation}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
|
|
|||
|
|
@ -40,10 +40,18 @@ export default function DynamicFields({
|
|||
disabled = false,
|
||||
setData,
|
||||
}: DynamicFieldsProps) {
|
||||
// Errors.
|
||||
const { errors } = usePage().props;
|
||||
const [localErrors, setLocalErrors] = useState<Record<string, string>>(errors)
|
||||
|
||||
// Enums.
|
||||
const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes
|
||||
|
||||
// Accordion open index.
|
||||
const [openIndex, setOpenIndex] = useState<string>("");
|
||||
|
||||
// Local changes of fields (avoid loop between useEffects).
|
||||
const prevValueRef = useRef(JSON.stringify(value ?? []));
|
||||
|
||||
// Sensitive fields.
|
||||
var [originalConfigKeys, setOriginalConfigKeys] = useState<string[]>([]);
|
||||
|
|
@ -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<ConfigInternalField[]>(() => 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}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</Accordion>
|
||||
)}
|
||||
<AddNewFieldBtn array={fields} onClick={addField} />
|
||||
<AddNewFieldBtn array={fields} limitMax={MAX_DEPTH} onClick={addField} />
|
||||
<InputError message={localErrors[name]} />
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -51,11 +51,12 @@ type FieldGroupProps = {
|
|||
transDelete: string;
|
||||
transDragAndDrop?: string;
|
||||
sensitiveField: string[];
|
||||
updateSensitiveField: (key: string) => void;
|
||||
removeSensitiveField: (key: string) => void;
|
||||
localErrors: Record<string, string>;
|
||||
setLocalErrors: Dispatch<SetStateAction<Record<string, string>>>;
|
||||
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<string>("");
|
||||
// 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<string>("");
|
||||
|
||||
// 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<string>(() => {
|
||||
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}`)),
|
||||
})}>
|
||||
<CardContent className="flex flex-col p-3">
|
||||
{/* === HEADER === */}
|
||||
{/* HEADER */}
|
||||
<div className="flex flex-col lg:flex-row-reverse gap-1.5">
|
||||
<div className="flex flex-row gap-1.5 w-full h-full">
|
||||
<div className="flex-grow flex items-stretch">
|
||||
|
|
@ -257,7 +271,7 @@ export default function FieldGroup({
|
|||
</AccordionTrigger>
|
||||
</div>
|
||||
</div>
|
||||
{/* === CONTENT === */}
|
||||
{/* CONTENT */}
|
||||
<AccordionContent className="p-0 px-1">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 pt-4">
|
||||
<SimpleString
|
||||
|
|
@ -320,63 +334,58 @@ export default function FieldGroup({
|
|||
parentErrors={localErrors}
|
||||
/>
|
||||
</div>
|
||||
{/* === SOUS-CHAMPS (si type is array) === */}
|
||||
{/* CHILDREN */}
|
||||
{currentEnum?.isarray && (
|
||||
<>
|
||||
{canAddChild ? (
|
||||
<Accordion
|
||||
type="single"
|
||||
className="w-full mt-4"
|
||||
value={openIndex}
|
||||
onValueChange={setOpenIndex}
|
||||
collapsible
|
||||
<Accordion
|
||||
type="single"
|
||||
className="w-full mt-4"
|
||||
value={openIndex}
|
||||
onValueChange={setOpenIndex}
|
||||
collapsible
|
||||
>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleOnDragEnd}
|
||||
>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
<SortableContext
|
||||
items={(currentField.children ?? []).map((c) => String(c.id))}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<SortableContext
|
||||
items={(currentField.children ?? []).map((c) => String(c.id))}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
{(currentField.children ?? []).map((child: ConfigInternalField, i: number) => (
|
||||
<FieldGroup
|
||||
key={child.id}
|
||||
currentId={child.id}
|
||||
currentIndex={i}
|
||||
currentFieldKey={`${currentFieldKey}.${currentIndex}.children`}
|
||||
parentFieldKey={`${parentFieldKey}.${currentField.key}`}
|
||||
currentField={child}
|
||||
currentRequired
|
||||
currentDisabled={false}
|
||||
getTransInput={getTransInput}
|
||||
updateField={(childId: number, updatedChild: Partial<ConfigField>) => {
|
||||
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}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
<AddNewFieldBtn array={currentField.children} variant="secondary" onClick={handleAddChild} />
|
||||
</Accordion>
|
||||
) : (
|
||||
<p className="text-destructive italic mt-2">
|
||||
Profondeur maximale atteinte ({MAX_DEPTH})
|
||||
</p>
|
||||
)}
|
||||
{(currentField.children ?? []).map((child: ConfigInternalField, i: number) => (
|
||||
<FieldGroup
|
||||
key={child.id}
|
||||
currentId={child.id}
|
||||
currentIndex={i}
|
||||
currentFieldKey={`${currentFieldKey}.${currentIndex}.children`}
|
||||
parentFieldKey={`${parentFieldKey}.${currentField.key}`}
|
||||
currentField={child}
|
||||
currentRequired
|
||||
currentDisabled={false}
|
||||
getTransInput={getTransInput}
|
||||
updateField={(childId: number, updatedChild: Partial<ConfigField>) => {
|
||||
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}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
<AddNewFieldBtn array={currentField.children} limitMax={limitMaxChildren} variant="secondary" onClick={handleAddNewChild} />
|
||||
</Accordion>
|
||||
</>
|
||||
)}
|
||||
</AccordionContent>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue