Merge branch 'fix/news' into 'develop'

feat: ✨ add new missing field in news, and improve form, + new input type

See merge request ldc-web/projets/ldc!58
This commit is contained in:
karl.muller 2025-11-19 09:12:59 +00:00
commit 5244f24672
23 changed files with 943 additions and 594 deletions

View file

@ -18,9 +18,13 @@ enum DynamicFieldTypes: int
case email = 7;
case image = 8;
case list = 9;
case file = 10;
case vimeoId = 11;
case youtubeId = 12;
// case color = 10;
// case date = 11;
/**
* Labels definition.
*
@ -36,6 +40,9 @@ enum DynamicFieldTypes: int
self::email->name => 'enums.dynamic-field-types.email',
self::image->name => 'enums.dynamic-field-types.image',
self::list->name => 'enums.dynamic-field-types.list',
self::file->name => 'enums.dynamic-field-types.file',
self::vimeoId->name => 'enums.dynamic-field-types.vimeoId',
self::youtubeId->name => 'enums.dynamic-field-types.youtubeId'
];
/**
@ -51,6 +58,9 @@ enum DynamicFieldTypes: int
self::email->name => 'required|email:rfc,strict,dns,spoof,filter',
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',
];
/**
@ -65,7 +75,7 @@ enum DynamicFieldTypes: int
/**
* Is array definition.
*
*
* @return array
*/
private const ISARRAY = [
@ -78,5 +88,8 @@ enum DynamicFieldTypes: int
self::email->name => false,
self::image->name => false,
self::list->name => true,
self::file->name => false,
self::vimeoId->name => false,
self::youtubeId->name => false
];
}

View file

@ -6,9 +6,11 @@ use App\Enums\News\NewsCategoryEnum;
use App\Enums\News\NewsStatusEnum;
use App\Models\News;
use App\Traits\Requests\HasInertiaPicture;
use GuzzleHttp\Psr7\UploadedFile;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rules\Enum;
use Uwil\LaravelCommon\Rules\IsValidVimeoId;
class StoreNewsRequest extends FormRequest
{
@ -39,20 +41,43 @@ class StoreNewsRequest extends FormRequest
*/
public function rules(): array
{
return [
'seo_title' => 'required|string|between:3,255',
'seo_description' => 'required|string|between:3,255',
'title' => 'required|string|between:3,255',
'slug' => 'required|string|between:3,255',
'picture' => $this->pictureRules("nullable|file|mimes:jpg,jpeg,png,webp|max:5120|dimensions:width=525,height=295"),
'picture' => [
function ($attribute, $value, $fail) {
if (request()->file($attribute) && request()->file($attribute)->getClientOriginalExtension() === 'gif') {
$validator = \Validator::make(
[$attribute => $value],
[$attribute => 'nullable|file|mimes:gif|max:5120']
);
} else {
$validator = \Validator::make(
[$attribute => $value],
[$attribute => 'nullable|file|mimes:jpg,jpeg,png,webp|max:5120|dimensions:width=525,height=295']
);
}
if ($validator->fails()) {
$fail($validator->errors()->first($attribute));
}
}
],
'picture_alt' => 'nullable|string|between:3,60',
'picture_title' => 'nullable|string|between:3,60',
'content' => 'required|string',
'content' => 'required|string|max:5000',
'status' => ['required', new Enum(NewsStatusEnum::class)],
'categories' => 'nullable|array',
'categories.*' => ['integer', new Enum(NewsCategoryEnum::class)],
'published_at' => 'nullable|date',
'unpublished_at' => 'nullable|date|after:published_at',
'inverted' => 'boolean',
'vimeo_id' => ['string', 'nullable', 'min:8', 'max:10', new IsValidVimeoId()]
];
}

View file

@ -25,6 +25,8 @@ use Illuminate\Support\Facades\Cache;
* @property string $picture_alt Alt text for the picture.
* @property string $picture_title Title for the picture.
* @property string $content Content of the news.
* @property boolean $inverted Are image and content inverted in front
* @property string $vimeo_id Optionnal vimeo_id
* @property \App\Enums\News\NewsStatusEnum $status Status of the news.
* @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated.
@ -75,6 +77,8 @@ class News extends Model implements TranslatableModel
'picture_title',
'published_at',
'unpublished_at',
'inverted',
'vimeo_id'
];
/**

View file

@ -45,8 +45,8 @@ trait HasInertiaPicture
/**
* Set picture rules (UploadedFile or string path).
*
* @param array $rules
*
* @param string $rules
* @return string
*/
protected function pictureRules(string $rules): array
@ -73,7 +73,7 @@ trait HasInertiaPicture
// Filter unused rules for validator.
// The “required” and “nullable” rules are not the same as those for online validation.
$validatorRules = array_filter($rules, fn($r) => $r !== 'required' && $r !== 'nullable');
$validator = \Validator::make(
[$attribute => $value],
[$attribute => implode('|', $validatorRules)]

View file

@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('news', function (Blueprint $table) {
$table->mediumText('content')->comment('Body of the news, wysiwyg to be more specific')->change();
$table->text('seo_title')->nullable(false)->comment('Seo title for the news')->change();
$table->text('seo_description')->nullable(false)->comment('Seo description of the news')->change();
$table->text('picture_alt')->nullable()->comment('Alt of the picture of the news')->change();
$table->text('picture_title')->nullable()->comment('Title of the picture of the news')->change();
$table->boolean('inverted')->default(false)->comment('Side of the text/image in the front display');
$table->text('vimeo_id')->nullable()->comment('Vimeo id optionnal');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('news', function (Blueprint $table) {
$table->text('content')->change();
$table->string('seo_title')->nullable(false)->comment('Seo title for the news')->change();
$table->string('seo_description')->nullable(false)->comment('Seo description of the news')->change();
$table->string('picture_alt')->nullable()->comment('Alt of the picture of the news')->change();
$table->string('picture_title')->nullable()->comment('Title of the picture of the news')->change();
$table->dropColumn('inverted');
$table->dropColumn('vimeo_id');
});
}
};

View file

@ -1,6 +1,8 @@
<?php
return [
"access_to_front_page" => "link to your page",
"access_to_front_page_when_published" => "link to your page when published",
"login_title" => "Authentication",
"login_desc" => "Log in to access the administrative part of your website
<span class='font-bold'>:appName</span> !",
@ -65,6 +67,8 @@ return [
"table_search_reset" => "Reset the search",
"table_filter_button" => "Filter results by :field",
"table_filter_reset" => "Remove all selected filters",
"form_title_additional_files" => "Additionnal files",
"form_subtitle_additional_files" => "Add additionnal files",
"form_title_global" => "General information",
"form_subtitle_global" => "Modify the main information related to this data model.",
"form_title_visibility" => "Visibility",
@ -85,6 +89,8 @@ return [
"form_subtitle_content" => "Manage content of the model",
"form_title_configuration" => "Configuration",
"form_subtitle_configuration" => "Manage model configuration.",
"form_title_display" => "Display",
"form_subtitle_display" => "Manage the final display of the model",
"access_model" => "Access to the :model",
"close" => "Close",
"clear" => "clear",
@ -111,8 +117,10 @@ return [
"validate" => "confirm",
"cancel" => "cancel",
"crop" => "crop",
"slugify" => "slugify",
"filter" => "filter|filters",
"image_cropper" => [
"state_file_uploaded" => "a file is uploaded with success",
"modale_title" => "Image modification",
"modale_description" => "Customize the rendering according to your needs",
"action_the_crop" => ":action the crop",

View file

@ -20,7 +20,10 @@ return [
'url' => 'Link',
'email' => 'E-mail',
'image' => 'Image',
'list' => 'Item list'
'list' => 'Item list',
'file' => 'File',
'vimeoId' => 'VIMEO ID',
'youtubeId' => 'YOUTUBE ID'
],
'contactFormType' => [
'collaborator' => [

View file

@ -256,6 +256,8 @@ return [
"contactCount" => [
"type" => "form type",
"submissions" => "count of soumissions"
]
],
"vimeo_id" => "VIMEO ID",
"youtube_id" => "YOUTUBE ID"
],
];

View file

@ -1,118 +1,126 @@
<?php
return [
"login_title" => "Authentification",
"login_desc" => "Connectez-vous afin d'accéder à la partie administrative de votre site
"access_to_front_page" => "lien de votre page",
"access_to_front_page_when_published" => "lien de votre page une fois publiée",
"login_title" => "Authentification",
"login_desc" => "Connectez-vous afin d'accéder à la partie administrative de votre site
internet <span class='font-bold'>:appName</span> !",
"login_btn" => "Connexion avec UWIL Support",
"login_unpublished_user" => "Votre compte à été désactivé, veuillez contactez un administrateur du site.",
"dashboard" => "Tableau de bord",
"your_website" => "Votre site",
"pages" => "Pages",
"modules" => "Modules",
"telescope" => "Telescope",
"yes_delete" => "Oui, supprimer",
"yes_update" => "Oui, mettre à jour",
"yes_restore" => "Oui, restorer",
"yes_archive" => "Oui, archiver",
"no_cancel" => "Non, annuler",
"yes" => "Oui",
"no" => "Non",
"are_you_sure" => "Êtes-vous sûr ?",
"trash_data" => "Toutes les données seront archivées !",
"restore_data" => "Toutes les données seront restorées !",
"lost_data" => "Toutes les données seront définitivement perdues !",
"model_action_updated_at" => "Dernières modifications le :",
"profile" => "Profil",
"disconnect" => "Se déconnecter",
"sidebar_trigger_tooltip" => "Réduire/aggrandir la barre de navigation",
"warning" => "Attention",
"warning_production" => "Vous êtes actuellement connecté en <span class='font-bold'>PRODUCTION</span>.
"login_btn" => "Connexion avec UWIL Support",
"login_unpublished_user" => "Votre compte à été désactivé, veuillez contactez un administrateur du site.",
"dashboard" => "Tableau de bord",
"your_website" => "Votre site",
"pages" => "Pages",
"modules" => "Modules",
"telescope" => "Telescope",
"yes_delete" => "Oui, supprimer",
"yes_update" => "Oui, mettre à jour",
"yes_restore" => "Oui, restorer",
"yes_archive" => "Oui, archiver",
"no_cancel" => "Non, annuler",
"yes" => "Oui",
"no" => "Non",
"are_you_sure" => "Êtes-vous sûr ?",
"trash_data" => "Toutes les données seront archivées !",
"restore_data" => "Toutes les données seront restorées !",
"lost_data" => "Toutes les données seront définitivement perdues !",
"model_action_updated_at" => "Dernières modifications le :",
"profile" => "Profil",
"disconnect" => "Se déconnecter",
"sidebar_trigger_tooltip" => "Réduire/aggrandir la barre de navigation",
"warning" => "Attention",
"warning_production" => "Vous êtes actuellement connecté en <span class='font-bold'>PRODUCTION</span>.
Pour tester, veuillez vous connecter à la recette !",
"warning_trash" => "Suppression des entrées après 30 jours passé en temps qu'archive !",
"dashboard_paragraph_1" => "Bienvenue dans le <span class='font-bold'>back-office</span> de votre site internet
"warning_trash" => "Suppression des entrées après 30 jours passé en temps qu'archive !",
"dashboard_paragraph_1" => "Bienvenue dans le <span class='font-bold'>back-office</span> de votre site internet
<span class='font-bold'>:appName</span>.",
"dashboard_paragraph_2" => "Ici, vous pouvez gérer des contenus apparaissant dans votre site internet, tel que
"dashboard_paragraph_2" => "Ici, vous pouvez gérer des contenus apparaissant dans votre site internet, tel que
des images, des textes et bien d'autres éléments.",
"dashboard_paragraph_3" => "<span class='font-bold'>UWIL</span> vous accompagne dans votre
"dashboard_paragraph_3" => "<span class='font-bold'>UWIL</span> vous accompagne dans votre
<span class='font-bold'>conception</span> ainsi que la <span class='font-bold'>réalisation</span> de vos projets
actuels et futurs.",
"dashboard_paragraph_4" => "N'hésitez pas à utiliser nos outils <span class='font-bold'>UWIL by LDC</span> :",
"uwil_report_desc" => "Accéder aux statistiques de votre site via notre outil",
"uwil_support_desc" => "Pour tout problème ou évolution souhaitée, veuillez nous contacter via notre outil",
"uwil_expo_desc" => "...",
"uwil_util_tooltip" => "Accéder à notre outil dans un nouvel onglet",
"words" => "Mots : ",
"characters" => "Caractères : ",
"table_no_results" => "Aucun résultat.",
"table_field" => "Champ",
"table_value" => "Valeur",
"table_not_known" => "Non renseigné",
"enter_text_here" => "Renseigner du texte ici",
"enter_number_here" => "Renseigner un chiffre/nombre ici",
"errors" => "Erreurs",
"light" => "Clair",
"dark" => "Sombre",
"system" => "Système",
"mods" => "Modes",
"languages" => "Langues",
"settings" => "Paramètres",
"crud_back_to_list" => "Revenir à la liste des entrées",
"crud_add_entry" => "Ajouter une nouvelle entrée",
"crud_access_trash" => "Accéder aux entrées archivées",
"table_search" => "Rechercher sur :searchFields",
"table_search_reset" => "Effacer la recherche",
"table_filter_button" => "Filtrer les résultats par le champs :field",
"table_filter_reset" => "Retirer tous les filtres sélectionnés",
"form_title_global" => "Informations générales",
"form_subtitle_global" => "Modifier les informations principales liées à ce modèle de données.",
"form_title_visibility" => "Visibilité",
"form_subtitle_visibility" => "Gérer l'affichage du compte.",
"form_title_isLocked" => "Restriction",
"form_subtitle_isLocked" => "Gérer le vérouillage de la page.",
"form_associate_to" => ":attribute associé au modèle|:attribute associée au modèle",
"form_associate_to_plural" => ":attribute associés au modèle|:attribute associées au modèle",
"form_title_config" => "Réglage",
"form_subtitle_config" => "Gérer le paramétrage d'une configuration.",
"form_title_page" => "Configuration",
"form_subtitle_page" => "Gérer le contenu d'une page dynamique.",
"form_title_files" => "Fichiers",
"form_subtitle_files" => "Gérer les fichiers du modèle.",
"form_title_seo" => "Champs SEO",
"form_subtitle_seo" => "Gérer les champs SEO du modèle.",
"form_title_content" => "Contenu",
"form_subtitle_content" => "Gérer le contenu du modèle.",
"form_title_configuration" => "Configuration",
"form_subtitle_configuration" => "Gérer la configuration du modèle.",
"access_model" => "Accéder à la :model",
"clear" => "vider",
"close" => "Fermer",
"config_modal_title" => "Prévisualisation",
"config_modal_descripion" => "Contenu de la configuration sélectionnée",
"config_none_selected" => "Aucune configuration sélectionnée",
"config_select_fields" => "Écraser les champs avec ceux d'une langue déjà existante",
"config_save_warning" => "La configuration des pages associées dans la langue :locale devra être mise à jour
"dashboard_paragraph_4" => "N'hésitez pas à utiliser nos outils <span class='font-bold'>UWIL by LDC</span> :",
"uwil_report_desc" => "Accéder aux statistiques de votre site via notre outil",
"uwil_support_desc" => "Pour tout problème ou évolution souhaitée, veuillez nous contacter via notre outil",
"uwil_expo_desc" => "...",
"uwil_util_tooltip" => "Accéder à notre outil dans un nouvel onglet",
"words" => "Mots : ",
"characters" => "Caractères : ",
"table_no_results" => "Aucun résultat.",
"table_field" => "Champ",
"table_value" => "Valeur",
"table_not_known" => "Non renseigné",
"enter_text_here" => "Renseigner du texte ici",
"enter_number_here" => "Renseigner un chiffre/nombre ici",
"errors" => "Erreurs",
"light" => "Clair",
"dark" => "Sombre",
"system" => "Système",
"mods" => "Modes",
"languages" => "Langues",
"settings" => "Paramètres",
"crud_back_to_list" => "Revenir à la liste des entrées",
"crud_add_entry" => "Ajouter une nouvelle entrée",
"crud_access_trash" => "Accéder aux entrées archivées",
"table_search" => "Rechercher sur :searchFields",
"table_search_reset" => "Effacer la recherche",
"table_filter_button" => "Filtrer les résultats par le champs :field",
"table_filter_reset" => "Retirer tous les filtres sélectionnés",
"form_title_additional_files" => "Fichier supplémentaire",
"form_subtitle_additional_files" => "Ajouter des fichiers supplémentaires",
"form_title_global" => "Informations générales",
"form_subtitle_global" => "Modifier les informations principales liées à ce modèle de données.",
"form_title_visibility" => "Visibilité",
"form_subtitle_visibility" => "Gérer l'affichage du compte.",
"form_title_isLocked" => "Restriction",
"form_subtitle_isLocked" => "Gérer le vérouillage de la page.",
"form_associate_to" => ":attribute associé au modèle|:attribute associée au modèle",
"form_associate_to_plural" => ":attribute associés au modèle|:attribute associées au modèle",
"form_title_config" => "Réglage",
"form_subtitle_config" => "Gérer le paramétrage d'une configuration.",
"form_title_page" => "Configuration",
"form_subtitle_page" => "Gérer le contenu d'une page dynamique.",
"form_title_files" => "Fichiers",
"form_subtitle_files" => "Gérer les fichiers du modèle.",
"form_title_seo" => "Champs SEO",
"form_subtitle_seo" => "Gérer les champs SEO du modèle.",
"form_title_content" => "Contenu",
"form_subtitle_content" => "Gérer le contenu du modèle.",
"form_title_configuration" => "Configuration",
"form_subtitle_configuration" => "Gérer la configuration du modèle.",
"form_title_display" => "Affichage",
"form_subtitle_display" => "Gérer l'ordre d'affichage sur le rendu final.",
"access_model" => "Accéder à la :model",
"clear" => "vider",
"close" => "Fermer",
"config_modal_title" => "Prévisualisation",
"config_modal_descripion" => "Contenu de la configuration sélectionnée",
"config_none_selected" => "Aucune configuration sélectionnée",
"config_select_fields" => "Écraser les champs avec ceux d'une langue déjà existante",
"config_save_warning" => "La configuration des pages associées dans la langue :locale devra être mise à jour
en conséquence.",
"config_save_warning_list" => "Voici la liste des :models concernés:|Voici la liste des :models concernées:",
"config_archived" => "Cette configuration est actuellement archivée",
"config_complete_label" => "Copier le libellé complet de l'input",
"entries_count" => ":length entrée renseignée|:length entrées renseignées",
"new_field" => "Ajouter un nouveau champ",
"delete_field" => "Supprimer ce champ",
"dnd_field" => "Déplacer ce champ",
"list_children_needed" => "Des enfants sont nécessaires pour ce type :enumLabel",
"empty_warning" => "Aucune donnée enregistrée",
"page_locked" => "Cette page est actuellement vérouillée",
"unsupported_type" => "Type non supporté:",
"missing_translations" => "La traduction du champs :field pour la langue :locales est manquante.|La traduction
du champs :field pour les langues :locales sont manquantes.",
"no_more_children" => "Limite atteinte, vous ne pouvez pas ajouter de nouveaux éléments",
"archives" => "archives",
"validate" => "valider",
"cancel" => "annuler",
"crop" => "recadrer",
"filter" => "filtre|filtres",
"image_cropper" => [
"config_save_warning_list" => "Voici la liste des :models concernés:|Voici la liste des :models concernées:",
"config_archived" => "Cette configuration est actuellement archivée",
"config_complete_label" => "Copier le libellé complet de l'input",
"entries_count" => ":length entrée renseignée|:length entrées renseignées",
"new_field" => "Ajouter un nouveau champ",
"delete_field" => "Supprimer ce champ",
"dnd_field" => "Déplacer ce champ",
"list_children_needed" => "Des enfants sont nécessaires pour ce type :enumLabel",
"empty_warning" => "Aucune donnée enregistrée",
"page_locked" => "Cette page est actuellement vérouillée",
"unsupported_type" => "Type non supporté:",
"missing_translations" => "La traduction du champs :field pour la langue :locales est manquante.|La traduction
du champs :field pour l es langues :locales sont manquantes.",
"no_more_children" => "Limite atteinte, vous ne pouvez pas ajouter de nouveaux éléments",
"archives" => "archives",
"validate" => "valider",
"cancel" => "annuler",
"crop" => "recadrer",
"slugify" => "slugifier",
"filter" => "filtre|filtres",
"image_cropper" => [
"state_file_uploaded" => "un fichier à bien été chargé",
"modale_title" => "Modification de l'image",
"modale_description" => "Personnalisez le rendu selon vos besoins",
"action_the_crop" => ":action le cadrage",

View file

@ -12,15 +12,18 @@ return [
'unpublished' => 'Dépublié',
],
'dynamic-field-types' => [
'string' => 'Chaîne de caractères',
'textarea' => 'Textarea',
'wysiwyg' => 'Wysiwyg',
'number' => 'Numérique',
'boolean' => 'Booléen',
'url' => 'Lien',
'email' => 'E-mail',
'image' => 'Image',
'list' => 'Liste de champs'
'string' => 'Chaîne de caractères',
'textarea' => 'Textarea',
'wysiwyg' => 'Wysiwyg',
'number' => 'Numérique',
'boolean' => 'Booléen',
'url' => 'Lien',
'email' => 'E-mail',
'image' => 'Image',
'list' => 'Liste de champs',
'list' => 'Fichier',
'vimeoId' => 'ID de la vidéo VIMEO',
'youtubeId' => 'ID de la vidéo YOUTUBE'
],
'contactFormType' => [
'collaborator' => [

View file

@ -255,5 +255,7 @@ return [
"type" => "type de formulaire",
"submissions" => "nombre de soumissions"
],
"vimeo_id" => "ID de la vidéo VIMEO",
"youtube_id" => "ID de la vidéo YOUTUBE"
],
];

View file

@ -5,7 +5,7 @@ import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleNumber from "@/back/Components/Inputs/SimpleNumber";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import SimpleWysiwyg from "@/back/Components/Inputs/SimpleWysiwyg";
import ImageCropperWrapper from "@/back/Components/Inputs/ImageCropper/ImageCropperWrapper";
import ImageCropperWrapper from "@/back/Components/Inputs/CompleteInputFile";
import DynamicList from "@/back/Components/DynamicPages/DynamicList";
import SimpleTextarea from "@/back/Components/Inputs/SimpleTextarea";
import { ConfigField, DynamicFieldTypes, DynamicInternalField } from "@/back/types/global";

View file

@ -0,0 +1,79 @@
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { AppEnv, Model } from "../types/global";
import useTrans from "@/hooks/use-translations";
import { usePage } from "@inertiajs/react";
import { ExternalLinkIcon } from "lucide-react";
import str from "@/hooks/use-string";
interface Props {
/** Current Model being edited */
model?: Model;
/** Model Name used to translate the helper */
modelName: string;
/** Field data to build path */
pathField: string;
/** additionnal segment used in the url */
additionalGroupPath?: string;
/** Does the actual page status available in front */
isAvailable: boolean;
}
const GoToFrontView = (props: Props) => {
const { model, modelName, pathField, additionalGroupPath = null, isAvailable = false } = props;
if(!model) return;
const { locale, url } = usePage().props.appEnv as AppEnv;
const anchorAccessPage = useTrans("back.access_model", {
params: {
model: useTrans(`models.classes.${modelName}`, { choice: 1 }),
},
});
const definitivePath = [
url + (locale === "fr" ? '' : '/' + locale),
additionalGroupPath,
pathField,
]
.filter(Boolean)
.join("/");
return (
<small className="flex flex-row justify-start items-center">
{model && isAvailable ? (
<>
{str(useTrans('back.access_to_front_page')).ucFirst().value()}
<Tooltip>
<TooltipTrigger asChild>
<a
href={definitivePath}
className="flex justify-center items-center rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 underline-offset-4 hover:underline text-blue-600 hover:text-blue-600/80 visited:text-purple-600 w-fit gap-1.5 ms-1"
target="_blank"
rel="noreferrer"
>
{definitivePath}{" "}
<ExternalLinkIcon size={12} />
</a>
</TooltipTrigger>
<TooltipContent>
{anchorAccessPage}
</TooltipContent>
</Tooltip>
</>
) : (
<>
{str(useTrans("back.access_to_front_page_when_published")).ucFirst().value()}:
<span className="italic ms-1">
{definitivePath}
</span>
</>
)}
</small>
)
}
export default GoToFrontView;

View file

@ -0,0 +1,320 @@
// * Packages
import { useCallback, useEffect, useState } from "react";
import { FileCheck, Trash, UploadIcon } from "lucide-react";
import { ErrorCode, FileWithPath, useDropzone } from "react-dropzone";
import "react-image-crop/dist/ReactCrop.css";
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
// * Other
import InputError from "@/back/Components/InputError";
import ImageCropperLogic from "@/back/Components/Inputs/ImageCropper/ImageCropperLogic";
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;
};
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
type ImageCropperWrapperProps = FileValidation & {
name: string;
value?: string | File | null;
label?: string;
required?: boolean;
fileName?: string;
setData: (name: string, value: File | string | null) => void;
reset: (name?: string) => void;
};
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
export default function ImageCropperWrapper(props: ImageCropperWrapperProps) {
const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes;
const {
value,
setData,
name = "defaultName",
label = "defaultLabel",
required = false,
maxFileSize,
validationRules,
allowedFormats,
reset,
inputType = enumDynamicFieldTypes.image.value,
fileName = "image",
} = props;
const { toast } = useToast();
const { errors } = usePage().props;
const { url } = usePage().props.appEnv as AppEnv;
const [isReset, setIsReset] = useState<boolean>(false);
const finalFileName = `${fileName}.png`;
console.log(value)
const [selectedFile, setSelectedFile] = useState<FileWithPreview | null>(
() => {
// When there is an image selected but not stored yet.
if (value instanceof File) {
return Object.assign(value, {
preview: URL.createObjectURL(value),
});
}
// When there is already an image stored.
if (value) {
return { preview: `${url}/${value}` } as FileWithPreview;
}
// When there is not value.
return null;
}
);
const [isDialogOpen, setDialogOpen] = useState(false);
const [accept, setAccept] = useState<Record<string, Array<string>>>({
"image/*": [],
});
const [extensions, setExtensions] = useState<string>();
const localValidationRules = {
width: validationRules?.width ? parseInt(validationRules.width, 10) : 250,
height: validationRules?.height
? parseInt(validationRules?.height, 10)
: 250,
};
const localMaxFileSize = maxFileSize ? parseInt(maxFileSize, 10) * 1024 : 50000;
// Translations
const transSelectImgZone = useTrans('back.image_cropper.select_img_zone');
const transValidationAllFormats = str(
useTrans("back.image_cropper.validation.all_formats"),
).ucFirst().value();
const getTransValidationAllowedFormats = (extensions: string) => {
return str(
useTrans("back.image_cropper.validation.allowed_formats", {
params: {
formats: extensions,
},
}),
).ucFirst().value();
};
// Fonction utilitaire pour formater la taille de fichier
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const currentSize = sizes[i];
const currentBytes = parseFloat((bytes / k ** i).toFixed(2));
return `${currentBytes} ${currentSize}`;
};
const buildDropzoneAccept = (): Record<string, string[]> => {
if (!allowedFormats) return {};
const currentExtensions = allowedFormats.split(",");
setExtensions(allowedFormats);
const mimeMap: Record<string, string> = {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
pdf: "application/pdf",
svg: "image/svg+xml",
webp: "image/webp",
};
const result: Record<string, Set<string>> = {};
currentExtensions.forEach((ext) => {
const cleanExt = ext.trim().toLowerCase();
const mime = mimeMap[cleanExt];
if (mime) {
if (!result[mime]) {
result[mime] = new Set();
}
result[mime].add(`.${cleanExt}`);
}
});
// Convert Set to Array for React Dropzone
const currentAccept: Record<string, string[]> = {};
Object.entries(result).forEach(([mime, extSet]) => {
currentAccept[mime] = Array.from(extSet);
});
setAccept(currentAccept);
return currentAccept;
};
useEffect(() => {
buildDropzoneAccept();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// This error message for the useDropZone can not be used directly in the hook because or react hook error,
// they have to be used as they actually are.
const dropErrorMessages = {
noFile: str(useTrans("back.image_cropper.toast.no_file")).ucFirst().value(),
tooLarge: str(
useTrans("back.image_cropper.toast.too_big", {
params: {
maxSize: formatFileSize(localMaxFileSize),
},
}),
).ucFirst().value(),
forbidden: str(useTrans("back.image_cropper.toast.forbidden_file")).ucFirst().value(),
tooMany: str(useTrans("back.image_cropper.toast.too_many")).ucFirst().value(),
default: str(useTrans("back.image_cropper.toast.defaultError")).ucFirst().value(),
};
const onDrop = useCallback(
(acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0];
if (!file) {
toast({
title: "Oups !",
description: dropErrorMessages.noFile,
});
return;
}
const fileWithPreview = Object.assign(file, {
preview: URL.createObjectURL(file),
});
setSelectedFile(fileWithPreview);
if (inputType === enumDynamicFieldTypes.file.value) {
setData(name, file);
}
setDialogOpen(true);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[maxFileSize, formatFileSize],
);
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept,
multiple: false,
maxSize: localMaxFileSize,
onDropRejected: (fileRejections) => {
const rejection = fileRejections[0];
const rejectionCode = rejection?.errors?.[0]?.code;
if (rejectionCode === ErrorCode.FileTooLarge) {
toast({
title: "Oups !",
description: `${dropErrorMessages.tooLarge} (${formatFileSize(rejection.file.size)}).`,
});
} else if (rejectionCode === ErrorCode.FileInvalidType) {
toast({
title: "Oups !",
description: dropErrorMessages.forbidden,
});
} else if (rejectionCode === ErrorCode.TooManyFiles) {
toast({
title: "Oups !",
description: dropErrorMessages.tooMany,
});
} else {
toast({
title: "Oups !",
description: dropErrorMessages.default,
});
}
},
});
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={name}>{label + (required ? " *" : "")}</Label>
{selectedFile ? (
<div className="relative">
{inputType === enumDynamicFieldTypes.image.value && (
<ImageCropperLogic
dialogOpen={isDialogOpen}
value={value}
reset={reset}
setData={setData}
setDialogOpen={setDialogOpen}
selectedFile={selectedFile}
validationRules={{
width: localValidationRules.width,
height: localValidationRules.height,
}}
name={name}
url={url}
isReset={isReset}
setIsReset={setIsReset}
finalFileName={finalFileName}
/>
)}
{inputType === enumDynamicFieldTypes.file.value && (
<div
className={cn(
"text-sm flex justify-center border border-dashed overflow-hidden whitespace-normal [&_svg]:!size-auto [&_svg]:!shrink text-muted-foreground w-full h-36",
)}
>
<div className="flex flex-col justify-center items-center">
<FileCheck />
<p className="text-center break-normal w-full mt-2">
{str(useTrans('back.image_cropper.state_file_uploaded')).ucFirst().value()}
</p>
<small>
{selectedFile.name}
</small>
</div>
</div>
)}
<BtnOptionnalLinkWithTooltip
className="absolute top-2 right-2"
variant={'destructive'}
content={<Trash />}
onClick={() => {
setSelectedFile(null);
setData(name, null);
}}
tooltipContent={str(useTrans("back.cancel")).ucFirst().value()}
/>
</div>
) : (
<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",
{ "border-destructive": errors[name] }
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...getRootProps()}
>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<input name={name} {...getInputProps()} />
<div className="flex flex-col justify-center items-center">
<UploadIcon />
<p className="text-center break-normal w-full mt-2">{transSelectImgZone}</p>
<small>
{extensions
? getTransValidationAllowedFormats(extensions)
: transValidationAllFormats}
. {str(
useTrans("back.image_cropper.validation.rules_weight", {
params: {
size: formatFileSize(localMaxFileSize).toString(),
},
}),
)
.ucFirst()
.value()}
</small>
</div>
</Button>
)}
<InputError message={errors[name]} />
</div>
);
}

View file

@ -15,7 +15,6 @@ import {
FlipVerticalIcon,
RotateCcwIcon,
RotateCwIcon,
Trash,
Trash2Icon,
Upload,
ZoomInIcon,
@ -76,7 +75,6 @@ import { cn } from "@/lib/utils";
finalFileName: string;
setData: (name: string, value: File | string | null) => void;
setDialogOpen: Dispatch<SetStateAction<boolean>>;
setSelectedFile: Dispatch<SetStateAction<FileWithPreview | null>>;
reset: (name?: string) => void;
setIsReset: (value: boolean) => void;
}
@ -86,7 +84,6 @@ import { cn } from "@/lib/utils";
dialogOpen,
setDialogOpen,
selectedFile,
setSelectedFile,
validationRules,
setData,
name,
@ -98,7 +95,7 @@ import { cn } from "@/lib/utils";
finalFileName,
}: ImageCropperLogicProps) {
const { errors } = usePage().props;
const aspect = 1;
const { isDesktop } = useDeviceType();
const imgRef = useRef<HTMLImageElement | null>(null);
@ -714,24 +711,6 @@ import { cn } from "@/lib/utils";
)}
</Button>
</DialogTrigger>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="destructive"
size="icon"
onClick={() => {
setSelectedFile(null);
setData(name, null);
}}
className="absolute top-2 right-2"
>
<Trash />
</Button>
</TooltipTrigger>
<TooltipContent>
{str(useTrans("back.cancel")).ucFirst().value()}
</TooltipContent>
</Tooltip>
</div>
<DialogContent className="overflow-y-scroll max-h-[90vh] w-full max-w-full md:max-w-xl lg:max-w-5xl xl:max-w-screen-xl">
<DialogTitle>{useTrans("back.image_cropper.modale_title")}</DialogTitle>

View file

@ -1,288 +0,0 @@
// * Packages
import { useCallback, useEffect, useState } from "react";
import { UploadIcon } from "lucide-react";
import { ErrorCode, FileWithPath, useDropzone } from "react-dropzone";
import "react-image-crop/dist/ReactCrop.css";
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
// * Other
import InputError from "@/back/Components/InputError";
import ImageCropperLogic from "@/back/Components/Inputs/ImageCropper/ImageCropperLogic";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import { useToast } from "@/hooks/use-toast";
import { AppEnv } from "@/back/types/global";
import { cn } from "@/lib/utils";
type FileWithPreview = FileWithPath & {
preview: string;
};
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
type ImageCropperWrapperProps = {
name: string;
value?: string | File | null;
label?: string;
required?: boolean;
validationRules?: {
width: string | null;
height: string | null;
} | null;
maxFileSize: string | null;
allowedFormats: string | null;
fileName?: string;
setData: (name: string, value: File | string | null) => void;
reset: (name?: string) => void;
};
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
export default function ImageCropperWrapper({
value,
setData,
name = "defaultName",
label = "defaultLabel",
required = false,
maxFileSize,
validationRules,
allowedFormats,
reset,
fileName = "image",
}: ImageCropperWrapperProps) {
const { toast } = useToast();
const { errors } = usePage().props;
const { url } = usePage().props.appEnv as AppEnv;
const [isReset, setIsReset] = useState<boolean>(false);
const finalFileName = `${fileName}.png`;
const [selectedFile, setSelectedFile] = useState<FileWithPreview | null>(
() => {
// When there is an image selected but not stored yet.
if (value instanceof File) {
return Object.assign(value, {
preview: URL.createObjectURL(value),
});
}
// When there is already an image stored.
if (value) {
return { preview: `${url}/${value}` } as FileWithPreview;
}
// When there is not value.
return null;
}
);
const [isDialogOpen, setDialogOpen] = useState(false);
const [accept, setAccept] = useState<Record<string, Array<string>>>({
"image/*": [],
});
const [extensions, setExtensions] = useState<string>();
const localValidationRules = {
width: validationRules?.width ? parseInt(validationRules.width, 10) : 250,
height: validationRules?.height
? parseInt(validationRules?.height, 10)
: 250,
};
const localMaxFileSize = maxFileSize ? parseInt(maxFileSize, 10) * 1024 : 50000;
// Translations
const transSelectImgZone = useTrans('back.image_cropper.select_img_zone');
const transValidationAllFormats = str(
useTrans("back.image_cropper.validation.all_formats"),
).ucFirst().value();
const getTransValidationAllowedFormats = (extensions: string) => {
return str(
useTrans("back.image_cropper.validation.allowed_formats", {
params: {
formats: extensions,
},
}),
).ucFirst().value();
};
// Fonction utilitaire pour formater la taille de fichier
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const currentSize = sizes[i];
const currentBytes = parseFloat((bytes / k ** i).toFixed(2));
return `${currentBytes} ${currentSize}`;
};
const buildDropzoneAccept = (): Record<string, string[]> => {
if (!allowedFormats) return {};
const currentExtensions = allowedFormats.split(",");
setExtensions(allowedFormats);
const mimeMap: Record<string, string> = {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
pdf: "application/pdf",
svg: "image/svg+xml",
webp: "image/webp",
};
const result: Record<string, Set<string>> = {};
currentExtensions.forEach((ext) => {
const cleanExt = ext.trim().toLowerCase();
const mime = mimeMap[cleanExt];
if (mime) {
if (!result[mime]) {
result[mime] = new Set();
}
result[mime].add(`.${cleanExt}`);
}
});
// Convert Set to Array for React Dropzone
const currentAccept: Record<string, string[]> = {};
Object.entries(result).forEach(([mime, extSet]) => {
currentAccept[mime] = Array.from(extSet);
});
setAccept(currentAccept);
return currentAccept;
};
useEffect(() => {
buildDropzoneAccept();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// This error message for the useDropZone can not be used directly in the hook because or react hook error,
// they have to be used as they actually are.
const dropErrorMessages = {
noFile: str(useTrans("back.image_cropper.toast.no_file")).ucFirst().value(),
tooLarge: str(
useTrans("back.image_cropper.toast.too_big", {
params: {
maxSize: formatFileSize(localMaxFileSize),
},
}),
).ucFirst().value(),
forbidden: str(useTrans("back.image_cropper.toast.forbidden_file")).ucFirst().value(),
tooMany: str(useTrans("back.image_cropper.toast.too_many")).ucFirst().value(),
default: str(useTrans("back.image_cropper.toast.defaultError")).ucFirst().value(),
};
const onDrop = useCallback(
(acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0];
if (!file) {
toast({
title: "Oups !",
description: dropErrorMessages.noFile,
});
return;
}
const fileWithPreview = Object.assign(file, {
preview: URL.createObjectURL(file),
});
setSelectedFile(fileWithPreview);
setDialogOpen(true);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[maxFileSize, formatFileSize],
);
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept,
multiple: false,
maxSize: localMaxFileSize,
onDropRejected: (fileRejections) => {
const rejection = fileRejections[0];
const rejectionCode = rejection?.errors?.[0]?.code;
if (rejectionCode === ErrorCode.FileTooLarge) {
toast({
title: "Oups !",
description: `${dropErrorMessages.tooLarge} (${formatFileSize(rejection.file.size)}).`,
});
} else if (rejectionCode === ErrorCode.FileInvalidType) {
toast({
title: "Oups !",
description: dropErrorMessages.forbidden,
});
} else if (rejectionCode === ErrorCode.TooManyFiles) {
toast({
title: "Oups !",
description: dropErrorMessages.tooMany,
});
} else {
toast({
title: "Oups !",
description: dropErrorMessages.default,
});
}
},
});
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={name}>{label + (required ? " *" : "")}</Label>
{selectedFile ? (
<ImageCropperLogic
dialogOpen={isDialogOpen}
value={value}
reset={reset}
setData={setData}
setDialogOpen={setDialogOpen}
selectedFile={selectedFile}
setSelectedFile={setSelectedFile}
validationRules={{
width: localValidationRules.width,
height: localValidationRules.height,
}}
name={name}
url={url}
isReset={isReset}
setIsReset={setIsReset}
finalFileName={finalFileName}
/>
) : (
<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",
{ "border-destructive": errors[name] }
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...getRootProps()}
>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<input name={name} {...getInputProps()} />
<div className="flex flex-col justify-center items-center">
<UploadIcon />
<p className="text-center break-normal w-full mt-2">{transSelectImgZone}</p>
<small>
{extensions
? getTransValidationAllowedFormats(extensions)
: transValidationAllFormats}
. {str(
useTrans("back.image_cropper.validation.rules_weight", {
params: {
size: formatFileSize(localMaxFileSize).toString(),
},
}),
)
.ucFirst()
.value()}
</small>
</div>
</Button>
)}
<InputError message={errors[name]} />
</div>
);
}

View file

@ -23,6 +23,7 @@ type SimpleStringProps = {
wordCounter?: boolean;
required?: boolean;
disabled?: boolean;
/** Pattern is regex without antislash */
pattern?: string;
checkVisibility?: boolean;
parentErrors?: Record<string, string> | null,

View file

@ -0,0 +1,25 @@
import str from "@/hooks/use-string";
import SimpleString from "./SimpleString";
import useTrans from "@/hooks/use-translations";
type SimpleVimeoIdProps = {
className?: string;
name: string;
value?: string;
id?: string;
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null,
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
export default function SimpleVimeoId(props: SimpleVimeoIdProps) {
const pattern = "^[0-9]{8,10}$";
const label = str(useTrans('validation.custom.vimeo_id')).ucFirst().value();
const localProps = {pattern, label, ...props};
return (
<SimpleString {...localProps} />
);
}

View file

@ -0,0 +1,25 @@
import str from "@/hooks/use-string";
import SimpleString from "./SimpleString";
import useTrans from "@/hooks/use-translations";
type SimpleYoutubeIdProps = {
className?: string;
name: string;
value?: string;
id?: string;
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null,
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
export default function SimpleYoutubeId(props: SimpleYoutubeIdProps) {
const pattern = "^[0-9A-Za-z_-]{10}[048AEIMQUYcgkosw]$";
const label = str(useTrans('validation.custom.youtube_id')).ucFirst().value();
const localProps = {pattern, label, ...props};
return (
<SimpleString {...localProps} />
);
}

View file

@ -1,6 +1,6 @@
// * Packages
import { useForm, usePage } from "@inertiajs/react";
import { BookTextIcon, CogIcon, ExternalLinkIcon, EyeIcon, ShieldAlertIcon } from "lucide-react";
import { BookTextIcon, CogIcon, EyeIcon, ShieldAlertIcon } from "lucide-react";
import { route } from "ziggy-js";
import { FormEvent, useEffect, useState } from "react";
// * Components shadcn
@ -15,11 +15,6 @@ import {
DialogFooter,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
@ -36,6 +31,7 @@ import str from "@/hooks/use-string";
import { useToast } from "@/hooks/use-toast";
import { Methods } from "@/lib/enums";
import { AppEnv, AuthProp, ConfigField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global";
import GoToFrontView from "@/back/Components/GoToFrontView";
export default function Form({
model,
@ -96,7 +92,7 @@ export default function Form({
.value();
/** Global */
const { locale, url } = usePage().props.appEnv as AppEnv;
const { locale } = usePage().props.appEnv as AppEnv;
const userModel = (usePage().props.auth as AuthProp).user;
const enumUserRole = usePage().props.enumUserRole as LaravelEnum;
const enumDynamicPageStatus = usePage().props
@ -149,11 +145,6 @@ export default function Form({
const modalTitle = useTrans("back.config_modal_title");
const modalDescription = useTrans("back.config_modal_descripion");
const modalClose = useTrans("back.close");
const anchorAccessPage = useTrans("back.access_model", {
params: {
model: useTrans("models.classes.dynamic-page", { choice: 1 }),
},
});
const anchorAccessConfig = useTrans("back.access_model", {
params: {
model: useTrans("models.classes.page-config", { choice: 1 }),
@ -161,7 +152,7 @@ export default function Form({
});
const getConfig = (id: number) =>
configOptions.find((objet) => objet.id == id)?.config[
locale
locale
] as ConfigField[];
const { toast } = useToast();
@ -228,15 +219,9 @@ export default function Form({
return [buildPath(parent), currentTranslatedModelSlug].filter(Boolean).join("/");
};
console.log(buildPath(current));
return buildPath(current);
}
const definitivePath = [
url,
getFullSlugPath(dynamicPageModels, selectedGroup, locale),
data.slug,
]
.filter(Boolean)
.join("/");
useEffect(() => {
const modelTitleValue = model?.title ? model?.title[locale] : "";
@ -337,38 +322,13 @@ export default function Form({
setData={setData}
/>
<div className="col-span-2">
<small className="flex flex-row justify-start items-center">
{model &&
model.status ===
enumDynamicPageStatus.published.value ? (
<>
Lien de votre page:
<Tooltip>
<TooltipTrigger asChild>
<a
href={definitivePath}
className="flex justify-center items-center rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 underline-offset-4 hover:underline text-blue-600 hover:text-blue-600/80 visited:text-purple-600 w-fit gap-1.5 ms-1"
target="_blank"
rel="noreferrer"
>
{definitivePath}{" "}
<ExternalLinkIcon size={12} />
</a>
</TooltipTrigger>
<TooltipContent>
{anchorAccessPage}
</TooltipContent>
</Tooltip>
</>
) : (
<>
Lien de votre page une fois publiée:
<span className="italic ms-1">
{definitivePath}
</span>
</>
)}
</small>
<GoToFrontView
model={model}
modelName="dynamic-page"
pathField={data.slug}
additionalGroupPath={getFullSlugPath(dynamicPageModels, selectedGroup, locale) ?? undefined}
isAvailable={model?.status === enumDynamicPageStatus.published.value}
/>
</div>
</FieldsetWrapper>
<FieldsetWrapper

View file

@ -1,8 +1,8 @@
// * Packages
import { useForm, usePage } from "@inertiajs/react";
import { BookText, Cog } from "lucide-react";
import { BookText, Cog, RefreshCw } from "lucide-react";
import { route } from "ziggy-js";
import { FormEvent } from "react";
import { FormEvent, useEffect, useState } from "react";
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
@ -12,13 +12,20 @@ import str from "@/hooks/use-string";
import InputError from "@/back/Components/InputError";
import { useToast } from "@/hooks/use-toast";
import { Methods } from "@/lib/enums";
import { AppEnv, LaravelEnum, NewsModel } from "@/back/types/global";
import { AppEnv, DynamicFieldTypes, LaravelEnum, NewsModel } from "@/back/types/global";
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
import SimpleWysiwyg from "@/back/Components/Inputs/SimpleWysiwyg";
import { MultiSelect } from "@/back/Components/Inputs/MultiSelect";
import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker";
import { mapLaravelEnumOptions } from "@/lib/mapEnumOptions";
import ImageCropperWrapper from "@/back/Components/Inputs/ImageCropper/ImageCropperWrapper";
import ImageCropperWrapper from "@/back/Components/Inputs/CompleteInputFile";
import { Button } from "@/components/ui/button";
import GoToFrontView from "@/back/Components/GoToFrontView";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { Card, CardContent } from "@/components/ui/card";
import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId";
export default function Form({
model,
@ -35,6 +42,9 @@ export default function Form({
}) {
const { locale } = usePage().props.appEnv as AppEnv;
const { toast } = useToast();
const [isGif, setIsGif] = useState<boolean>(false);
const [dynamicKey, setDynamicKey] = useState<number | null>(null);
const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes;
const enumNewsStatus = usePage().props.enumNewsStatus as LaravelEnum;
const enumNewsCategory = usePage().props.enumNewsCategory as LaravelEnum;
const { options, defaultValue } = mapLaravelEnumOptions(enumNewsCategory, model?.categories, "category");
@ -59,6 +69,27 @@ export default function Form({
),
).ucFirst().value();
useEffect(() => {
if (model && model.picture) {
const isGif = typeof model.picture === "string" && model.picture.toLowerCase().endsWith(".gif");
setIsGif(isGif);
}
}, [model]);
useEffect(() => {
setData('picture', null)
data.picture = null;
}, [isGif])
const refreshFileFromDb = () => {
if (model && model.picture) {
const isGif = typeof model.picture === "string" && model.picture.toLowerCase().endsWith(".gif");
setIsGif(isGif);
setData('picture', model.picture)
setDynamicKey(Date.now())
}
}
/** Form section */
const { post, setData, data, reset } = useForm({
_method: method === Methods.POST ? 'post' : 'put',
@ -67,6 +98,8 @@ export default function Form({
title: model?.title ? model?.title[locale] : "",
slug: model?.slug ? model?.slug[locale] : "",
content: model?.content ? model?.content[locale] : "",
inverted: model?.inverted ?? false,
vimeo_id: model?.vimeo_id ?? "",
status: model?.status ?? enumNewsStatus.unpublished.value,
picture: model?.picture,
picture_alt: model?.picture_alt ? model?.picture_alt[locale] : "",
@ -115,6 +148,21 @@ export default function Form({
)
}
const SlugiFyButton = () => {
return (
<Button variant={"secondary"} type="button" onClick={() => setData("slug", str(data.title).slug().value())}>
<RefreshCw />
{str(useTrans('back.slugify')).ucFirst().value()}
</Button>
);
};
return (
<form onSubmit={submit}>
<InputError all />
@ -159,35 +207,47 @@ export default function Form({
title={useTrans("back.form_title_global")}
icon={<BookText className="mr-1" />}
description={useTrans("back.form_subtitle_global")}
className="sm:grid-cols-2 gap-4"
className="space-y-3"
>
<SimpleString
name="title"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.attributes.title"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.title}
setData={setData}
/>
<SimpleString
name="slug"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.slug"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.slug}
setData={setData}
<div className="w-full grid grid-cols-1 lg:grid-cols-2 items-center sm:grid-cols-2 gap-4">
<SimpleString
name="title"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.attributes.title"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.title}
setData={setData}
/>
<div className="flex items-end gap-1">
<SimpleString
name="slug"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.slug"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.slug}
setData={setData}
/>
<SlugiFyButton />
</div>
</div>
<GoToFrontView
model={model}
modelName="news"
pathField={data.slug}
additionalGroupPath={"actualites"} // TODO: ce sera translatable plus tard
isAvailable={model?.status === enumNewsStatus.published.value}
/>
</FieldsetWrapper>
<FieldsetWrapper
@ -241,64 +301,29 @@ export default function Form({
/>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_files")}
title={useTrans("back.form_title_display")}
icon={<BookText className="mr-1" />}
description={useTrans("back.form_subtitle_files")}
description={useTrans("back.form_subtitle_display")}
className="sm:grid-cols-2 gap-4"
>
<SimpleString
name="picture_alt"
required={false}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.image_alt"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.picture_alt ?? ""}
<SimpleSwitch
name={"inverted"}
checked={Boolean(data.inverted)}
setData={setData}
/>
<SimpleString
name="picture_title"
required={false}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.image_title"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.picture_title ?? ""}
setData={setData}
/>
<ImageCropperWrapper
fileName="picture"
modelRoute="news"
name={"picture"}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.attributes.image"),
},
choice: 1,
}),
).ucFirst().value()}
setData={setData}
reset={reset}
value={data.picture}
required={true}
maxFileSize={"5120"}
allowedFormats={"jpg,jpeg,png,webp"}
validationRules={{
width: "525",
height: "295"
}}
/>
<Card className="col-span-2 w-fit">
<CardContent className="pt-6 ">
<div className="flex items-center gap-4">
<Skeleton className={cn('h-[125px] w-[250px] rounded-xl', data.inverted ? 'order-2' : 'order-1')} />
<div className={cn('space-y-2', data.inverted ? 'order-1' : 'order-2')}>
<Skeleton className="h-4 w-[250px]" />
<Skeleton className="h-4 w-[200px]" />
<Skeleton className="h-4 w-[300px]" />
<Skeleton className="h-4 w-[290px]" />
</div>
</div>
</CardContent>
</Card>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_content")}
@ -306,6 +331,94 @@ export default function Form({
description={useTrans("back.form_subtitle_content")}
className="gap-4"
>
<div className="grid sm:grid-cols-2 gap-4 col-span-2 gap-4">
<div className="flex items-center justify-between gap-2 col-span-1">
<div className="flex items-center gap-2">
<small>Image</small>
<SimpleSwitch
name={"inputType"}
checked={isGif}
setData={(_, value) => {
setIsGif(value)
reset('picture')
setDynamicKey(Date.now())
}}
/>
<small>Gif</small>
</div>
{model && model.picture && (
<BtnOptionnalLinkWithTooltip
variant={'secondary'}
onClick={refreshFileFromDb}
content={
<RefreshCw />
}
tooltipContent="Remettre à l'état d'origine"
/>
)}
</div>
</div>
<div className="grid sm:grid-cols-2 gap-4 col-span-2 gap-4">
<ImageCropperWrapper
key={dynamicKey}
fileName="picture"
modelRoute="news"
name={"picture"}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.attributes.image"),
},
choice: 1,
}),
).ucFirst().value()}
setData={setData}
reset={reset}
value={data.picture}
required={false}
maxFileSize={"5120"}
allowedFormats={isGif ? 'gif' : "jpg,jpeg,png,webp"}
validationRules={isGif ? null : {
width: "525",
height: "295"
}}
inputType={isGif ? enumDynamicFieldTypes.file.value : enumDynamicFieldTypes.image.value}
/>
<div></div>
</div>
<div className="grid sm:grid-cols-2 col-span-2 gap-4">
<SimpleString
name="picture_alt"
required={false}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.image_alt"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.picture_alt ?? ""}
setData={setData}
/>
<SimpleString
name="picture_title"
required={false}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.image_title"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
value={data.picture_title ?? ""}
setData={setData}
/>
</div>
<SimpleWysiwyg
name={"content"}
model="News"
@ -342,6 +455,19 @@ export default function Form({
options={options}
/>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_additional_files")}
icon={<BookText className="mr-1" />}
description={useTrans("back.form_subtitle_additional_files")}
className="sm:grid-cols-2 gap-4"
>
<SimpleVimeoId
name="vimeo_id"
setData={setData}
value={data.vimeo_id}
required={false}
/>
</FieldsetWrapper>
<div className="text-center">
<SubmitButton />
</div>

View file

@ -112,7 +112,9 @@ type NewsModel = {
title: TranslationField;
slug: TranslationField;
content: TranslationField;
inverted: boolean;
status: number;
vimeo_id: string | null;
picture: string | null;
picture_alt: TranslationField | null;
picture_title: TranslationField | null;
@ -143,6 +145,7 @@ type Model =
| UserModel
| PageConfigModel
| DynamicPageModel
| NewsModel
| ActivityLogModel;
// Common policy type.
@ -228,6 +231,17 @@ type LaravelEnum = Record<
{ label: string; name: string; value: number }
>;
// For Input file type
type FileValidation = {
validationRules?: {
width: string | null;
height: string | null;
} | null;
maxFileSize: string | null;
allowedFormats: string | null;
inputType?: number;
}
// Theme type.
type Theme = "dark" | "light";

View file

@ -22,30 +22,30 @@ export default defineConfig({
refresh: true,
}),
react(),
debugMode &&
stylelint({
dev: false,
build: true,
cache: false,
include: ['**/resources/**/*.scss', '**/resources/**/*.css'],
exclude: ['node_modules', 'vendor', 'packages'],
lintOnStart: true,
emitError: true,
emitWarning: true,
emitErrorAsWarning: false,
emitWarningAsError: true,
}),
debugMode &&
eslint({
cache: false,
include: ['resources/ts/**/*.{ts,tsx}'],
exclude: ['node_modules', 'vendor', 'packages'],
lintOnStart: true,
emitWarning: true,
emitError: true,
failOnWarning: false,
failOnError: true,
}),
// debugMode &&
// stylelint({
// dev: false,
// build: true,
// cache: false,
// include: ['**/resources/**/*.scss', '**/resources/**/*.css'],
// exclude: ['node_modules', 'vendor', 'packages'],
// lintOnStart: true,
// emitError: true,
// emitWarning: true,
// emitErrorAsWarning: false,
// emitWarningAsError: true,
// }),
// debugMode &&
// eslint({
// cache: false,
// include: ['resources/ts/**/*.{ts,tsx}'],
// exclude: ['node_modules', 'vendor', 'packages'],
// lintOnStart: true,
// emitWarning: true,
// emitError: true,
// failOnWarning: false,
// failOnError: true,
// }),
copy({
targets: [
{