diff --git a/app/Enums/DynamicFieldTypes.php b/app/Enums/DynamicFieldTypes.php index b70c546b..c06fbe63 100644 --- a/app/Enums/DynamicFieldTypes.php +++ b/app/Enums/DynamicFieldTypes.php @@ -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 ]; } diff --git a/app/Http/Requests/Back/News/StoreNewsRequest.php b/app/Http/Requests/Back/News/StoreNewsRequest.php index e9bf4292..62a49aa1 100644 --- a/app/Http/Requests/Back/News/StoreNewsRequest.php +++ b/app/Http/Requests/Back/News/StoreNewsRequest.php @@ -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()] ]; } diff --git a/app/Models/News.php b/app/Models/News.php index ce5a881b..8110c721 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -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' ]; /** diff --git a/app/Traits/Requests/HasInertiaPicture.php b/app/Traits/Requests/HasInertiaPicture.php index 64ca2159..42f95ec1 100644 --- a/app/Traits/Requests/HasInertiaPicture.php +++ b/app/Traits/Requests/HasInertiaPicture.php @@ -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)] diff --git a/database/migrations/2025_11_17_163811_alter_news_fields_add_side_table.php b/database/migrations/2025_11_17_163811_alter_news_fields_add_side_table.php new file mode 100644 index 00000000..fad6d19e --- /dev/null +++ b/database/migrations/2025_11_17_163811_alter_news_fields_add_side_table.php @@ -0,0 +1,40 @@ +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'); + }); + } +}; diff --git a/lang/en/back.php b/lang/en/back.php index edcb3c33..98441489 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -1,6 +1,8 @@ "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 :appName !", @@ -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", diff --git a/lang/en/enums.php b/lang/en/enums.php index d0f0d6e0..bbccd0d0 100644 --- a/lang/en/enums.php +++ b/lang/en/enums.php @@ -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' => [ diff --git a/lang/en/validation.php b/lang/en/validation.php index c5406664..0394d48e 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -256,6 +256,8 @@ return [ "contactCount" => [ "type" => "form type", "submissions" => "count of soumissions" - ] + ], + "vimeo_id" => "VIMEO ID", + "youtube_id" => "YOUTUBE ID" ], ]; diff --git a/lang/fr/back.php b/lang/fr/back.php index 488e1b03..9354654c 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -1,118 +1,126 @@ "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 :appName !", - "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 PRODUCTION. + "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 PRODUCTION. 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 back-office 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 back-office de votre site internet :appName.", - "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" => "UWIL vous accompagne dans votre + "dashboard_paragraph_3" => "UWIL vous accompagne dans votre conception ainsi que la réalisation de vos projets actuels et futurs.", - "dashboard_paragraph_4" => "N'hésitez pas à utiliser nos outils UWIL by LDC :", - "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 UWIL by LDC :", + "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", diff --git a/lang/fr/enums.php b/lang/fr/enums.php index 715423bf..0ee53f01 100644 --- a/lang/fr/enums.php +++ b/lang/fr/enums.php @@ -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' => [ diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 01afb0d1..d7ca3013 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -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" ], ]; diff --git a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx index 2caf3451..8bc59f2c 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx @@ -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"; diff --git a/resources/ts/back/Components/GoToFrontView.tsx b/resources/ts/back/Components/GoToFrontView.tsx new file mode 100644 index 00000000..36b9d291 --- /dev/null +++ b/resources/ts/back/Components/GoToFrontView.tsx @@ -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 ( + + {model && isAvailable ? ( + <> + {str(useTrans('back.access_to_front_page')).ucFirst().value()} + + + + {definitivePath}{" "} + + + + + {anchorAccessPage} + + + + ) : ( + <> + {str(useTrans("back.access_to_front_page_when_published")).ucFirst().value()}: + + {definitivePath} + + + )} + + ) +} + + +export default GoToFrontView; diff --git a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx new file mode 100644 index 00000000..5bf7cf62 --- /dev/null +++ b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx @@ -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(false); + const finalFileName = `${fileName}.png`; + console.log(value) + const [selectedFile, setSelectedFile] = useState( + () => { + // 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>>({ + "image/*": [], + }); + const [extensions, setExtensions] = useState(); + + 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 => { + if (!allowedFormats) return {}; + + const currentExtensions = allowedFormats.split(","); + setExtensions(allowedFormats); + const mimeMap: Record = { + 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> = {}; + + 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 = {}; + 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 ( +
+ + {selectedFile ? ( +
+ {inputType === enumDynamicFieldTypes.image.value && ( + + )} + {inputType === enumDynamicFieldTypes.file.value && ( +
+
+ +

+ {str(useTrans('back.image_cropper.state_file_uploaded')).ucFirst().value()} +

+ + {selectedFile.name} + +
+
+ )} + } + onClick={() => { + setSelectedFile(null); + setData(name, null); + }} + tooltipContent={str(useTrans("back.cancel")).ucFirst().value()} + /> +
+ + ) : ( + + )} + +
+ ); +} diff --git a/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperLogic.tsx b/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperLogic.tsx index eaf59a0e..43636fdf 100644 --- a/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperLogic.tsx +++ b/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperLogic.tsx @@ -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>; - setSelectedFile: Dispatch>; 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(null); @@ -714,24 +711,6 @@ import { cn } from "@/lib/utils"; )} - - - - - - {str(useTrans("back.cancel")).ucFirst().value()} - - {useTrans("back.image_cropper.modale_title")} diff --git a/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperWrapper.tsx b/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperWrapper.tsx deleted file mode 100644 index 81c4d183..00000000 --- a/resources/ts/back/Components/Inputs/ImageCropper/ImageCropperWrapper.tsx +++ /dev/null @@ -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(false); - const finalFileName = `${fileName}.png`; - - const [selectedFile, setSelectedFile] = useState( - () => { - // 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>>({ - "image/*": [], - }); - const [extensions, setExtensions] = useState(); - - 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 => { - if (!allowedFormats) return {}; - - const currentExtensions = allowedFormats.split(","); - setExtensions(allowedFormats); - const mimeMap: Record = { - 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> = {}; - - 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 = {}; - 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 ( -
- - {selectedFile ? ( - - ) : ( - - )} - -
- ); -} diff --git a/resources/ts/back/Components/Inputs/SimpleString.tsx b/resources/ts/back/Components/Inputs/SimpleString.tsx index 45da2386..8923828a 100644 --- a/resources/ts/back/Components/Inputs/SimpleString.tsx +++ b/resources/ts/back/Components/Inputs/SimpleString.tsx @@ -23,6 +23,7 @@ type SimpleStringProps = { wordCounter?: boolean; required?: boolean; disabled?: boolean; + /** Pattern is regex without antislash */ pattern?: string; checkVisibility?: boolean; parentErrors?: Record | null, diff --git a/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx b/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx new file mode 100644 index 00000000..a45721ce --- /dev/null +++ b/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx @@ -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 | 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 ( + + ); +} diff --git a/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx b/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx new file mode 100644 index 00000000..44bcb648 --- /dev/null +++ b/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx @@ -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 | 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 ( + + ); +} diff --git a/resources/ts/back/Pages/DynamicPages/Form.tsx b/resources/ts/back/Pages/DynamicPages/Form.tsx index f0b587bc..5ad36dd3 100644 --- a/resources/ts/back/Pages/DynamicPages/Form.tsx +++ b/resources/ts/back/Pages/DynamicPages/Form.tsx @@ -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} />
- - {model && - model.status === - enumDynamicPageStatus.published.value ? ( - <> - Lien de votre page: - - - - {definitivePath}{" "} - - - - - {anchorAccessPage} - - - - ) : ( - <> - Lien de votre page une fois publiée: - - {definitivePath} - - - )} - +
(false); + const [dynamicKey, setDynamicKey] = useState(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 ( + + ); + }; + + + + + return (
@@ -159,35 +207,47 @@ export default function Form({ title={useTrans("back.form_title_global")} icon={} description={useTrans("back.form_subtitle_global")} - className="sm:grid-cols-2 gap-4" + className="space-y-3" > - - + +
+ + +
+ + } - description={useTrans("back.form_subtitle_files")} + description={useTrans("back.form_subtitle_display")} className="sm:grid-cols-2 gap-4" > - - - + + +
+ +
+ + + + +
+
+
+
+
+
+
+ Image + { + setIsGif(value) + reset('picture') + setDynamicKey(Date.now()) + }} + /> + Gif +
+ {model && model.picture && ( + + } + tooltipContent="Remettre à l'état d'origine" + /> + )} +
+
+
+ +
+
+ +
+ + +
+ } + description={useTrans("back.form_subtitle_additional_files")} + className="sm:grid-cols-2 gap-4" + > + +
diff --git a/resources/ts/back/types/global.d.ts b/resources/ts/back/types/global.d.ts index 23cb2258..e63e6ab4 100644 --- a/resources/ts/back/types/global.d.ts +++ b/resources/ts/back/types/global.d.ts @@ -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"; diff --git a/vite.config.ts b/vite.config.ts index e481b949..e1b3a03a 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -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: [ {