feat: ✨ add color picker to the dynamic inputs list

This commit is contained in:
Alexis Gousseau 2025-11-19 12:16:44 +01:00
parent 228ad99403
commit 2ac6bacf71
13 changed files with 2272 additions and 1580 deletions

View file

@ -22,7 +22,7 @@ enum DynamicFieldTypes: int
case vimeoId = 11;
case youtubeId = 12;
case date = 13;
case color = 14;
/**
* Labels definition.
@ -43,6 +43,7 @@ enum DynamicFieldTypes: int
self::vimeoId->name => 'enums.dynamic-field-types.vimeoId',
self::youtubeId->name => 'enums.dynamic-field-types.youtubeId',
self::date->name => 'enums.dynamic-field-types.date',
self::color->name => 'enums.dynamic-field-types.color',
];
/**
@ -59,9 +60,10 @@ enum DynamicFieldTypes: int
self::image->name => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120|dimensions:width=100,height=100',
self::list->name => 'required|array|min:1|max:10',
self::file->name => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120|dimensions:width=100,height=100',
self::vimeoId->name => 'nullable|string|min:8|max:10',
self::youtubeId->name => 'nullable|string|size:11',
self::vimeoId->name => 'required|string|min:8|max:10',
self::youtubeId->name => 'required|string|size:11',
self::date->name => 'required|date',
self::color->name => 'required|hex_color',
];
/**
@ -93,5 +95,6 @@ enum DynamicFieldTypes: int
self::vimeoId->name => false,
self::youtubeId->name => false,
self::date->name => false,
self::color->name => false,
];
}

View file

@ -139,6 +139,11 @@ abstract class UpdateDynamicFieldRequest extends FormRequest
$ruleKey => $this->compileValidate(DynamicFieldTypes::date->getValidation(), $input)
]);
break;
case DynamicFieldTypes::color->value:
$rules = array_merge($rules, [
$ruleKey => $this->compileValidate(DynamicFieldTypes::color->getValidation(), $input)
]);
break;
default:
throw new \UnexpectedValueException("Unrecognized dynamic type: " . ($input['type'] ?? 'null'));
break;

View file

@ -162,6 +162,11 @@ return [
"simple_date_picker" => [
"reset" => "reset the date"
],
"simple_color_picker" => [
"select" => "select a color",
"reset" => "reset the color",
"delete" => "delete the color",
],
"news" => [
"categories" => [
"placeholder" => "select your article's categories"

View file

@ -25,6 +25,7 @@ return [
'vimeoId' => 'Vimeo video identification',
'youtubeId' => 'Youtube video identification',
'date' => 'Date',
'color' => 'Color',
],
'contactFormType' => [
'collaborator' => [

View file

@ -163,6 +163,11 @@ return [
"simple_date_picker" => [
"reset" => "vider la date",
],
"simple_color_picker" => [
"select" => "sélectionner une couleur",
"reset" => "réinitialiser la couleur",
"delete" => "supprimer la couleur",
],
"news" => [
"categories" => [
"placeholder" => "sélectionnez les catégories de votre article",

View file

@ -25,6 +25,7 @@ return [
'vimeoId' => 'Identifiant vidéo Vimeo',
'youtubeId' => 'Identifiant vidéo Youtube',
'date' => 'Date',
'color' => 'Couleur',
],
'contactFormType' => [
'collaborator' => [

3470
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -27,6 +27,7 @@
"@tailwindcss/forms": "^0.5.10",
"@tailwindcss/typography": "^0.5.16",
"@tailwindcss/vite": "^4.1",
"@types/react-color": "^3.0.13",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitejs/plugin-react": "^4.7.0",
@ -83,6 +84,7 @@
"laravel-vite-plugin": "^1.3.0",
"lucide-react": "^0.503.0",
"motion": "^12.23.12",
"react-color": "^2.19.3",
"react-day-picker": "^9.11.1",
"react-dropzone": "^14.3.8",
"reactjs-tiptap-editor": "^0.3.23",

View file

@ -1,6 +1,6 @@
// * Packages
import { Link } from "@inertiajs/react";
import { ReactNode } from "react";
import { CSSProperties, ReactNode } from "react";
import { VariantProps } from "class-variance-authority";
// * Components shadcn
import { Button, buttonVariants } from "@/components/ui/button";
@ -23,7 +23,8 @@ type BtnOptionnalLinkWithTooltipProps = {
size?: ButtonSize;
variant?: ButtonVariant;
externalLink?: boolean;
disable?: boolean;
disabled?: boolean;
style?: CSSProperties;
onClick?: () => void;
};
@ -36,7 +37,9 @@ export default function BtnOptionnalLinkWithTooltip({
size = "icon",
variant = "default",
externalLink = false,
disable = false,
disabled = false,
style,
onClick,
...props
}: BtnOptionnalLinkWithTooltipProps) {
return (
@ -48,8 +51,9 @@ export default function BtnOptionnalLinkWithTooltip({
className={className}
type={type}
asChild={link !== null}
disabled={disable}
onClick={props.onClick}
disabled={disabled}
onClick={onClick}
style={style}
{...props}
>
{link !== null ? (

View file

@ -9,6 +9,7 @@ import ImageCropperWrapper from "@/back/Components/Inputs/CompleteInputFile";
import DynamicList from "@/back/Components/DynamicPages/DynamicList";
import SimpleTextarea from "@/back/Components/Inputs/SimpleTextarea";
import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker";
import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker";
import { ConfigField, DynamicFieldTypes, DynamicInternalField } from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
@ -215,6 +216,17 @@ export default function DynamicInputs({
label={getTrans(field.label)}
/>
);
// Color picker.
case enumDynamicFieldTypes.color.value:
return (
<SimpleColorPicker
name={fieldName}
setData={setData}
value={String(fieldValue)}
label={getTrans(field.label)}
required={extractRequiredValidation(field.validation)}
/>
);
default:
return (
<p

View file

@ -292,7 +292,7 @@ function SortableItem({
type="button"
variant="outline"
size="icon"
disable={parentAccordionState !== ""}
disabled={parentAccordionState !== ""}
{...listeners}
{...attributes}
/>

View file

@ -0,0 +1,324 @@
// * Packages
import { useState, useEffect, useRef } from "react";
import { usePage } from "@inertiajs/react";
import { SketchPicker, ColorResult } from "react-color";
import { RefreshCwIcon, TrashIcon } from "lucide-react";
import { PresetColor } from "react-color/lib/components/sketch/Sketch";
// * Components shadcn
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "@/components/ui/popover";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import { cn } from "@/lib/utils";
type SimpleColorPickerProps = {
className?: string;
name: string;
id?: string;
label: string;
value: string | null;
placeholder?: string,
presetColors?: PresetColor[];
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
setData: (name: string, value: string | null) => void;
};
export default function SimpleColorPicker({
className,
name,
id = name,
label,
value = null,
placeholder = "#ffffffff",
presetColors = [
"#000000", // Black
"#ffffff", // White
"#ff0000", // Red
"#00ff00", // Vert
"#008080", // Teal
"#8a2be2", // Violet
"#0000ff", // Blue
"#ff7f50", // Coral
"#ffa500", // Orange
"#ffff00", // Yellow
],
required = true,
disabled = false,
parentErrors = null,
setData,
}: SimpleColorPickerProps) {
const { errors } = usePage().props;
const localErrors = parentErrors ?? errors;
// Colors.
const [color, setColor] = useState<string | null>(value);
const initialColor = useRef<string | null>(value ?? "#ffffffff");
// Popover status.
const [open, setOpen] = useState(false);
// Translations.
const transSelect = useTrans("back.simple_color_picker.select");
const transReset = useTrans("back.simple_color_picker.reset");
const transDelete = useTrans("back.simple_color_picker.delete");
/**
* Check the format/structure of the selected color.
*
* @param val string
* @return boolean
*/
function isHex(val: string): boolean {
return /^#([0-9A-Fa-f]{3,4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(val);
};
/**
* Convert ColorResult → HEXA.
*
* @param color ColorResult
* @return string
*/
function toHEXA(color: ColorResult): string {
const r = color.rgb.r.toString(16).padStart(2, "0");
const g = color.rgb.g.toString(16).padStart(2, "0");
const b = color.rgb.b.toString(16).padStart(2, "0");
const a = Math.round((color.rgb.a ?? 1) * 255).toString(16).padStart(2, "0") ?? "ff";
return `#${r}${g}${b}${a}`;
};
/**
* On change color via picker.
*
* @param color ColorResult
* @return void
*/
function handleChange(c: ColorResult): void {
const hex = toHEXA(c);
setColor(hex);
}
/**
* Update color via picker.
*
* @param color ColorResult
* @return void
*/
function handleChangeComplete(color: ColorResult): void {
const hex = toHEXA(color);
setColor(hex);
setData(name, hex);
}
/**
* Reset input color.
*
* @return void
*/
function handleReset(): void {
setColor(initialColor.current);
setData(name, initialColor.current);
}
/**
* Clear input color.
*
* @return void
*/
function handleClear(): void {
setColor(null);
setData(name, null);
setOpen(false);
}
/**
* Change color manually.
*
* @param val string
* @returns void
*/
function handleInput(val: string): void {
if (val === "") {
setColor(null);
setData(name, null);
return;
}
setColor(val);
// Validate format.
if (isHex(val)) {
setData(name, val);
}
}
useEffect(() => {
if (value !== color) setColor(value);
}, [value]);
return (
<div className={cn("flex flex-col gap-2", className)}>
<Label htmlFor={id}>
{label}
{required ? " *" : ""}
</Label>
<div className="flex items-center gap-1.5">
{/* POPUP PICKER */}
<Popover open={open} onOpenChange={setOpen}>
{/* Preview */}
<PopoverTrigger asChild>
<BtnOptionnalLinkWithTooltip
content={""}
tooltipContent={str(transSelect).ucFirst().value()}
type="button"
variant="outline"
className="w-10 h-10 border-0"
disabled={disabled}
style={{
background: color || "transparent",
outline: "1px solid hsl(var(--input))",
}}
/>
</PopoverTrigger>
{/* Input HEX / RGBA */}
<Input
id={id}
value={color ?? ""}
onChange={(e) => handleInput(e.target.value)}
placeholder={placeholder}
disabled={disabled}
className="flex-1"
/>
{/* POPUP CONTENT */}
<PopoverContent className="p-2">
<SketchPicker
color={String(color || initialColor.current)}
onChange={handleChange}
onChangeComplete={handleChangeComplete}
disableAlpha={false}
presetColors={presetColors}
/>
{/* Force custom style */}
<style>
{`
.sketch-picker {
display: flex;
flex-direction: column;
padding: 0 !important;
border: 0 !important;
box-shadow: none !important;
width: 100% !important;
}
.sketch-picker, .sketch-picker .flexbox-fix {
gap: 0.375rem;
}
.sketch-picker > div, .sketch-picker .flexbox-fix > div {
padding: 0 !important;
margin: 0 !important;
}
.sketch-picker > div:first-child {
aspect-ratio: 1 / 1;
border-radius: calc(var(--radius) - 2px);
}
.sketch-picker > div:first-child > div > div > div:last-child > div {
width: 10px !important;
height: 10px !important;
box-shadow: none !important;
border-radius: 50% !important;
transform: translate(-5px, -5px) !important;
background-color: white;
}
.sketch-picker > div:nth-child(2) > div:first-child {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.sketch-picker > div:nth-child(2) > div:first-child > div {
height: 20px !important;
outline: 1px solid hsl(var(--input));
border-radius: calc(var(--radius) - 2px);
margin: 0rem !important;
cursor: pointer;
}
.sketch-picker > div:nth-child(2) > div:first-child > div > div > div > div > div {
width: 0.5rem !important;
height: 20px !important;
border-radius: 0 !important;
box-shadow: none !important;
background: rgb(255, 255, 255) !important;
transform: translateX(-4px) !important;
margin-top: 0 !important;
border: 1px hsl(var(--input)) solid;
}
.sketch-picker > div:nth-child(2) > div:last-child {
display: none;
}
.sketch-picker > div:nth-child(3) > div:first-child {
width: 16rem;
}
.sketch-picker > div:nth-child(3) > div {
flex: auto !important;
}
.sketch-picker > div:last-child {
justify-content: space-between;
padding-top: 0.375rem !important;
}
.sketch-picker > div:last-child > div {
width: 20px !important;
height: 20px !important;
}
.sketch-picker > div:last-child > div > span > div {
box-shadow: none !important;
outline: 1px solid hsl(var(--input)) !important;
border-radius: calc(var(--radius) - 2px) !important;
}
.sketch-picker input {
width: 100% !important;
height: 2.5rem;
border-radius: calc(var(--radius) - 2px) !important;
border: 1px hsl(var(--input)) solid !important;
background-color: hsl(var(--background));
padding: 0.5rem 0.75rem !important;
color: var(--foreground);
box-shadow: none !important;
outline: none;
text-align: center;
}
`}
</style>
</PopoverContent>
</Popover>
{/* RESET/DELETE */}
<BtnOptionnalLinkWithTooltip
content={<RefreshCwIcon className="w-4 h-4" />}
tooltipContent={str(transReset).ucFirst().value()}
type="button"
variant="secondary"
size="icon"
onClick={handleReset}
disabled={disabled}
/>
{!required && (
<BtnOptionnalLinkWithTooltip
content={<TrashIcon className="w-4 h-4" />}
tooltipContent={str(transDelete).ucFirst().value()}
type="button"
variant="destructive"
size="icon"
onClick={handleClear}
disabled={disabled}
/>
)}
</div>
<InputError message={localErrors?.[name]} />
</div>
);
}

View file

@ -226,7 +226,7 @@ export default function FieldGroup({
type="button"
variant="outline"
size="icon"
disable={parentAccordionState !== ""}
disabled={parentAccordionState !== ""}
{...attributes}
{...listeners}
/>