diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 7dee6d3b..5411e55a 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -66,5 +66,10 @@ module.exports = { }, ], 'prettier/prettier': 'error', + "no-console": [ + "warn", { + allow: ["warn", "error"], + }, + ], }, } diff --git a/app/Casts/LocalDateTime.php b/app/Casts/LocalDateTime.php index 7b3d7b06..d025efae 100644 --- a/app/Casts/LocalDateTime.php +++ b/app/Casts/LocalDateTime.php @@ -2,20 +2,43 @@ namespace App\Casts; -use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Carbon\Carbon; +use Illuminate\Contracts\Database\Eloquent\CastsAttributes; +use Illuminate\Database\Eloquent\Model; class LocalDateTime implements CastsAttributes { - public function get($model, string $key, $value, array $attributes) + /** + * Get local date time. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param string|integer|null $value + * @param array $attributes + * @return \Carbon\Carbon|null + * @phpcs:disable + */ + public function get(Model $model, string $key, string|int|null $value, array $attributes): ?\Carbon\Carbon { + // phpcs:enable return $value ? Carbon::parse($value)->setTimezone(config('app.timezone')) : null; } - public function set($model, string $key, $value, array $attributes) + /** + * Set the locale date time. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param string|integer|null $value + * @param array $attributes + * @return \Carbon\Carbon|null + * @phpcs:disable + */ + public function set(Model $model, string $key, string|int|null $value, array $attributes): ?\Carbon\Carbon { + // phpcs:enable return $value ? Carbon::parse($value, config('app.timezone'))->setTimezone('UTC') : null; diff --git a/app/Console/Commands/UpdateMeilisearch.php b/app/Console/Commands/UpdateMeilisearch.php deleted file mode 100644 index ba7ec1c6..00000000 --- a/app/Console/Commands/UpdateMeilisearch.php +++ /dev/null @@ -1,44 +0,0 @@ -info("Import {$locale}..."); - app()->setLocale($locale); - - foreach ($models as $model) { - $this->call('scout:import', ['model' => $model]); - } - } - } -} diff --git a/app/Enums/Contact/BreedType.php b/app/Enums/Contact/BreedType.php index d7bd0869..9a81e575 100644 --- a/app/Enums/Contact/BreedType.php +++ b/app/Enums/Contact/BreedType.php @@ -24,5 +24,4 @@ enum BreedType: int self::chickenEggs->name => 'enums.breedType.chickenEggs', self::other->name => 'enums.breedType.other' ]; - } diff --git a/app/Enums/Contact/ContactFormType.php b/app/Enums/Contact/ContactFormType.php index 68aa86e1..40fe725f 100644 --- a/app/Enums/Contact/ContactFormType.php +++ b/app/Enums/Contact/ContactFormType.php @@ -132,10 +132,13 @@ enum ContactFormType: int /** * Get the slug for each type * + * @param string|null $locale * @return string|null + * @phpcs:disable Generic.Metrics.CyclomaticComplexity */ public function slug(?string $locale = null): ?string { + // phpcs:enable return match ($this) { self::collaborator => Lang::get('enums.contactFormType.collaborator.slug', [], $locale), self::breeder => Lang::get('enums.contactFormType.breeder.slug', [], $locale), @@ -152,6 +155,10 @@ enum ContactFormType: int /** * Check if current lang slug match in specific lang slug + * + * @param string $slug + * @param string $locale + * @return self */ public static function fromSlug(string $slug, string $locale): ?self { @@ -188,7 +195,8 @@ enum ContactFormType: int return match (true) { in_array($this, $commonRoutes, true) => route('front.contact.show', ['slug' => $this->slug()]), $this === self::professional => null, - $this === self::press => RouteHelper::routeNameChecker('front.dynamic-pages.espace-presse') . '#page-press-form', + $this === self::press => + RouteHelper::routeNameChecker('front.dynamic-pages.espace-presse') . '#page-press-form', default => null, }; } @@ -240,38 +248,41 @@ enum ContactFormType: int * Get the slug for each type * * @return array + * @phpcs:disable Generic.Metrics.CyclomaticComplexity */ public function getContactMails(): ?array { + // phpcs:enable return match ($this) { self::collaborator => [], self::breeder => [ 'marie-charlotte.garnier@ldc.fr', - 'dylan.chevalier@ldc.fr' + 'dylan.chevalier@ldc.fr', ], self::professional => null, self::restauration => [ - 'rhd@ldc.fr' + 'rhd@ldc.fr', ], self::export => [ 'alexis.lambert@ldc.fr', - 'bruno.lafon@ldc.fr' + 'bruno.lafon@ldc.fr', ], self::finance => [ 'david.eluaud@ldc.fr', - 'malaury.offe@ldc.fr' + 'malaury.offe@ldc.fr', ], self::commitments => [ - 'claire-marie.gesland@ldc.fr' + 'claire-marie.gesland@ldc.fr', ], self::product => [], self::info => [ 'blandine.durand-gratian@ldc.fr', - 'malaury.offe@ldc.fr' + 'malaury.offe@ldc.fr', ], self::press => [ - 'communicationgroupe@ldc.fr' + 'communicationgroupe@ldc.fr', ], - }; + // phpcs:ignore Squiz.Commenting.InlineComment + }; //end match } } diff --git a/app/Enums/Contact/CustomerAskingType.php b/app/Enums/Contact/CustomerAskingType.php index 613e3a43..ac98b674 100644 --- a/app/Enums/Contact/CustomerAskingType.php +++ b/app/Enums/Contact/CustomerAskingType.php @@ -26,5 +26,4 @@ enum CustomerAskingType: int self::gastronomy->name => 'enums.customerAskingType.gastronomy', self::other->name => 'enums.customerAskingType.other', ]; - } diff --git a/app/Enums/Contact/PressType.php b/app/Enums/Contact/PressType.php index a1f0b825..f90883f9 100644 --- a/app/Enums/Contact/PressType.php +++ b/app/Enums/Contact/PressType.php @@ -26,5 +26,4 @@ enum PressType: int self::photo->name => 'enums.pressType.photo', self::other->name => 'enums.pressType.other' ]; - } diff --git a/app/Enums/DynamicFieldTypes.php b/app/Enums/DynamicFieldTypes.php index b3039fcc..c65d40bb 100644 --- a/app/Enums/DynamicFieldTypes.php +++ b/app/Enums/DynamicFieldTypes.php @@ -26,8 +26,8 @@ enum DynamicFieldTypes: int case model = 15; case staticroute = 16; - // Specific inputs - case position = 101; + // Specific inputs. + case position = 101; /** * Labels definition. @@ -52,8 +52,8 @@ enum DynamicFieldTypes: int self::model->name => 'enums.dynamic-field-types.model', self::staticroute->name => 'enums.dynamic-field-types.staticroute', - // Specific inputs - self::position->name => 'enums.dynamic-field-types.position', + // Specific inputs. + self::position->name => 'enums.dynamic-field-types.position', ]; /** @@ -75,10 +75,10 @@ enum DynamicFieldTypes: int self::date->name => 'required|date', self::color->name => 'required|string|hex_color', self::model->name => 'required|numeric|exists:dynamic_pages,id', - self::staticroute->name => 'required|numeric|between:1,10', + self::staticroute->name => 'required|numeric|between:1,99', - // Specific inputs - self::position->name => 'required|numeric|between:1,5', + // Specific inputs. + self::position->name => 'required|numeric|between:1,5', ]; /** @@ -114,7 +114,7 @@ enum DynamicFieldTypes: int self::model->name => false, self::staticroute->name => false, - // Specific inputs - self::position->name => false, + // Specific inputs. + self::position->name => false, ]; } diff --git a/app/Enums/ModelsList.php b/app/Enums/ModelsList.php index 65042195..3551d800 100644 --- a/app/Enums/ModelsList.php +++ b/app/Enums/ModelsList.php @@ -17,8 +17,7 @@ enum ModelsList: int case documents = 3; /** - * Labels definition. - * Key of the translation. + * Labels definition (key of the translation). * etc: enums.model-list.dynamic-page etc... * * @phpstan-ignore-next-line @@ -30,7 +29,6 @@ enum ModelsList: int ]; /** - * Validations definition. * Target field used to present the resource. * ex: title, label, name etc... */ @@ -41,7 +39,7 @@ enum ModelsList: int ]; /** - * Get validation. + * Get target field. * * @return string */ diff --git a/app/Enums/News/NewsYearsEnum.php b/app/Enums/News/NewsYearsEnum.php index cfa7afad..5c69b8f6 100644 --- a/app/Enums/News/NewsYearsEnum.php +++ b/app/Enums/News/NewsYearsEnum.php @@ -35,7 +35,7 @@ enum NewsYearsEnum: int /** * Get the years to display using the app locale * - * @return bool + * @return boolean */ public function yearsWithLocal(): bool { diff --git a/app/Enums/OrdersEnum.php b/app/Enums/OrdersEnum.php index 4930a075..70e1618d 100644 --- a/app/Enums/OrdersEnum.php +++ b/app/Enums/OrdersEnum.php @@ -25,7 +25,7 @@ enum OrdersEnum: int /** * Get the orders to display using the app locale * - * @return bool + * @return boolean */ public function ordersWithLocal(): bool { @@ -39,6 +39,9 @@ enum OrdersEnum: int /** * Optional factory from label. + * + * @param string $name + * @return self */ public static function makeFromLabel(string $name): ?self { diff --git a/app/Enums/StaticRoutes.php b/app/Enums/StaticRoutesEnum.php similarity index 77% rename from app/Enums/StaticRoutes.php rename to app/Enums/StaticRoutesEnum.php index 26f632e9..3ec90662 100644 --- a/app/Enums/StaticRoutes.php +++ b/app/Enums/StaticRoutesEnum.php @@ -5,11 +5,11 @@ namespace App\Enums; use App\Enums\Contact\ContactFormType; use Uwil\LaravelCommon\Traits\Enums\BaseEnum; -enum StaticRoutes: int +enum StaticRoutesEnum: int { use BaseEnum; - // Set all cases for each static routes. + // Set all cases for each static routes. case collaborator = 1; case breeder = 2; case professional = 3; @@ -20,22 +20,21 @@ enum StaticRoutes: int case product = 8; case info = 9; case press = 10; - // case google = 11; + case search = 11; /** * Get array of each route with his matching value. - * @param callable $callback * + * @param callable|null $callback * @return array */ public static function getRoutes(?callable $callback = null): array { - $dataKeyValue = array_merge(ContactFormType::getLabelisedRoutes(), [ - // self::google->name => (object) [ - // 'label' => 'Google', - // 'route' => 'https://google.com', - // ] + self::search->name => (object) [ + 'label' => trans('front.search.title'), + 'route' => '/recherche?texte=LDC', + ] ]); return collect($dataKeyValue) ->reject(fn($item) => is_null($item->label) || is_null($item->route)) @@ -55,12 +54,12 @@ enum StaticRoutes: int } /** - * Get the url of a given enum - * e.g : \App\Enums\StaticRoutes::make(1)->getRoute(); + * Get the url of a given enum value. * + * @param integer $value * @return string|null */ - public static function getRoute($value): ?string + public static function getRoute(int $value): ?string { $collect = collect(self::getRoutes(fn ($route) => $route->value == $value)); return $collect->isEmpty() ? null : $collect->first()->route; diff --git a/app/Enums/YearsEnum.php b/app/Enums/YearsEnum.php index 2165a1f4..1e3c74e5 100644 --- a/app/Enums/YearsEnum.php +++ b/app/Enums/YearsEnum.php @@ -45,6 +45,9 @@ enum YearsEnum: int /** * Optional factory from label. + * + * @param string $label + * @return self */ public static function makeFromLabel(string $label): ?self { diff --git a/app/Helpers/BladeComponentHelper.php b/app/Helpers/BladeComponentHelper.php deleted file mode 100644 index c51e41f7..00000000 --- a/app/Helpers/BladeComponentHelper.php +++ /dev/null @@ -1,18 +0,0 @@ -sortQuery($query); - } - - public function runPaginate($query) - { - return $this->paginate($query); - } -} diff --git a/app/Helpers/DocumentHelper.php b/app/Helpers/DocumentHelper.php index 5d26309c..34f5d303 100644 --- a/app/Helpers/DocumentHelper.php +++ b/app/Helpers/DocumentHelper.php @@ -3,7 +3,7 @@ namespace App\Helpers; use App\Enums\Document\DocumentStatusEnum; -use App\Models\Document; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; class DocumentHelper @@ -22,8 +22,8 @@ class DocumentHelper * * HTML entities (e.g. `&`) are automatically decoded. * - * @param string|null $issuIframe Raw Issuu iframe HTML or embed URL - * @return string|null The normalized Issuu embed URL, or null if none is found + * @param string|null $issuIframe Raw Issuu iframe HTML or embed URL. + * @return string|null The normalized Issuu embed URL, or null if none is found. */ public static function extractDocumentFromIssuIframe(?string $issuIframe): ?string { @@ -51,14 +51,14 @@ class DocumentHelper /** * Return a document query with all the request filters applied * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query - * @return \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder $query */ - public static function getQueryWithFilters(Request $request, $query): \Illuminate\Database\Eloquent\Builder + public static function getQueryWithFilters(Request $request, Builder $query): \Illuminate\Database\Eloquent\Builder { $statusFilter = $request->status; - if($statusFilter) { + if ($statusFilter) { $query->where('status', DocumentStatusEnum::make($statusFilter, 'name')->value); } diff --git a/app/Helpers/DynamicPageHelper.php b/app/Helpers/DynamicPageHelper.php index 3ad98918..66de6249 100644 --- a/app/Helpers/DynamicPageHelper.php +++ b/app/Helpers/DynamicPageHelper.php @@ -30,9 +30,8 @@ class DynamicPageHelper $originalContent = $model->getOriginal('content'); $availableLocales = array_keys(config('laravellocalization.supportedLocales', ['fr' => "Français"])); - $localesToProcess = ($forceDeleteImage) - ? $availableLocales // on delete it's all the locales - : [$locale]; + // On delete it's all the locales. + $localesToProcess = ($forceDeleteImage) ? $availableLocales : [$locale]; foreach ($localesToProcess as $lang) { if (isset($originalContent[$lang])) { @@ -65,14 +64,14 @@ class DynamicPageHelper array $newContent, bool $forceDeleteImage ): void { - $prefix = DynamicFieldTypes::image->name . '_'; + $prefix = DynamicFieldTypes::image->name . '_'; $oldImages = static::extractImagePaths($oldContent, $prefix); $newImages = static::extractImagePaths($newContent, $prefix); - $allPaths = collect(array_keys($oldImages)) + $allPaths = collect(array_keys($oldImages)) ->merge(array_keys($newImages)) ->unique(); - foreach ($allPaths as $key) { + foreach ($allPaths as $key) { $old = $oldImages[$key] ?? null; $new = $newImages[$key] ?? null; // Case n°1 : Same values when force delete. @@ -103,6 +102,15 @@ class DynamicPageHelper } } //end foreach } + + /** + * Extract image path for fields with image key prefix. + * + * @param array $array + * @param string $prefix + * @param string $path + * @return array + */ protected static function extractImagePaths( array $array, string $prefix, @@ -128,8 +136,8 @@ class DynamicPageHelper /** * Remove imgs from wysiwygs. * - * @param array $oldContent - * @param array $newContent + * @param array $oldContent + * @param array $newContent * @param boolean $forceDeleteImage * @return void */ @@ -171,11 +179,11 @@ class DynamicPageHelper } /** - * Get all segments url for dynamic pages + * Get all segments url for dynamic pages. * - * @param DynamicPage $page - * @param Collection $pages - * @param string $locale + * @param \App\Models\DynamicPage $page + * @param \Illuminate\Support\Collection $pages + * @param string $locale * @return array|null */ public static function getAllDynamicPageSegments(DynamicPage $page, Collection $pages, string $locale): ?array @@ -185,10 +193,10 @@ class DynamicPageHelper // Browse all relationships. while ($parentId) { - /** @var \App\Models\DynamicPage|null $parentPage */ + /** @var \App\Models\DynamicPage|null $parent */ $parent = $pages->find($parentId); - if (! $parent || !$parent->status->equals(PageStatusEnum::published)) { + if (!$parent || !$parent->status->equals(PageStatusEnum::published)) { return null; } diff --git a/app/Helpers/FinancePageChartHelper.php b/app/Helpers/FinancePageChartHelper.php index ce9aac64..cf36ed63 100644 --- a/app/Helpers/FinancePageChartHelper.php +++ b/app/Helpers/FinancePageChartHelper.php @@ -44,7 +44,7 @@ class FinancePageChartHelper */ public static function getBilanSimplify(array $item): array { - $active = $item['list_bilan_simplify_active_values'] ?? []; + $active = $item['list_bilan_simplify_active_values'] ?? []; $passive = $item['list_bilan_simplify_passive_values'] ?? []; $datasets = []; @@ -79,7 +79,7 @@ class FinancePageChartHelper */ public static function getAutofinancement(array $item): array { - $labels = []; + $labels = []; $valuesCPT = []; $valuesIVT = []; @@ -103,7 +103,7 @@ class FinancePageChartHelper * Routes chart building based on chart type. * * @param string $type Chart identifier. - * @param array $data Raw chart data. + * @param array $data Raw chart data. * @return array Chart.js-compatible configuration. */ public static function buildChart(string $type, array $data): array diff --git a/app/Helpers/RouteHelper.php b/app/Helpers/RouteHelper.php index 59b98063..52f08da9 100644 --- a/app/Helpers/RouteHelper.php +++ b/app/Helpers/RouteHelper.php @@ -34,7 +34,7 @@ class RouteHelper extends Controller } /** - * Return true or false, if the passed route is actually active + * Return true or false, if the passed route is actually active. * * @param string $routeName * @param mixed $locale @@ -50,25 +50,25 @@ class RouteHelper extends Controller } /** - * Get the localized url in the langage switcher + * Get the localized url in the langage switcher. * - * @param string $localeCode LocaleCode from LaravelLocalization::getSupportedLocales() + * @param string $localeCode LocaleCode from LaravelLocalization::getSupportedLocales(). * @return string */ public static function getLocalizedUrl(string $localeCode): string { - $route = request()->route(); - if (! $route) { + $route = request()->route(); + if (!$route) { return LaravelLocalization::getLocalizedURL($localeCode); } return self::resolve( - self::getDynamicPageLocalizedURL($route, $localeCode), - self::getContactShowLocalizedURL($route, $localeCode), + self::getDynamicPageLocalizedUrl($route, $localeCode), + self::getContactShowLocalizedUrl($route, $localeCode), ) ?? LaravelLocalization::getLocalizedURL($localeCode, null, [], false); } /** - * Resolve the url to be returned for the localized switcher + * Resolve the url to be returned for the localized switcher. * * @param string|null ...$urls * @return string|null @@ -84,13 +84,13 @@ class RouteHelper extends Controller } /** - * Return the localized url for contact page show + * Return the localized url for contact page show. * - * @param Route $route - * @param string $localeCode + * @param \Illuminate\Routing\Route $route + * @param string $localeCode * @return string|false|null */ - private static function getContactShowLocalizedURL(Route $route, string $localeCode) + private static function getContactShowLocalizedUrl(Route $route, string $localeCode) { $contactPage = $route->parameter('contactPage'); @@ -101,11 +101,12 @@ class RouteHelper extends Controller [], false ); - $parsed = parse_url($localizedUrl); - if (! isset($parsed['path'])) { + $parsed = parse_url($localizedUrl); + if (!isset($parsed['path'])) { return $localizedUrl; } - $segments = explode('/', trim($parsed['path'], '/')); + + $segments = explode('/', trim($parsed['path'], '/')); $currentSlug = end($segments); $enum = ContactFormType::fromSlug( @@ -121,19 +122,19 @@ class RouteHelper extends Controller } } return $localizedUrl; - } + } //end if } /** - * Return the localized url for all dynamic pages + * Return the localized url for all dynamic pages. * * @param \Illuminate\Routing\Route $route - * @param string $localeCode + * @param string $localeCode * @return string|false|null */ - private static function getDynamicPageLocalizedURL(Route $route, string $localeCode) + private static function getDynamicPageLocalizedUrl(Route $route, string $localeCode): string|false|null { - /** @var DynamicPage|null $page */ + /** @var \App\Models\DynamicPage|null $dynamicPage */ $dynamicPage = $route->parameter('dynamicPage'); if ($dynamicPage instanceof DynamicPage) { $path = $dynamicPage->getLocalizedPath($localeCode); diff --git a/app/Helpers/TranslationHelper.php b/app/Helpers/TranslationHelper.php index 1b6b3852..e0f74924 100644 --- a/app/Helpers/TranslationHelper.php +++ b/app/Helpers/TranslationHelper.php @@ -35,7 +35,7 @@ class TranslationHelper * Assert fallback locale translation is present. * * @param \App\Contracts\TranslatableModel $model - * @param array $excludeKeys key of the model we need to keep nullable + * @param array $excludeKeys Key of the model we need to keep nullable. * @return void * @throws \Illuminate\Validation\ValidationException Translations missing. */ @@ -43,7 +43,7 @@ class TranslationHelper { $localeFallback = config('app.fallback_locale'); $missingTranslations = []; - $excludeFields = array_merge(['slug'], $excludeKeys); + $excludeFields = array_merge(['slug'], $excludeKeys); foreach (Arr::except($model->getTranslations(), $excludeFields) as $key => $value) { if (!is_null($model->{$key}) && !$model->hasTranslation($key, $localeFallback)) { $validationTranslations = self::getCachedTranslations()['validation']; diff --git a/app/Http/Controllers/Back/CompanyActivityController.php b/app/Http/Controllers/Back/CompanyActivityController.php index efc8ed17..5b5075d5 100644 --- a/app/Http/Controllers/Back/CompanyActivityController.php +++ b/app/Http/Controllers/Back/CompanyActivityController.php @@ -15,7 +15,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class CompanyActivityController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "company-activities"; /** @@ -144,8 +144,10 @@ class CompanyActivityController extends Controller * @param \App\Models\CompanyActivity $company_activity * @return \Illuminate\Http\RedirectResponse */ - public function update(UpdateCompanyActivityRequest $request, CompanyActivity $company_activity): \Illuminate\Http\RedirectResponse - { + public function update( + UpdateCompanyActivityRequest $request, + CompanyActivity $company_activity, + ): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $company_activity) { $company_activity->fill($request->validated()); diff --git a/app/Http/Controllers/Back/CompanyController.php b/app/Http/Controllers/Back/CompanyController.php index a29b7e05..251ecada 100644 --- a/app/Http/Controllers/Back/CompanyController.php +++ b/app/Http/Controllers/Back/CompanyController.php @@ -16,7 +16,7 @@ use Uwil\LaravelCommon\Controllers\Controller; class CompanyController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "companies"; /** diff --git a/app/Http/Controllers/Back/CompanySectorController.php b/app/Http/Controllers/Back/CompanySectorController.php index f22bdc9f..e984e691 100644 --- a/app/Http/Controllers/Back/CompanySectorController.php +++ b/app/Http/Controllers/Back/CompanySectorController.php @@ -15,7 +15,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class CompanySectorController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "company-sectors"; /** @@ -92,8 +92,10 @@ class CompanySectorController extends Controller */ public function show(CompanySector $company_sector): \Inertia\Response { + $companies = $company_sector->companies()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('CompanySectors/Show', [ 'data' => CommonResource::make($company_sector), + 'companies' => CommonResource::collection($companies), 'modelName' => $this->modelName, ]); } @@ -144,8 +146,10 @@ class CompanySectorController extends Controller * @param \App\Models\CompanySector $company_sector * @return \Illuminate\Http\RedirectResponse */ - public function update(UpdateCompanySectorRequest $request, CompanySector $company_sector): \Illuminate\Http\RedirectResponse - { + public function update( + UpdateCompanySectorRequest $request, + CompanySector $company_sector, + ): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $company_sector) { $company_sector->fill($request->validated()); diff --git a/app/Http/Controllers/Back/ContactController.php b/app/Http/Controllers/Back/ContactController.php index cf1d71af..fa4002b8 100644 --- a/app/Http/Controllers/Back/ContactController.php +++ b/app/Http/Controllers/Back/ContactController.php @@ -10,8 +10,14 @@ use Uwil\LaravelCommon\Controllers\Controller; class ContactController extends Controller { + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "contact-counts"; + /** + * Display a listing of the resource. + * + * @return \Inertia\Response + */ public function index(): \Inertia\Response { $query = ContactCount::query(); diff --git a/app/Http/Controllers/Back/DocumentCategoryController.php b/app/Http/Controllers/Back/DocumentCategoryController.php index a0283d4a..d4a15662 100644 --- a/app/Http/Controllers/Back/DocumentCategoryController.php +++ b/app/Http/Controllers/Back/DocumentCategoryController.php @@ -14,7 +14,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class DocumentCategoryController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "document-categories"; /** @@ -132,11 +132,13 @@ class DocumentCategoryController extends Controller * Update the specified resource. * * @param \App\Http\Requests\Back\News\UpdateDocumentCategoryRequest $request - * @param \App\Models\DocumentCategory $document_category + * @param \App\Models\DocumentCategory $document_category * @return \Illuminate\Http\RedirectResponse */ - public function update(UpdateDocumentCategoryRequest $request, DocumentCategory $document_category): \Illuminate\Http\RedirectResponse - { + public function update( + UpdateDocumentCategoryRequest $request, + DocumentCategory $document_category, + ): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $document_category) { $document_category->fill($request->validated()); if ($document_category->saveOrFail()) { diff --git a/app/Http/Controllers/Back/DocumentController.php b/app/Http/Controllers/Back/DocumentController.php index 5eaad7bb..88908b5e 100644 --- a/app/Http/Controllers/Back/DocumentController.php +++ b/app/Http/Controllers/Back/DocumentController.php @@ -18,7 +18,7 @@ use Uwil\LaravelCommon\Controllers\Controller; class DocumentController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "documents"; /** @@ -62,6 +62,7 @@ class DocumentController extends Controller /** Custom pagination */ $docModels = $this->paginate($query); + return Inertia::render('Document/Index', [ 'documentsModel' => CommonResource::collection($docModels), 'searchFields' => $searchFields, @@ -144,7 +145,7 @@ class DocumentController extends Controller * Update the specified resource. * * @param \App\Http\Requests\Back\Document\UpdateDocumentRequest $request - * @param \App\Models\Document $document + * @param \App\Models\Document $document * @return \Illuminate\Http\RedirectResponse */ public function update(UpdateDocumentRequest $request, Document $document): \Illuminate\Http\RedirectResponse @@ -160,6 +161,16 @@ class DocumentController extends Controller }); } + /** + * Duplicate the specified resource. + * + * @param \App\Models\Document $document + * @return \Inertia\Response + */ + public function duplicate(Document $document): \Inertia\Response + { + return $this->create($document->replicate()); + } /** * Destroy the specified resource. diff --git a/app/Http/Controllers/Back/DocumentTagController.php b/app/Http/Controllers/Back/DocumentTagController.php index c0aa1eb0..283e0240 100644 --- a/app/Http/Controllers/Back/DocumentTagController.php +++ b/app/Http/Controllers/Back/DocumentTagController.php @@ -14,7 +14,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class DocumentTagController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "document-tags"; /** @@ -132,11 +132,13 @@ class DocumentTagController extends Controller * Update the specified resource. * * @param \App\Http\Requests\Back\News\UpdateDocumentTagRequest $request - * @param \App\Models\DocumentTag $finance_document + * @param \App\Models\DocumentTag $document_tag * @return \Illuminate\Http\RedirectResponse */ - public function update(UpdateDocumentTagRequest $request, DocumentTag $document_tag): \Illuminate\Http\RedirectResponse - { + public function update( + UpdateDocumentTagRequest $request, + DocumentTag $document_tag, + ): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $document_tag) { $document_tag->fill($request->validated()); if ($document_tag->saveOrFail()) { diff --git a/app/Http/Controllers/Back/DynamicPageController.php b/app/Http/Controllers/Back/DynamicPageController.php index 358272e8..093776f8 100644 --- a/app/Http/Controllers/Back/DynamicPageController.php +++ b/app/Http/Controllers/Back/DynamicPageController.php @@ -16,7 +16,7 @@ use Uwil\LaravelCommon\Controllers\Controller; class DynamicPageController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "dynamic-pages"; /** @@ -141,7 +141,7 @@ class DynamicPageController extends Controller { $dynamicPageModel = $dynamic_page->load(['parentPage', 'config']); $dynamicPageModels = DynamicPage::getModelsCached() - ->filter(fn ($model) => $model->getKey() !== $dynamic_page->getKey()) + ->filter(fn ($model) => $model->getKey() !== $dynamic_page->getKey()) ->values(); $pageConfigModels = PageConfig::getModelsCached(); return Inertia::render('DynamicPages/Edit', [ diff --git a/app/Http/Controllers/Back/InputsController.php b/app/Http/Controllers/Back/InputsController.php index d3d8bbd0..ab5d429b 100644 --- a/app/Http/Controllers/Back/InputsController.php +++ b/app/Http/Controllers/Back/InputsController.php @@ -43,9 +43,8 @@ class InputsController extends Controller return response()->json(['error' => 'Invalid model class'], 404); } - // Determine the field to display. - $model = new $modelClass(); + $model = new $modelClass(); $isTranslatable = method_exists($model, 'getTranslations'); $locale = app()->getLocale(); @@ -70,7 +69,7 @@ class InputsController extends Controller return filled($getValue($item)); }); - // Apply search and exclude filters + // Apply search and exclude filters. $items = $allItems ->when(!empty($validated['exclude']), function ($collection) use ($validated) { return $collection->reject(fn($item) => $item->id == $validated['exclude']); @@ -129,7 +128,7 @@ class InputsController extends Controller return response()->json([ - 'url' => $url, + 'url' => $url, 'token' => $token, ]); } @@ -138,7 +137,7 @@ class InputsController extends Controller * Get the url to access a specific resource. * * @param integer $modelId Id of the target model. - * @param integer $modelName Name of the target model. + * @param string $modelName Name of the target model. * @return string|null */ private function getAccessModel(int $modelId, string $modelName): string|null @@ -184,7 +183,8 @@ class InputsController extends Controller public function uploadFile(UploadFileRequest $request): \Illuminate\Http\JsonResponse { // Get the class of the target model and verify its existence. - $modelClass = "App\\Models\\$request->folder"; + $modelName = Str::singular($request->validated()['folder']); + $modelClass = "App\\Models\\$modelName"; if (!class_exists($modelClass)) { return response()->json(['error' => 'Invalid model class'], 404); } diff --git a/app/Http/Controllers/Back/NewsCategoryController.php b/app/Http/Controllers/Back/NewsCategoryController.php index d15e8653..d7a3f44f 100644 --- a/app/Http/Controllers/Back/NewsCategoryController.php +++ b/app/Http/Controllers/Back/NewsCategoryController.php @@ -15,7 +15,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class NewsCategoryController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "news-categories"; /** @@ -71,14 +71,14 @@ class NewsCategoryController extends Controller /** * Show the form for creating a new resource. * - * @param \App\Models\News $news_category + * @param \App\Models\NewsCategory $news_category * @return \Inertia\Response */ public function create(NewsCategory $news_category): \Inertia\Response { return Inertia::render('NewsCategory/Create', [ - 'data' => CommonResource::make($news_category), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_category), + 'modelName' => $this->modelName, ]); } @@ -92,10 +92,10 @@ class NewsCategoryController extends Controller { $news = $news_category->news()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('NewsCategory/Show', [ - 'data' => CommonResource::make($news_category), - 'news' => CommonResource::collection($news), - 'enumNewsStatus' => NewsStatusEnum::toArray(), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_category), + 'news' => CommonResource::collection($news), + 'enumNewsStatus' => NewsStatusEnum::toArray(), + 'modelName' => $this->modelName, ]); } @@ -126,8 +126,8 @@ class NewsCategoryController extends Controller public function edit(NewsCategory $news_category): \Inertia\Response { return Inertia::render('NewsCategory/Edit', [ - 'data' => CommonResource::make($news_category), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_category), + 'modelName' => $this->modelName, ]); } @@ -138,8 +138,10 @@ class NewsCategoryController extends Controller * @param \App\Models\NewsCategory $news_category * @return \Illuminate\Http\RedirectResponse */ - public function update(UpdateNewsCategoryRequest $request, NewsCategory $news_category): \Illuminate\Http\RedirectResponse - { + public function update( + UpdateNewsCategoryRequest $request, + NewsCategory $news_category, + ): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $news_category) { $news_category->fill($request->validated()); if ($news_category->saveOrFail()) { diff --git a/app/Http/Controllers/Back/NewsController.php b/app/Http/Controllers/Back/NewsController.php index 0bf341a8..c50ceb9f 100644 --- a/app/Http/Controllers/Back/NewsController.php +++ b/app/Http/Controllers/Back/NewsController.php @@ -14,7 +14,7 @@ use Uwil\LaravelCommon\Controllers\Controller; class NewsController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "news"; /** @@ -71,30 +71,30 @@ class NewsController extends Controller /** * Show the form for creating a new resource. * - * @param \App\Models\News $page_config + * @param \App\Models\News $news * @return \Inertia\Response */ public function create(News $news): \Inertia\Response { return Inertia::render('News/Create', [ - 'data' => CommonResource::make($news), - 'enumNewsStatus' => NewsStatusEnum::toArray(), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news), + 'enumNewsStatus' => NewsStatusEnum::toArray(), + 'modelName' => $this->modelName, ]); } /** * Show a specific resource. * - * @param \App\Models\PageConfig $news + * @param \App\Models\News $news * @return \Inertia\Response */ public function show(News $news): \Inertia\Response { return Inertia::render('News/Show', [ - 'data' => CommonResource::make($news->load('categories', 'tags')), - 'enumNewsStatus' => NewsStatusEnum::toArray(), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news->load('categories', 'tags')), + 'enumNewsStatus' => NewsStatusEnum::toArray(), + 'modelName' => $this->modelName, ]); } @@ -128,9 +128,9 @@ class NewsController extends Controller public function edit(News $news): \Inertia\Response { return Inertia::render('News/Edit', [ - 'data' => CommonResource::make($news->load('categories', 'tags')), - 'enumNewsStatus' => NewsStatusEnum::toArray(), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news->load('categories', 'tags')), + 'enumNewsStatus' => NewsStatusEnum::toArray(), + 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Back/NewsTagController.php b/app/Http/Controllers/Back/NewsTagController.php index 4caa4596..1d852c26 100644 --- a/app/Http/Controllers/Back/NewsTagController.php +++ b/app/Http/Controllers/Back/NewsTagController.php @@ -15,7 +15,7 @@ use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class NewsTagController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "news-tags"; /** @@ -63,22 +63,22 @@ class NewsTagController extends Controller return Inertia::render('NewsTag/Index', [ 'newsTagModels' => CommonResource::collection($newsTagModels), - 'searchFields' => $searchFields, - 'modelName' => $this->modelName, + 'searchFields' => $searchFields, + 'modelName' => $this->modelName, ]); } /** * Show the form for creating a new resource. * - * @param \App\Models\News $news_tag + * @param \App\Models\NewsTag $news_tag * @return \Inertia\Response */ public function create(NewsTag $news_tag): \Inertia\Response { return Inertia::render('NewsTag/Create', [ - 'data' => CommonResource::make($news_tag), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_tag), + 'modelName' => $this->modelName, ]); } @@ -92,10 +92,10 @@ class NewsTagController extends Controller { $news = $news_tag->news()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('NewsTag/Show', [ - 'data' => CommonResource::make($news_tag), - 'news' => CommonResource::collection($news), - 'enumNewsStatus' => NewsStatusEnum::toArray(), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_tag), + 'news' => CommonResource::collection($news), + 'enumNewsStatus' => NewsStatusEnum::toArray(), + 'modelName' => $this->modelName, ]); } @@ -126,8 +126,8 @@ class NewsTagController extends Controller public function edit(NewsTag $news_tag): \Inertia\Response { return Inertia::render('NewsTag/Edit', [ - 'data' => CommonResource::make($news_tag), - 'modelName' => $this->modelName, + 'data' => CommonResource::make($news_tag), + 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Back/PageConfigController.php b/app/Http/Controllers/Back/PageConfigController.php index 03a68fba..a903cb49 100644 --- a/app/Http/Controllers/Back/PageConfigController.php +++ b/app/Http/Controllers/Back/PageConfigController.php @@ -13,7 +13,7 @@ use Uwil\LaravelCommon\Controllers\Controller; class PageConfigController extends Controller { - /** @var string $modelName */ + /** @var string $modelName Name of the model in kebab case. */ private $modelName = "page-configs"; /** diff --git a/app/Http/Controllers/Front/ContactController.php b/app/Http/Controllers/Front/ContactController.php index cb021d32..69622479 100644 --- a/app/Http/Controllers/Front/ContactController.php +++ b/app/Http/Controllers/Front/ContactController.php @@ -5,10 +5,11 @@ namespace App\Http\Controllers\Front; use App\Enums\Contact\ContactFormType; use App\Exceptions\AbortContactMailer; use App\Http\Requests\Front\Contact\ContactRequest; -use App\Models\MailContactData; use App\Jobs\Mails\SendContactMail; use App\Models\ContactCount; +use App\Models\MailContactData; use Illuminate\Support\Facades\Log; +use Illuminate\Support\HtmlString; use LDC\LDCCRM\Enums\ApiError; use LDC\LDCCRM\Exceptions\ApiErrorException; use LDC\LDCCRM\Exceptions\CrmException; @@ -30,6 +31,7 @@ class ContactController /** * Show contact show page. * + * @param string $slug * @return \Illuminate\Contracts\View\View */ public function show(string $slug): \Illuminate\Contracts\View\View @@ -46,6 +48,7 @@ class ContactController /** * Contact send. * + * @param \App\Http\Requests\Front\Contact\ContactRequest $request * @return \Illuminate\Http\RedirectResponse */ public function send(ContactRequest $request): \Illuminate\Http\RedirectResponse @@ -77,11 +80,13 @@ class ContactController } report($e); $hasNewsletterError = true; - $newsletterMessage = trans('Une erreur est survenue lors de l\'inscription à la newsletter, merci de réessayer ultérieurement.'); + // phpcs:ignore Generic.Files.LineLength + $newsletterMessage = trans('Une erreur est survenue lors de l\'inscription à la newsletter, merci de réessayer ultérieurement.'); } catch (CrmException $e) { report($e); $hasNewsletterError = true; - $newsletterMessage = trans('Une erreur est survenue lors de l\'inscription à la newsletter, merci de réessayer ultérieurement.'); + // phpcs:ignore Generic.Files.LineLength + $newsletterMessage = trans('Une erreur est survenue lors de l\'inscription à la newsletter, merci de réessayer ultérieurement.'); } } ContactCount::updateOrInsert( @@ -90,8 +95,11 @@ class ContactController ); $contactMessage = trans('Votre message a bien été envoyé.'); - $message = $newsletterMessage ? $contactMessage. '
' . $newsletterMessage : $contactMessage; + $message = $newsletterMessage ? $contactMessage . '
' . $newsletterMessage : $contactMessage; return redirect()->back() - ->with($hasContactError || $hasNewsletterError ? 'info' : 'success', new \Illuminate\Support\HtmlString($message)); + ->with( + $hasContactError || $hasNewsletterError ? 'info' : 'success', + new HtmlString($message) + ); } } diff --git a/app/Http/Controllers/Front/NewsController.php b/app/Http/Controllers/Front/NewsController.php index 990f33ea..bb098348 100644 --- a/app/Http/Controllers/Front/NewsController.php +++ b/app/Http/Controllers/Front/NewsController.php @@ -10,6 +10,7 @@ class NewsController extends Controller /** * Show news show page. * + * @param \App\Models\News $news * @return \Illuminate\Contracts\View\View */ public function show(News $news): \Illuminate\Contracts\View\View diff --git a/app/Http/Controllers/Front/PostsController.php b/app/Http/Controllers/Front/PostsController.php index bb29cbc4..64637619 100644 --- a/app/Http/Controllers/Front/PostsController.php +++ b/app/Http/Controllers/Front/PostsController.php @@ -17,17 +17,20 @@ use Uwil\LaravelCommon\Helpers\CollectionHelper; class PostsController extends Controller { + /** @var string */ protected const DOCUMENTS = "documents"; - protected const NEWS = "news"; + + /** @var string */ + protected const NEWS = "news"; + /** * Extract unique years from date field in a collection. * - * @param \Illuminate\Support\Collection $query - * @param string $field - * + * @param \Illuminate\Support\Collection $model + * @param string $field * @return \Illuminate\Support\Collection */ - private function getUniqueYearsFromCollection(Collection $model, string $field): Collection + private function getUniqueYearsFromCollection(Collection $model, string $field): \Illuminate\Support\Collection { return $model->pluck($field) ->map(fn($date) => Carbon::parse($date)->year) @@ -41,10 +44,9 @@ class PostsController extends Controller * @param \Illuminate\Support\Collection $array1 * @param \Illuminate\Support\Collection $array2 * @param string|null $field - * * @return array */ - function getMatchingValues(Collection $array1, Collection $array2, ?string $field = null): array + private function getMatchingValues(Collection $array1, Collection $array2, ?string $field = null): array { return $array2 ->filter(fn ($item) => $array1->contains($field ? $item[$field] : $item)) @@ -57,11 +59,10 @@ class PostsController extends Controller * * If the type is "documents" the "order" filter is included * - * @param string $type - * @param string $category + * @param string $type + * @param string $category * @param \Illuminate\Database\Eloquent\Collection $publishedTags * @param \Illuminate\Database\Eloquent\Collection $model - * * @return array */ private function getFilters(string $type, string $category, Collection $publishedTags, Collection $model): array @@ -76,7 +77,6 @@ class PostsController extends Controller ]) ->values(); - $enumYears = collect(YearsEnum::toArray()) ->map(fn($year) => YearsEnum::make((int) $year->value)) ->map(fn($year) => [ @@ -98,7 +98,7 @@ class PostsController extends Controller ]) ->values(); - /** Sort displayed years */ + // Sort displayed years. $years = $this->getMatchingValues( $this->getUniqueYearsFromCollection($model, 'published_at'), $enumYears, @@ -114,32 +114,34 @@ class PostsController extends Controller } $filters[] = [ - 'title' => $type === self::DOCUMENTS ? ucfirst(__('front.news.document')) : ucfirst(__('front.news.theme')), + 'title' => $type === self::DOCUMENTS + ? ucfirst(__('front.news.document')) + : ucfirst(__('front.news.theme')), 'name' => 'tags', 'fields' => $tags, ]; - $filters[] = [ - 'title' => $type === self::DOCUMENTS ? ucfirst(__('front.news.exercise')) : ucfirst(__('front.news.year')), + 'title' => $type === self::DOCUMENTS + ? ucfirst(__('front.news.exercise')) + : ucfirst(__('front.news.year')), 'name' => 'years', 'fields' => $years, ]; - return $filters; } /** - * Returns news in JSON format filtered by category and language - * Optionally, the results can be further filtered by tags, and years + * Returns news in JSON format filtered by category and language. + * Optionally, the results can be further filtered by tags, and years. * * @param \App\Http\Requests\Front\PostsRequest $request * @return \Illuminate\Http\JsonResponse */ public function ajaxLoadNews(PostsRequest $request): \Illuminate\Http\JsonResponse { - $data = $request->validated(); - $perPage = 9; + $data = $request->validated(); + $perPage = 9; $selectedFilters = []; $category = $data['category']; @@ -197,34 +199,36 @@ class PostsController extends Controller $filters = $this->getFilters('news', $category, $publishedNewsTags, $newsModel); - /** Custom pagination */ + // Custom pagination. $newsModel = CollectionHelper::paginate($newsModel, $perPage); return response()->json([ - 'pagination' => [ - 'total' => $newsModel->total(), - 'nbItems' => count($newsModel->items()), + 'pagination' => [ + 'total' => $newsModel->total(), + 'nbItems' => count($newsModel->items()), 'currentPage' => $newsModel->currentPage(), - 'lastPage' => $newsModel->lastPage(), - 'hasMore' => $newsModel->currentPage() < $newsModel->lastPage(), + 'lastPage' => $newsModel->lastPage(), + 'hasMore' => $newsModel->currentPage() < $newsModel->lastPage(), ], - 'filters' => view('components.front.posts.filters-dropdowns', ['filters' => $filters])->render(), - 'selectedFilters' => view('components.front.posts.selected-filters', ['selectedFilters' => $selectedFilters])->render(), - 'news' => view('components.front.posts.news', ['newsList' => $newsModel->items()])->render() + 'filters' => view('components.front.posts.filters-dropdowns', ['filters' => $filters])->render(), + 'selectedFilters' => view('components.front.posts.selected-filters', [ + 'selectedFilters' => $selectedFilters, + ])->render(), + 'news' => view('components.front.posts.news', ['newsList' => $newsModel->items()])->render() ]); } /** - * Returns documents in JSON format filtered by category and language - * Optionally, the results can be further filtered by order, tags, and years + * Returns documents in JSON format filtered by category and language. + * Optionally, the results can be further filtered by order, tags, and years. * * @param \App\Http\Requests\Front\PostsRequest $request * @return \Illuminate\Http\JsonResponse */ public function ajaxLoadDocuments(PostsRequest $request): \Illuminate\Http\JsonResponse { - $data = $request->validated(); - $perPage = 3; + $data = $request->validated(); + $perPage = 3; $selectedFilters = []; $category = $data['category']; @@ -239,7 +243,8 @@ class PostsController extends Controller ->unique() ->values(); - $selectedTags = $publishedDocumentsTags->filter(fn ($tag) => $requestedTags->contains($tag->slug ?? null)) + $selectedTags = $publishedDocumentsTags + ->filter(fn ($tag) => $requestedTags->contains($tag->slug ?? null)) ->map(fn ($tag) => [ 'id' => $tag->id, 'title' => $tag->name, @@ -300,20 +305,24 @@ class PostsController extends Controller $filters = $this->getFilters('documents', $category, $publishedDocumentsTags, $documentsModel); - /** Custom pagination */ + // Custom pagination. $documentsModel = CollectionHelper::paginate($documentsModel, $perPage); return response()->json([ - 'pagination' => [ - 'total' => $documentsModel->total(), - 'nbItems' => count($documentsModel->items()), + 'pagination' => [ + 'total' => $documentsModel->total(), + 'nbItems' => count($documentsModel->items()), 'currentPage' => $documentsModel->currentPage(), - 'lastPage' => $documentsModel->lastPage(), - 'hasMore' => $documentsModel->currentPage() < $documentsModel->lastPage(), + 'lastPage' => $documentsModel->lastPage(), + 'hasMore' => $documentsModel->currentPage() < $documentsModel->lastPage(), ], - 'filters' => view('components.front.posts.filters-dropdowns', ['filters' => $filters])->render(), - 'selectedFilters' => view('components.front.posts.selected-filters', ['selectedFilters' => $selectedFilters])->render(), - 'news' => view('components.front.posts.documents', ['documentsList' => $documentsModel->items()])->render() + 'filters' => view('components.front.posts.filters-dropdowns', ['filters' => $filters])->render(), + 'selectedFilters' => view('components.front.posts.selected-filters', [ + 'selectedFilters' => $selectedFilters, + ])->render(), + 'news' => view('components.front.posts.documents', [ + 'documentsList' => $documentsModel->items(), + ])->render() ]); } } diff --git a/app/Http/Controllers/Front/SearchController.php b/app/Http/Controllers/Front/SearchController.php index 8f2ad16f..de765633 100644 --- a/app/Http/Controllers/Front/SearchController.php +++ b/app/Http/Controllers/Front/SearchController.php @@ -4,18 +4,7 @@ namespace App\Http\Controllers\Front; use App\Http\Requests\Front\Search\SearchAjaxRequest; use App\Http\Requests\Front\Search\SearchRequest; -use App\Models\Document; -use App\Models\DynamicPage; -use App\Models\News; -use App\Enums\Document\DocumentStatusEnum; -use App\Enums\News\NewsStatusEnum; -use App\Enums\DynamicPages\PageStatusEnum; -use Illuminate\Http\Request; -use Illuminate\Support\Str; -use Illuminate\Database\Eloquent\Builder; -use Mcamara\LaravelLocalization\LaravelLocalization; use Uwil\LaravelCommon\Controllers\Controller; -use Uwil\LaravelCommon\Helpers\CollectionHelper; class SearchController extends Controller { @@ -25,7 +14,7 @@ class SearchController extends Controller * @param \App\Http\Requests\Front\Search\SearchRequest $request * @return \Illuminate\Contracts\View\View */ - public function search(SearchRequest $request) + public function search(SearchRequest $request): \Illuminate\Contracts\View\View { $queryKey = trans('front.search.query'); $searchTerm = $request->validated()[$queryKey]; @@ -46,85 +35,87 @@ class SearchController extends Controller $currentPage = (int) $request->validated()['page']; $currentLocale = $request->validated()['locale']; $perPage = 5; - + app()->setLocale($currentLocale); $searchQuery = $this->buildExactSearchQuery($searchTerm); - + $models = $class::search($searchQuery, function ($engine, $query, $options) use ($class, $currentLocale) { $options['attributesToSearchOn'] = $class::searchTransFields($currentLocale); return $engine->search($query, $options); }) ->where('status', $class::searchStatusEnum()) ->paginateRaw(perPage: $perPage, page: $currentPage); - + // Render items. - $itemsHtml = collect($models['hits'])->map(fn ($result) => - view('components.front.search.card', [ - 'class' => $class, - 'result' => $result, - 'mainField' => $class::searchMainField(), - 'routeName' => $class::searchRouteName($result['id_key'] ?? null), - 'customBreadcrumbs' => true, - 'searchTerm' => $searchTerm, - 'currentLocale' => $currentLocale, - ])->render() - )->implode(''); - + $itemsHtml = collect($models['hits'])->map(fn ($result) => view('components.front.search.card', [ + 'class' => $class, + 'result' => $result, + 'mainField' => $class::searchMainField(), + 'routeName' => $class::searchRouteName($result['id_key'] ?? null), + 'customBreadcrumbs' => true, + 'searchTerm' => $searchTerm, + 'currentLocale' => $currentLocale, + ])->render())->implode(''); + // Pagination. $paginationHtml = view('components.front.search.pagination', [ 'models' => $models, ])->render(); - + return response()->json([ 'items' => $itemsHtml, 'pagination' => $paginationHtml, 'totalHits' => $models['totalHits'], ]); } - + /** * Set strict search term. - * + * + * @param string $searchTerm * @return string */ private function buildExactSearchQuery(string $searchTerm): string { $words = preg_split('/\s+/', trim($searchTerm), -1, PREG_SPLIT_NO_EMPTY); - + if (count($words) === 1) { return '"' . $words[0] . '"'; } - - $exactTerms = array_map(function($word) { + + $exactTerms = array_map(function ($word) { return $word . '*'; }, $words); - + return '+' . implode(' +', $exactTerms); } /** * Highlights all search terms in a text. * - * @param string $text - * @param string $searchTerm + * @param string $text + * @param string $searchTerm + * @param integer $contextLength * @return string + * @phpcs:disable Generic.Metrics.CyclomaticComplexity */ public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string { + // phpcs:enable if (trim($searchTerm) === '') { return $text; } - + // Clean terms list. $words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY); if (empty($words)) { return $text; } - + $fullText = strip_tags($text); $textLength = strlen($fullText); $ranges = []; - + // Collection of relevant ranges around each word. foreach ($words as $word) { $pattern = '/(? $a['start'] <=> $b['start']); $merged = []; @@ -159,21 +150,21 @@ class SearchController extends Controller ); } } - + $snippets = []; - + foreach ($merged as $r) { $snippet = substr($fullText, $r['start'], $r['end'] - $r['start']); - - // Cut cleanly without breaking the words + + // Cut cleanly without breaking the words. if ($r['start'] > 0) { $snippet = preg_replace('/^\S*\s/', '…', $snippet, 1); } if ($r['end'] < $textLength) { $snippet = preg_replace('/\s\S*$/', '…', $snippet, 1); } - - // Highlighting searched words + + // Highlighting searched words. foreach ($words as $word) { $pattern = '/(?= 3) break; - } - + if (count($snippets) >= 3) { + break; + } + } //end foreach + $result = implode('… ', $snippets); $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); - + return trim($result); } } diff --git a/app/Http/Middleware/ForceLocale.php b/app/Http/Middleware/ForceLocale.php index d88974be..8f0829d9 100644 --- a/app/Http/Middleware/ForceLocale.php +++ b/app/Http/Middleware/ForceLocale.php @@ -20,9 +20,10 @@ class ForceLocale * The issue occurred when two browser tabs were open in different locales: * the data being saved could end up using the other tab’s locale. * - * @param Request $request - * @param Closure $next + * @param \Illuminate\Http\Request $request + * @param Closure $next * @return mixed + * @throws ValidationException Not supported locale. */ public function handle(Request $request, Closure $next): mixed { @@ -31,16 +32,9 @@ class ForceLocale return $next($request); } - // 1️⃣ Session - if (Session::has('lang')) { - $locale = Session::get('lang'); - } - // 2️⃣ FallBack - else { - $locale = config('app.fallback_locale'); - } - + $locale = (Session::has('lang')) ? Session::get('lang') : config('app.fallback_locale'); App::setLocale($locale); + // 1. Is Post method or Inertia request ? if ( in_array($request->method(), ['POST', 'PUT', 'PATCH'], true) and @@ -50,7 +44,7 @@ class ForceLocale $requestLocale = $request->locale ?? config('app.fallback_locale'); // 2. If prefix is not in supportedLocales if (!in_array($requestLocale, LaravelLocalization::getSupportedLanguagesKeys(), true)) { - throw ValidationException::withMessages(["Langue" => "locale pas accepté"]); + throw ValidationException::withMessages(["Langue" => "Not supported locale."]); } // 3. Set new locale if locale and prefix are not the same if ($requestLocale !== app()->getLocale()) { diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index b50af4ac..e3a5fdb4 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -2,9 +2,9 @@ namespace App\Http\Middleware; -use App\Enums\StaticRoutes; use App\Enums\DynamicFieldTypes; use App\Enums\ModelsList; +use App\Enums\StaticRoutesEnum; use App\Helpers\TranslationHelper; use App\Models\Company; use App\Models\CompanyActivity; @@ -138,9 +138,9 @@ class HandleInertiaRequests extends Middleware 'enumUserRole' => RoleEnum::toArray(), 'enumDynamicFieldTypes' => DynamicFieldTypes::toArray(), 'enumModelsList' => ModelsList::toArray(), + 'enumStaticRoutes' => StaticRoutesEnum::getRoutes(), 'errors' => $errors, 'translations' => $translations, - 'contactFormRoutes' => StaticRoutes::getRoutes(), ]; if (Breadcrumbs::exists($request->route()->getName())) { $props = array_merge($props, [ diff --git a/app/Http/Middleware/Lang.php b/app/Http/Middleware/Lang.php index 2455cc57..5d5a4266 100644 --- a/app/Http/Middleware/Lang.php +++ b/app/Http/Middleware/Lang.php @@ -5,13 +5,18 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; - class Lang { - + /** + * Handle an incoming request. + * Not used but need it for uwil package. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return \Symfony\Component\HttpFoundation\Response + */ public function handle(Request $request, Closure $next): mixed { return $next($request); } - } diff --git a/app/Http/Requests/Back/Companies/StoreCompanyRequest.php b/app/Http/Requests/Back/Companies/StoreCompanyRequest.php index 2ef29680..7bf2a780 100644 --- a/app/Http/Requests/Back/Companies/StoreCompanyRequest.php +++ b/app/Http/Requests/Back/Companies/StoreCompanyRequest.php @@ -2,12 +2,11 @@ namespace App\Http\Requests\Back\Companies; -use App\Enums\DynamicFieldTypes; use App\Models\Company; -use Illuminate\Foundation\Http\FormRequest; use App\Traits\Requests\HasInertiaPicture; +use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Gate; -use Illuminate\Validation\Rules\Enum; +use Uwil\LaravelCommon\Rules\WysiwygLength; class StoreCompanyRequest extends FormRequest { @@ -44,11 +43,13 @@ class StoreCompanyRequest extends FormRequest public function rules(): array { return [ - 'name' => 'required|string|between:3,255', - 'logo' => $this->pictureRules('required|nullable|file|mimes:jpg,jpeg,png,webp|max:5120|dimensions:width=500,height=500'), + 'name' => 'required|string|between:3,255|unique:companies,name', + 'logo' => $this->pictureRules( + 'required|nullable|file|mimes:jpg,jpeg,png,webp|max:5120|dimensions:width=500,height=500', + ), 'responsable' => 'required|nullable|string|between:3,255', - 'url' => 'required|nullable|string|between:3,255', - 'informations' => 'required|string|between:3,255', + 'url' => 'nullable|string|between:3,255', + 'informations' => ['required', 'string', new WysiwygLength(10, 5000)], 'employees' => 'required|nullable|numeric|between:0,100000', 'latitude' => 'required|numeric|between:-90,90', 'longitude' => 'required|numeric|between:-180,180', diff --git a/app/Http/Requests/Back/Companies/UpdateCompanyRequest.php b/app/Http/Requests/Back/Companies/UpdateCompanyRequest.php index 3798a43d..c874892d 100644 --- a/app/Http/Requests/Back/Companies/UpdateCompanyRequest.php +++ b/app/Http/Requests/Back/Companies/UpdateCompanyRequest.php @@ -15,4 +15,22 @@ class UpdateCompanyRequest extends StoreCompanyRequest { return Gate::check('update', $this->route('company')); } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules(): array + { + $rules = [ + 'name' => [ + 'required', + 'string', + 'between:3,255', + 'unique:companies,name,' . request()->company->getKey(), + ], + ]; + return \array_merge(parent::rules(), $rules); + } } diff --git a/app/Http/Requests/Back/CompanyActivities/StoreCompanyActivityRequest.php b/app/Http/Requests/Back/CompanyActivities/StoreCompanyActivityRequest.php index 18107243..2a6a6fa2 100644 --- a/app/Http/Requests/Back/CompanyActivities/StoreCompanyActivityRequest.php +++ b/app/Http/Requests/Back/CompanyActivities/StoreCompanyActivityRequest.php @@ -2,11 +2,9 @@ namespace App\Http\Requests\Back\CompanyActivities; -use App\Enums\DynamicFieldTypes; use App\Models\CompanyActivity; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Gate; -use Illuminate\Validation\Rules\Enum; class StoreCompanyActivityRequest extends FormRequest { diff --git a/app/Http/Requests/Back/CompanySectors/StoreCompanySectorRequest.php b/app/Http/Requests/Back/CompanySectors/StoreCompanySectorRequest.php index 6fbe4cb6..d6f8a456 100644 --- a/app/Http/Requests/Back/CompanySectors/StoreCompanySectorRequest.php +++ b/app/Http/Requests/Back/CompanySectors/StoreCompanySectorRequest.php @@ -2,11 +2,9 @@ namespace App\Http\Requests\Back\CompanySectors; -use App\Enums\DynamicFieldTypes; use App\Models\CompanySector; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Gate; -use Illuminate\Validation\Rules\Enum; class StoreCompanySectorRequest extends FormRequest { diff --git a/app/Http/Requests/Back/Document/StoreDocumentRequest.php b/app/Http/Requests/Back/Document/StoreDocumentRequest.php index a159d9d1..8d831ac7 100644 --- a/app/Http/Requests/Back/Document/StoreDocumentRequest.php +++ b/app/Http/Requests/Back/Document/StoreDocumentRequest.php @@ -16,6 +16,8 @@ class StoreDocumentRequest extends FormRequest /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { @@ -67,5 +69,4 @@ class StoreDocumentRequest extends FormRequest 'is_issuu' => trans('validation.custom.is_issuu'), ]; } - } diff --git a/app/Http/Requests/Back/Document/UpdateDocumentRequest.php b/app/Http/Requests/Back/Document/UpdateDocumentRequest.php index bd97bab3..d737b4c3 100644 --- a/app/Http/Requests/Back/Document/UpdateDocumentRequest.php +++ b/app/Http/Requests/Back/Document/UpdateDocumentRequest.php @@ -8,10 +8,11 @@ class UpdateDocumentRequest extends StoreDocumentRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { return Gate::check('update', $this->route('document')); } - } diff --git a/app/Http/Requests/Back/DocumentCategory/StoreDocumentCategoryRequest.php b/app/Http/Requests/Back/DocumentCategory/StoreDocumentCategoryRequest.php index 9833f71e..51b71635 100644 --- a/app/Http/Requests/Back/DocumentCategory/StoreDocumentCategoryRequest.php +++ b/app/Http/Requests/Back/DocumentCategory/StoreDocumentCategoryRequest.php @@ -10,6 +10,8 @@ class StoreDocumentCategoryRequest extends FormRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { diff --git a/app/Http/Requests/Back/DocumentCategory/UpdateDocumentCategoryRequest.php b/app/Http/Requests/Back/DocumentCategory/UpdateDocumentCategoryRequest.php index 9a08041b..f5b4e299 100644 --- a/app/Http/Requests/Back/DocumentCategory/UpdateDocumentCategoryRequest.php +++ b/app/Http/Requests/Back/DocumentCategory/UpdateDocumentCategoryRequest.php @@ -8,6 +8,8 @@ class UpdateDocumentCategoryRequest extends StoreDocumentCategoryRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { diff --git a/app/Http/Requests/Back/DocumentTag/StoreDocumentTagRequest.php b/app/Http/Requests/Back/DocumentTag/StoreDocumentTagRequest.php index 0ed26bca..a0f83ae9 100644 --- a/app/Http/Requests/Back/DocumentTag/StoreDocumentTagRequest.php +++ b/app/Http/Requests/Back/DocumentTag/StoreDocumentTagRequest.php @@ -10,6 +10,8 @@ class StoreDocumentTagRequest extends FormRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { diff --git a/app/Http/Requests/Back/DocumentTag/UpdateDocumentTagRequest.php b/app/Http/Requests/Back/DocumentTag/UpdateDocumentTagRequest.php index 626b75b9..26f9950d 100644 --- a/app/Http/Requests/Back/DocumentTag/UpdateDocumentTagRequest.php +++ b/app/Http/Requests/Back/DocumentTag/UpdateDocumentTagRequest.php @@ -8,6 +8,8 @@ class UpdateDocumentTagRequest extends StoreDocumentTagRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { diff --git a/app/Http/Requests/Back/ModelListRequest.php b/app/Http/Requests/Back/ModelListRequest.php index cd6d3078..c17e214a 100644 --- a/app/Http/Requests/Back/ModelListRequest.php +++ b/app/Http/Requests/Back/ModelListRequest.php @@ -8,6 +8,7 @@ use Illuminate\Foundation\Http\FormRequest; class ModelListRequest extends FormRequest { use HasLaravelFailedValidation; + /** * Determine if the user is authorized to make this request. * diff --git a/app/Http/Requests/Back/News/StoreNewsRequest.php b/app/Http/Requests/Back/News/StoreNewsRequest.php index c5165e58..97aaa4aa 100644 --- a/app/Http/Requests/Back/News/StoreNewsRequest.php +++ b/app/Http/Requests/Back/News/StoreNewsRequest.php @@ -17,6 +17,8 @@ class StoreNewsRequest extends FormRequest /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { diff --git a/app/Http/Requests/Back/NewsCategory/StoreNewsCategoryRequest.php b/app/Http/Requests/Back/NewsCategory/StoreNewsCategoryRequest.php index acd3204e..55bc5d86 100644 --- a/app/Http/Requests/Back/NewsCategory/StoreNewsCategoryRequest.php +++ b/app/Http/Requests/Back/NewsCategory/StoreNewsCategoryRequest.php @@ -10,6 +10,8 @@ class StoreNewsCategoryRequest extends FormRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { @@ -24,12 +26,12 @@ class StoreNewsCategoryRequest extends FormRequest public function rules(): array { return [ - 'slug' => 'required|string|between:3,255', - 'name' => 'required|string|between:3,255', + 'slug' => 'required|string|between:3,255', + 'name' => 'required|string|between:3,255', ]; } - /** + /** * Get custom attributes for validator errors. * * @return array @@ -37,7 +39,7 @@ class StoreNewsCategoryRequest extends FormRequest public function attributes(): array { return [ - 'name' => trans('validation.custom.name'), + 'name' => trans('validation.custom.name'), ]; } } diff --git a/app/Http/Requests/Back/NewsCategory/UpdateNewsCategoryRequest.php b/app/Http/Requests/Back/NewsCategory/UpdateNewsCategoryRequest.php index c3f080cd..8fdab740 100644 --- a/app/Http/Requests/Back/NewsCategory/UpdateNewsCategoryRequest.php +++ b/app/Http/Requests/Back/NewsCategory/UpdateNewsCategoryRequest.php @@ -8,10 +8,11 @@ class UpdateNewsCategoryRequest extends StoreNewsCategoryRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { return Gate::check('update', $this->route('news_category')); } - } diff --git a/app/Http/Requests/Back/NewsTag/StoreNewsTagRequest.php b/app/Http/Requests/Back/NewsTag/StoreNewsTagRequest.php index 26df0007..d3eb7b85 100644 --- a/app/Http/Requests/Back/NewsTag/StoreNewsTagRequest.php +++ b/app/Http/Requests/Back/NewsTag/StoreNewsTagRequest.php @@ -10,6 +10,8 @@ class StoreNewsTagRequest extends FormRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { @@ -30,7 +32,7 @@ class StoreNewsTagRequest extends FormRequest ]; } - /** + /** * Get custom attributes for validator errors. * * @return array @@ -38,8 +40,8 @@ class StoreNewsTagRequest extends FormRequest public function attributes(): array { return [ - 'name' => trans('validation.custom.name'), - 'color' => trans('validation.custom.color'), + 'name' => trans('validation.custom.name'), + 'color' => trans('validation.custom.color'), ]; } } diff --git a/app/Http/Requests/Back/NewsTag/UpdateNewsTagRequest.php b/app/Http/Requests/Back/NewsTag/UpdateNewsTagRequest.php index 836ca7e3..b19495e8 100644 --- a/app/Http/Requests/Back/NewsTag/UpdateNewsTagRequest.php +++ b/app/Http/Requests/Back/NewsTag/UpdateNewsTagRequest.php @@ -8,10 +8,11 @@ class UpdateNewsTagRequest extends StoreNewsTagRequest { /** * Determine if the user is authorized to make this request. + * + * @return boolean */ public function authorize(): bool { return Gate::check('update', $this->route('news_tag')); } - } diff --git a/app/Http/Requests/Back/PageConfigs/StorePageConfigRequest.php b/app/Http/Requests/Back/PageConfigs/StorePageConfigRequest.php index ba9dc583..4a0411c8 100644 --- a/app/Http/Requests/Back/PageConfigs/StorePageConfigRequest.php +++ b/app/Http/Requests/Back/PageConfigs/StorePageConfigRequest.php @@ -37,6 +37,8 @@ class StorePageConfigRequest extends FormRequest /** * Recursively generates rules for a given key. * + * @param string $prefix + * @param integer $depth * @return array */ protected function configRules(string $prefix, int $depth = 1): array @@ -66,7 +68,7 @@ class StorePageConfigRequest extends FormRequest if ($depth < 10) { $rules["{$prefix}.children"] = ['sometimes', 'array']; - $rules += $this->configRules("{$prefix}.children.*", $depth + 1); + $rules += $this->configRules("{$prefix}.children.*", $depth + 1); } return $rules; @@ -89,6 +91,8 @@ class StorePageConfigRequest extends FormRequest /** * Recursively generates attributes for a given key. * + * @param string $prefix + * @param integer $depth * @return array */ protected function configAttributes(string $prefix, int $depth = 1): array @@ -101,12 +105,12 @@ class StorePageConfigRequest extends FormRequest "{$prefix}.label" => trans('validation.custom.label'), "{$prefix}.validation" => trans('validation.custom.validation'), ]; - + if ($depth < 10) { $rules["{$prefix}.children"] = trans('validation.custom.children'); - $rules += $this->configAttributes("{$prefix}.children.*", $depth + 1); + $rules += $this->configAttributes("{$prefix}.children.*", $depth + 1); } - + return $rules; } } diff --git a/app/Http/Requests/Back/UpdateDynamicFieldRequest.php b/app/Http/Requests/Back/UpdateDynamicFieldRequest.php index 0a3509a7..c1b2b4cb 100644 --- a/app/Http/Requests/Back/UpdateDynamicFieldRequest.php +++ b/app/Http/Requests/Back/UpdateDynamicFieldRequest.php @@ -4,6 +4,7 @@ namespace App\Http\Requests\Back; use App\Enums\ElementPositionEnum; use App\Enums\DynamicFieldTypes; +use App\Enums\StaticRoutesEnum; use App\Models\PageConfig; use App\Traits\Requests\HasInertiaPicture; use Illuminate\Foundation\Http\FormRequest; @@ -61,10 +62,15 @@ abstract class UpdateDynamicFieldRequest extends FormRequest /** * Get rules from a specific input type. * + * @param array $input + * @param string $prefix * @return array + * @throws \UnexpectedValueException Unrecognized dynamic type. + * @phpcs:disable Generic.Metrics.CyclomaticComplexity */ - private function recursiveRules(&$input, $prefix): array + private function recursiveRules(array &$input, string $prefix): array { + // phpcs:enable $rules = []; $ruleKey = "$prefix.$input[key]"; switch ($input['type']) { @@ -86,7 +92,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest // remove them from the rules so that our custom rule WysiwygLength can apply it. $defaults = $this->extractMinMax($defaultRules); ['min' => $min, 'max' => $max] = $this->extractMinMax($wysiwygRules, $defaults); - $newWysiwygRules = array_values(array_filter($wysiwygRules, fn($rule) => !( + $newWysiwygRules = array_values(array_filter($wysiwygRules, fn($rule) => !( is_string($rule) && preg_match('/^(min|max|between):/', $rule) ))); @@ -112,7 +118,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest case DynamicFieldTypes::url->value: $rules = array_merge($rules, [ $ruleKey => array_merge(explode("|", DynamicFieldTypes::url->getValidation()), [ - // @phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed + // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed function ($attribute, $value, $fail) { try { ToolboxHelper::assertNoInternalUrls($attribute, $value); @@ -173,29 +179,30 @@ abstract class UpdateDynamicFieldRequest extends FormRequest case DynamicFieldTypes::model->value: // Set a new rule key for the model name. $ruleKeyReserved = preg_replace('/([^.\s]+)$/', 'reserved_$1', $ruleKey); - $rules = array_merge($rules, [ - $ruleKey => $this->compileValidate(DynamicFieldTypes::model->getValidation(), $input), + $rules = array_merge($rules, [ + $ruleKey => $this->compileValidate(DynamicFieldTypes::model->getValidation(), $input), $ruleKeyReserved => 'required|string|between:3,255', ]); break; case DynamicFieldTypes::staticroute->value: $rules = array_merge($rules, [ - $ruleKey => array_merge($this->compileValidate(DynamicFieldTypes::staticroute->getValidation(), $input), [ - new Enum(ElementPositionEnum::class), - ]) + $ruleKey => array_merge( + $this->compileValidate(DynamicFieldTypes::staticroute->getValidation(), $input), + [new Enum(StaticRoutesEnum::class)], + ), ]); break; // Specific inputs. case DynamicFieldTypes::position->value: $rules = array_merge($rules, [ - $ruleKey => array_merge($this->compileValidate(DynamicFieldTypes::position->getValidation(), $input), [ - new Enum(ElementPositionEnum::class), - ]) + $ruleKey => array_merge( + $this->compileValidate(DynamicFieldTypes::position->getValidation(), $input), + [new Enum(ElementPositionEnum::class)], + ), ]); break; default: throw new \UnexpectedValueException("Unrecognized dynamic type: " . ($input['type'] ?? 'null')); - break; } //end switch return $rules; } @@ -217,9 +224,11 @@ abstract class UpdateDynamicFieldRequest extends FormRequest /** * Get attributes from a specific input type. * + * @param array $input + * @param string $prefix * @return array */ - private function recursiveAttributes(&$input, $prefix): array + private function recursiveAttributes(array &$input, string $prefix): array { $attributes = []; $attributeKey = sprintf("%s.%s", $prefix, $input['key']); @@ -271,7 +280,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest * @param array $input * @return array */ - private function mergeValidations($defaultValidations, $input): array + private function mergeValidations(string|array $defaultValidations, array $input): array { if (\is_string($defaultValidations)) { $defaultValidations = explode('|', $defaultValidations); @@ -305,7 +314,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest $defaultValidations[] = $validate; } } - } + } //end foreach return $defaultValidations; } @@ -360,7 +369,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest } // Check if the key start with the pattern enum_. if (str_starts_with($key, sprintf("%s_", DynamicFieldTypes::boolean->name))) { - // Manages values "true", "false", "1", "0", 1, 0, "on", "off". + // Accepts boolean-like values (true/false, one/zero, on/off) as strings or numbers. $data[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN); } } @@ -370,7 +379,7 @@ abstract class UpdateDynamicFieldRequest extends FormRequest /** * Extract min and max values from laravel validation. * - * @param array $rules + * @param array $rules * @param array|null $fallback * @return array */ diff --git a/app/Http/Requests/Back/UploadFileRequest.php b/app/Http/Requests/Back/UploadFileRequest.php index 13e95443..5b2ede83 100644 --- a/app/Http/Requests/Back/UploadFileRequest.php +++ b/app/Http/Requests/Back/UploadFileRequest.php @@ -27,7 +27,14 @@ class UploadFileRequest extends FormRequest public function rules(): array { return [ - 'upload' => 'required|image|mimes:jpeg,png,jpg|max:5048|dimensions:min_width=567,min_height=567,max_width:1008,max_height:1008' + 'upload' => [ + 'required', + 'image', + 'mimes:jpeg,png,jpg', + 'max:5048', + 'dimensions:min_width=567,min_height=567,max_width:1008,max_height:1008', + ], + 'folder' => 'required|string|between:3,255', ]; } } diff --git a/app/Http/Requests/Front/Contact/ContactRequest.php b/app/Http/Requests/Front/Contact/ContactRequest.php index ecd16ba4..f1f4dbcf 100644 --- a/app/Http/Requests/Front/Contact/ContactRequest.php +++ b/app/Http/Requests/Front/Contact/ContactRequest.php @@ -20,52 +20,50 @@ class ContactRequest extends FormRequest */ public function rules(): array { - // ToolboxHelper::validateRecaptcha($this, \config('services.google.recaptcha.version')); + ToolboxHelper::validateRecaptcha($this, \config('services.google.recaptcha.version')); + $typeContactForm = $this->input('enumType'); - /** Validation for common fields */ + // Validation for common fields. $rules = [ - 'enumType' => ['required', Rule::enum(ContactFormType::class)], - 'lastname' => ['required', 'min:1', 'max:60'], + 'enumType' => ['required', Rule::enum(ContactFormType::class)], + 'lastname' => ['required', 'min:1', 'max:60'], 'firstname' => ['required', 'min:1', 'max:60'], - 'message' => ['required', 'min:10', 'max:255'], - 'email' => ['required', 'min:1', 'max:60', 'email:rfc,dns,spoof'], + 'message' => ['required', 'min:10', 'max:255'], + 'email' => ['required', 'min:1', 'max:60', 'email:rfc,dns,spoof'], ]; - /** Validation for breeder enum */ + // Validation for breeder enum. if (ContactFormType::breeder->equals(ContactFormType::make($typeContactForm))) { - $breeder = [ - 'phone' => ['required', 'min:1', 'max:60'], - 'typeelevage' => ['array', 'min:1'], + $rules = array_merge($rules, [ + 'phone' => ['required', 'min:1', 'max:60'], + 'typeelevage' => ['array', 'min:1'], 'typeelevage.*' => [Rule::enum(BreedType::class)], - 'zonegeo' => ['array', 'min:1'], - 'zonegeo.*' => [Rule::enum(Department::class)], - ]; - $rules = array_merge($rules, $breeder); + 'zonegeo' => ['array', 'min:1'], + 'zonegeo.*' => [Rule::enum(Department::class)], + ]); } - /** Validation for restauration enum */ + // Validation for restauration enum. if (ContactFormType::restauration->equals(ContactFormType::make($typeContactForm))) { - $restauration = [ - 'company' => 'string|max:255', - ]; - $rules = array_merge($rules, $restauration); + $rules = array_merge($rules, [ + 'company' => 'string|max:255', + ]); } - /** Add the country field */ + // Add the country field. if ( ContactFormType::restauration->equals(ContactFormType::make($typeContactForm)) || ContactFormType::export->equals(ContactFormType::make($typeContactForm)) || ContactFormType::commitments->equals(ContactFormType::make($typeContactForm)) || ContactFormType::info->equals(ContactFormType::make($typeContactForm)) ) { - $addCountry = [ + $rules = array_merge($rules, [ 'country' => ['required', 'min:1', 'max:150'], - ]; - $rules = array_merge($rules, $addCountry); + ]); } - /** Add the optional phone field */ + // Add the optional phone field. if ( ContactFormType::restauration->equals(ContactFormType::make($typeContactForm)) || ContactFormType::export->equals(ContactFormType::make($typeContactForm)) || @@ -73,13 +71,12 @@ class ContactRequest extends FormRequest ContactFormType::commitments->equals(ContactFormType::make($typeContactForm)) || ContactFormType::info->equals(ContactFormType::make($typeContactForm)) ) { - $addNoRequiredPhone = [ + $rules = array_merge($rules, [ 'phone' => ['max:60'], - ]; - $rules = array_merge($rules, $addNoRequiredPhone); + ]); } - /** Add the town and postalcode fields */ + // Add the town and postalcode fields. if ( ContactFormType::restauration->equals(ContactFormType::make($typeContactForm)) || ContactFormType::export->equals(ContactFormType::make($typeContactForm)) || @@ -88,35 +85,33 @@ class ContactRequest extends FormRequest ContactFormType::info->equals(ContactFormType::make($typeContactForm)) || ContactFormType::press->equals(ContactFormType::make($typeContactForm)) ) { - $addTownAndPostalCodeFields = [ - 'town' => 'string|required|min:2|max:255', - 'postalcode' => 'string|required|min:2|max:60', - ]; - $rules = array_merge($rules, $addTownAndPostalCodeFields); + $rules = array_merge($rules, [ + 'town' => 'string|required|min:2|max:255', + 'postalcode' => 'string|required|min:2|max:60', + ]); } - /** Validation for restauration and export commun fields */ + // Validation for restauration and export commun fields. if ( ContactFormType::restauration->equals(ContactFormType::make($typeContactForm)) || ContactFormType::export->equals(ContactFormType::make($typeContactForm)) ) { - $restaurationExport = [ - 'type' => ['array', 'min:1'], + $rules = array_merge($rules, [ + 'type' => ['array', 'min:1'], 'type.*' => [Rule::enum(CustomerAskingType::class)], - ]; - $rules = array_merge($rules, $restaurationExport); + ]); } - /** Validation for press enum */ + // Validation for press enum. if (ContactFormType::press->equals(ContactFormType::make($typeContactForm))) { - $press = [ - 'subject' => ['required', Rule::enum(PressType::class)], - 'company' => 'required|string|min:2|max:255', - 'phone' => ['required', 'max:60'], + $rules = array_merge($rules, [ + 'subject' => ['required', Rule::enum(PressType::class)], + 'company' => 'required|string|min:2|max:255', + 'phone' => ['required', 'max:60'], 'newsletter' => 'boolean' - ]; - $rules = array_merge($rules, $press); + ]); } + return $rules; } } diff --git a/app/Http/Requests/Front/PostsRequest.php b/app/Http/Requests/Front/PostsRequest.php index 6ceac820..99abcfd7 100644 --- a/app/Http/Requests/Front/PostsRequest.php +++ b/app/Http/Requests/Front/PostsRequest.php @@ -6,16 +6,6 @@ use Illuminate\Foundation\Http\FormRequest; class PostsRequest extends FormRequest { - /** - * Determine if the user is authorized to make this request. - * - * @return boolean - */ - public function authorize(): bool - { - return true; - } - /** * Get the validation rules that apply to the request. * @@ -24,18 +14,15 @@ class PostsRequest extends FormRequest public function rules(): array { return [ - 'page' => ['required', 'integer'], - 'category' => ['required', 'string'], - 'locale' => ['required', 'string'], - - 'filters' => ['nullable', 'array'], - 'filters.order' => ['nullable', 'string', 'in:asc,desc'], - - 'filters.tags' => ['nullable', 'array'], - 'filters.tags.*'=> ['string'], - - 'filters.years' => ['nullable', 'array'], - 'filters.years.*' => ['string'], + 'page' => 'required|integer', + 'category' => 'required|string', + 'locale' => 'required|string', + 'filters' => 'nullable|array', + 'filters.order' => 'nullable|string|in:asc,desc', + 'filters.tags' => 'nullable|array', + 'filters.tags.*' => 'string', + 'filters.years' => 'nullable|array', + 'filters.years.*' => 'string', ]; } } diff --git a/app/Jobs/CleanTrashModels.php b/app/Jobs/CleanTrashModels.php index 730afdf1..bf40b0ba 100644 --- a/app/Jobs/CleanTrashModels.php +++ b/app/Jobs/CleanTrashModels.php @@ -10,7 +10,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\File; -use Illuminate\Database\Eloquent\SoftDeletes; use Symfony\Component\Finder\SplFileInfo; class CleanTrashModels implements ShouldQueue, ShouldBeUnique @@ -44,7 +43,5 @@ class CleanTrashModels implements ShouldQueue, ShouldBeUnique ->cursor() ->each(fn($model) => $model->forceDelete()); }); - - dd($models); } } diff --git a/app/Mail/ContactMail.php b/app/Mail/ContactMail.php index 6bf4bd16..72cee4d3 100644 --- a/app/Mail/ContactMail.php +++ b/app/Mail/ContactMail.php @@ -12,7 +12,8 @@ use Illuminate\Mail\Mailables\Address; class ContactMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * The order instance. @@ -21,7 +22,6 @@ class ContactMail extends Mailable */ protected $data; - /** * Create a new message instance. * @@ -33,14 +33,12 @@ class ContactMail extends Mailable $this->data = $data; } - - /** * Get the message envelope. * * @return \Illuminate\Mail\Mailables\Envelope */ - public function envelope(): Envelope + public function envelope(): \Illuminate\Mail\Mailables\Envelope { return new Envelope( from: new Address(\config('mail.from.address'), \config('mail.from.name')), @@ -52,13 +50,12 @@ class ContactMail extends Mailable ); } - /** * Get the message content definition. * * @return \Illuminate\Mail\Mailables\Content */ - public function content(): Content + public function content(): \Illuminate\Mail\Mailables\Content { return new Content( view: 'emails.contact', @@ -67,7 +64,6 @@ class ContactMail extends Mailable ); } - /** * Get the attachments for the message. * diff --git a/app/Models/CompanyActivity.php b/app/Models/CompanyActivity.php index ce3bca44..0f8b11ef 100644 --- a/app/Models/CompanyActivity.php +++ b/app/Models/CompanyActivity.php @@ -10,7 +10,6 @@ use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Support\Facades\Cache; use Illuminate\Validation\ValidationException; use Uwil\LaravelActivityLogs\Traits\ActivityLog; @@ -111,8 +110,8 @@ class CompanyActivity extends Model implements TranslatableModel TranslationHelper::validateFallbackTranslations($model); } - // RELATIONSHIPS - + // * RELATIONSHIPS + /** * Get companies for this activity. * @@ -122,4 +121,4 @@ class CompanyActivity extends Model implements TranslatableModel { return $this->hasMany(Company::class, 'activity_id'); } -} \ No newline at end of file +} diff --git a/app/Models/CompanySector.php b/app/Models/CompanySector.php index f0e2e0c4..7468af8f 100644 --- a/app/Models/CompanySector.php +++ b/app/Models/CompanySector.php @@ -10,7 +10,6 @@ use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Support\Facades\Cache; use Illuminate\Validation\ValidationException; use Uwil\LaravelActivityLogs\Traits\ActivityLog; @@ -109,8 +108,8 @@ class CompanySector extends Model implements TranslatableModel TranslationHelper::validateFallbackTranslations($model); } - // RELATIONSHIPS - + // * RELATIONSHIPS + /** * Get companies for this sector. * @@ -120,4 +119,4 @@ class CompanySector extends Model implements TranslatableModel { return $this->hasMany(Company::class, 'sector_id'); } -} \ No newline at end of file +} diff --git a/app/Models/Document.php b/app/Models/Document.php index b1213a3e..1c2f1fe2 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -290,20 +290,33 @@ class Document extends Model implements TranslatableModel 'status' => $this->status->value, ]; foreach ($locales as $locale => $_) { - $data["name_$locale"] = $this->hasTranslation('name', $locale) ? $this->getTranslation('name', $locale) : null; - $data["path_$locale"] = $this->hasTranslation('path', $locale) ? $this->getTranslation('path', $locale) : null; + $data["name_$locale"] = $this->hasTranslation('name', $locale) + ? $this->getTranslation('name', $locale) + : null; + $data["path_$locale"] = $this->hasTranslation('path', $locale) + ? $this->getTranslation('path', $locale) + : null; } return $data; } - public function inertiaFill(array $attributes) + /** + * Override HasUwilImages trait method to fill the model without relations. + * + * @param array $attributes The attributes to fill the model with. + * @return void + */ + public function inertiaFill(array $attributes): void { + // Set issu_path if defined. $issuuPath = data_get($attributes, "issuu_path"); - if($issuuPath) - { - $attributes['issuu_path'] = DocumentHelper::extractDocumentFromIssuIframe(data_get($attributes, "issuu_path")); + if ($issuuPath) { + $attributes['issuu_path'] = DocumentHelper::extractDocumentFromIssuIframe( + data_get($attributes, "issuu_path"), + ); } + // Ommit some relations. $attributes = Arr::except($attributes, ['tags', 'categories']); $this->traitInertiaFill($attributes); } @@ -324,13 +337,12 @@ class Document extends Model implements TranslatableModel ->filter(function ($document) use ($category, $locale) { $hasPath = !empty($document->getTranslation('path', $locale, false)); - $hasIssuuPath = $document->is_issuu === true && !empty($document->getTranslation('issuu_path', $locale, false)); + $hasIssuuPath = $document->is_issuu === true + && !empty($document->getTranslation('issuu_path', $locale, false)); - return - ($hasPath || $hasIssuuPath) - && $document->categories->contains( - fn($cat) => $cat->slug === $category - ); + return ($hasPath || $hasIssuuPath) && $document->categories->contains( + fn($cat) => $cat->slug === $category + ); }); } diff --git a/app/Models/DocumentTag.php b/app/Models/DocumentTag.php index 84f05569..e1a36685 100644 --- a/app/Models/DocumentTag.php +++ b/app/Models/DocumentTag.php @@ -68,27 +68,28 @@ class DocumentTag extends Model implements TranslatableModel /** * Get all Tags by category. * - * @param string $category + * @param string $slugCategory * * @return \Illuminate\Database\Eloquent\Collection */ - public static function getTagsByCategoryInCurrentLocale(string $category): \Illuminate\Database\Eloquent\Collection - { + public static function getTagsByCategoryInCurrentLocale( + string $slugCategory, + ): \Illuminate\Database\Eloquent\Collection { $locale = App::getLocale(); - return DocumentTag::getModelsCached()->load('documents.categories')->filter(function ($tag) use ($locale, $category) { - return $tag->documents->filter(function ($document) use ($locale, $category) { + return DocumentTag::getModelsCached() + ->load('documents.categories') + ->filter(function ($tag) use ($locale, $slugCategory) { + return $tag->documents->filter(function ($document) use ($locale, $slugCategory) { + $hasPath = !empty($document->getTranslation('path', $locale, false)); + $hasIssuuPath = $document->is_issuu === true; - $hasPath = !empty($document->getTranslation('path', $locale, false)); - - $hasIssuuPath = $document->is_issuu === true; - - return ( - $hasPath || $hasIssuuPath - ) && $document->categories->contains( - fn($cat) => $cat->slug === $category - ); - })->isNotEmpty(); - }); + return ( + $hasPath || $hasIssuuPath + ) && $document->categories->contains( + fn($cat) => $cat->slug === $slugCategory + ); + })->isNotEmpty(); + }); } } diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index 1f12ebc3..4efa7114 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -3,8 +3,6 @@ namespace App\Models; use App\Contracts\TranslatableModel; -use App\Enums\DynamicFieldTypes; -use App\Enums\DynamicPages; use App\Enums\DynamicPages\PageStatusEnum; use App\Helpers\DynamicPageHelper; use App\Helpers\RouteHelper; @@ -12,17 +10,14 @@ use App\Helpers\TranslationHelper; use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; use App\Traits\Models\HasUwilImages; -use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Laravel\Scout\Searchable; +use Mcamara\LaravelLocalization\Facades\LaravelLocalization; use Uwil\LaravelActivityLogs\Traits\ActivityLog; -use Uwil\LaravelCommon\Helpers\FileHelper; /** * @property string $id_key Unique key identification of the dynamic page. @@ -136,11 +131,12 @@ class DynamicPage extends Model implements TranslatableModel } // * METHODS + /** * Unpublished all children pages if change status published from draft/unpublished. * * @param self $model - * @return boolean + * @return void */ private static function setAllChildPageStatus(self $model): void { @@ -159,7 +155,7 @@ class DynamicPage extends Model implements TranslatableModel * Publish current page if all parents are published. * * @param self $model - * @return boolean + * @return void * @throws \Illuminate\Validation\ValidationException Parent must be published. */ private static function checkParentsStatus(self $model): void @@ -198,7 +194,7 @@ class DynamicPage extends Model implements TranslatableModel private static function manageFields(self $model): void { // Check unique fields. - if($model->isRoot) { + if ($model->isRoot) { self::assertRootIsUnique($model); } else { $slug = $model->slug ?? Str::slug($model->title); @@ -218,10 +214,13 @@ class DynamicPage extends Model implements TranslatableModel */ public static function assertRootIsUnique(self $model): void { - $oldDynamicPageRoot = self::getModelsCached()->where('id', '!=', $model->getKey())->where('isRoot', true)->first(); + $oldDynamicPageRoot = self::getModelsCached() + ->where('id', '!=', $model->getKey()) + ->where('isRoot', true) + ->first(); if ($oldDynamicPageRoot) { $oldDynamicPageRoot->status = PageStatusEnum::unpublished; - $oldDynamicPageRoot->isRoot = false; + $oldDynamicPageRoot->isRoot = false; $oldDynamicPageRoot->saveQuietly(); } } @@ -394,7 +393,7 @@ class DynamicPage extends Model implements TranslatableModel */ public function toSearchableArray(): array { - $locales = config('laravellocalization.supportedLocales'); + $locales = LaravelLocalization::getSupportedLanguagesKeys(); $data = [ 'id' => $this->id, @@ -402,24 +401,29 @@ class DynamicPage extends Model implements TranslatableModel 'status' => $this->status->value, ]; - foreach ($locales as $locale => $_) { - $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; - $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; + foreach ($locales as $locale) { + $data["title_$locale"] = $this->hasTranslation('title', $locale) + ? $this->getTranslation('title', $locale) + : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) + ? $this->getTranslation('slug', $locale) + : null; - $content = $this->hasTranslation('content', $locale) ? strip_tags(collect($this->getTranslation('content', $locale)) - ->flatten() - ->filter(fn($value, $key) => - is_string($value) && - !empty($value) && - !is_numeric($value) && - !in_array($key, ['order', 'id']) && - !str_starts_with($key, 'image_') && - !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value) - ) - ->values() - ->implode(' ')) : null; + $content = $this->hasTranslation('content', $locale) + ? strip_tags(collect($this->getTranslation('content', $locale)) + ->flatten() + ->filter(fn($value, $key) => + is_string($value) && + !empty($value) && + !is_numeric($value) && + !in_array($key, ['order', 'id']) && + !str_starts_with($key, 'image_') && + !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value)) + ->values() + ->implode(' ')) + : null; $data["content_$locale"] = $content; - } + } //end foreach return $data; } diff --git a/app/Models/MailContactData.php b/app/Models/MailContactData.php index 6ff9c1c3..b9a267d3 100644 --- a/app/Models/MailContactData.php +++ b/app/Models/MailContactData.php @@ -13,24 +13,24 @@ use Illuminate\Database\Eloquent\Model; /** * This class is used to store data in memory only, not in databases. * - * @property integer $id Id. - * @property \App\Enums\Contact\ContactFormType $enumType The type enum. - * @property string $lastname The customer's lastname. - * @property string $firstname The customer's firstname. - * @property string $message The message. - * @property string $email The customer's email. - * @property string|null $phone The customer's phone. - * @property \App\Enums\Contact\BreedType[] $typeelevage The customer's breeding type - * @property \App\Enums\Department[] $zonegeo The customer's greographic zone - * @property string $company The customer's company. - * @property string $country The customer's country. - * @property string $town The customer's town. - * @property string $postalcode The customer's postalcode. - * @property boolean $newsletter The customer's optin response. - * @property \App\Enums\Contact\CustomerAskingType[] $type The customer's type asking - * @property \App\Enums\Contact\PressType $subject The message's subject - * @property-read \Carbon\Carbon $created_at Created date. - * @property-read \Carbon\Carbon $updated_at Updated date. + * @property integer $id Id. + * @property \App\Enums\Contact\ContactFormType $enumType The type enum. + * @property string $lastname The customer's lastname. + * @property string $firstname The customer's firstname. + * @property string $message The message. + * @property string $email The customer's email. + * @property string|null $phone The customer's phone. + * @property \App\Enums\Contact\BreedType[] $typeelevage The customer's breeding type + * @property \App\Enums\Department[] $zonegeo The customer's greographic zone + * @property string $company The customer's company. + * @property string $country The customer's country. + * @property string $town The customer's town. + * @property string $postalcode The customer's postalcode. + * @property boolean $newsletter The customer's optin response. + * @property \App\Enums\Contact\CustomerAskingType[] $type The customer's type asking + * @property \App\Enums\Contact\PressType $subject The message's subject + * @property-read \Carbon\Carbon $created_at Created date. + * @property-read \Carbon\Carbon $updated_at Updated date. */ class MailContactData extends Model { @@ -61,7 +61,7 @@ class MailContactData extends Model 'postalcode', 'type', 'subject', - 'newsletter' + 'newsletter', ]; /** @@ -71,19 +71,21 @@ class MailContactData extends Model */ protected $casts = [ 'enumType' => ContactFormType::class, - 'typeelevage' => AsEnumArrayObject::class.':'.BreedType::class, - 'zonegeo' => AsEnumArrayObject::class.':'.Department::class, - 'type' => AsEnumArrayObject::class.':'.CustomerAskingType::class, + 'typeelevage' => AsEnumArrayObject::class . ':' . BreedType::class, + 'zonegeo' => AsEnumArrayObject::class . ':' . Department::class, + 'type' => AsEnumArrayObject::class . ':' . CustomerAskingType::class, 'subject' => PressType::class, ]; /** * Construct method. * - * @param array $attributes + * @param array $attributes + * @phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function __construct(array $attributes = []) { + // phpcs:enable parent::__construct($attributes); } } diff --git a/app/Models/News.php b/app/Models/News.php index 684d7f0c..3b0b7bae 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -12,7 +12,6 @@ use App\Traits\Models\HasUwilImages; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Arr; use Illuminate\Support\Facades\App; @@ -64,10 +63,13 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable /** * Get the value of the model's localized route key. * + * @param string $locale * @return string + * @phpcs:disable */ public function getLocalizedRouteKey($locale): string { + // phpcs:enable return $this->getTranslation( $this->getRouteKeyName(), $locale @@ -189,8 +191,15 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable self::makeStatusSense($model); } - public function inertiaFill(array $attributes) + /** + * Override HasUwilImages trait method to fill the model without relations. + * + * @param array $attributes The attributes to fill the model with. + * @return void + */ + public function inertiaFill(array $attributes): void { + // Ommit some relations. $attributes = Arr::except($attributes, ['categories', 'tags']); $this->traitInertiaFill($attributes); } @@ -352,7 +361,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable * @param string $currentLocale * @return array */ - public static function searchTransFields($currentLocale): array + public static function searchTransFields(string $currentLocale): array { return [ "title_$currentLocale", @@ -405,9 +414,15 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable 'status' => $this->status->value, ]; foreach ($locales as $locale => $_) { - $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; - $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; - $data["content_$locale"] = $this->hasTranslation('content', $locale) ? strip_tags($this->getTranslation('content', $locale)) : null; + $data["title_$locale"] = $this->hasTranslation('title', $locale) + ? $this->getTranslation('title', $locale) + : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) + ? $this->getTranslation('slug', $locale) + : null; + $data["content_$locale"] = $this->hasTranslation('content', $locale) + ? strip_tags($this->getTranslation('content', $locale)) + : null; } return $data; diff --git a/app/Models/NewsTag.php b/app/Models/NewsTag.php index 48b6ce3b..7ad6a39f 100644 --- a/app/Models/NewsTag.php +++ b/app/Models/NewsTag.php @@ -5,7 +5,6 @@ namespace App\Models; use App\Traits\Models\HasCache; use Illuminate\Support\Facades\App; use App\Contracts\TranslatableModel; -use Illuminate\Support\Facades\Cache; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; @@ -76,19 +75,22 @@ class NewsTag extends Model implements TranslatableModel /** * Get all Tags by category. * + * @param string $slugCategory * @return \Illuminate\Database\Eloquent\Collection */ - public static function getTagsByCategoryInCurrentLocale($category): \Illuminate\Database\Eloquent\Collection - { + public static function getTagsByCategoryInCurrentLocale( + string $slugCategory, + ): \Illuminate\Database\Eloquent\Collection { $locale = App::getLocale(); - return NewsTag::getModelsCached()->load('news.categories')->filter(function ($tag) use ($locale, $category) { - return $tag->news->filter(function ($news) use ($locale, $category) { - return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains( - fn ($cat) => $cat->slug === $category - ); - })->isNotEmpty(); - }); + return NewsTag::getModelsCached() + ->load('news.categories') + ->filter(function ($tag) use ($locale, $slugCategory) { + return $tag->news->filter(function ($news) use ($locale, $slugCategory) { + return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains( + fn ($cat) => $cat->slug === $slugCategory + ); + })->isNotEmpty(); + }); } } - diff --git a/app/Models/PageConfig.php b/app/Models/PageConfig.php index 332d07c2..03f5cf47 100644 --- a/app/Models/PageConfig.php +++ b/app/Models/PageConfig.php @@ -3,14 +3,12 @@ namespace App\Models; use App\Contracts\TranslatableModel; -use App\Enums\DynamicPages\PageStatusEnum; use App\Helpers\TranslationHelper; use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; use Uwil\LaravelActivityLogs\Traits\ActivityLog; @@ -147,11 +145,15 @@ class PageConfig extends Model implements TranslatableModel /** * Get the target model from a specific id and model name. - * + * + * @param string $modelId + * @param string $modelName * @return \Illuminate\Database\Eloquent\Model */ - public static function getModelFromInputModelConfig(string $modelId, string $modelName): \Illuminate\Database\Eloquent\Model - { + public static function getModelFromInputModelConfig( + string $modelId, + string $modelName, + ): \Illuminate\Database\Eloquent\Model { $studly = Str::studly(Str::singular($modelName)); $class = "App\\Models\\{$studly}"; diff --git a/app/Policies/ContactCountPolicy.php b/app/Policies/ContactCountPolicy.php index bfab7a2e..f1f9aebc 100644 --- a/app/Policies/ContactCountPolicy.php +++ b/app/Policies/ContactCountPolicy.php @@ -10,6 +10,9 @@ class ContactCountPolicy { /** * Determine whether the user can view any models. + * + * @param \Illuminate\Database\Eloquent\Model $authModel + * @return boolean */ public function viewAny(Model $authModel): bool { diff --git a/app/Policies/DocumentCategoryPolicy.php b/app/Policies/DocumentCategoryPolicy.php index f7911cdd..d22677ee 100644 --- a/app/Policies/DocumentCategoryPolicy.php +++ b/app/Policies/DocumentCategoryPolicy.php @@ -8,7 +8,7 @@ use Uwil\LaravelBackend\Policies\Rules\UserStaticRules; class DocumentCategoryPolicy { - /** + /** * Determine whether the user can view any models. * * @param \Illuminate\Database\Eloquent\Model $authModel diff --git a/app/Policies/DocumentPolicy.php b/app/Policies/DocumentPolicy.php index 728b25e7..0d982d9a 100644 --- a/app/Policies/DocumentPolicy.php +++ b/app/Policies/DocumentPolicy.php @@ -79,7 +79,6 @@ class DocumentPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool diff --git a/app/Policies/NewsCategoryPolicy.php b/app/Policies/NewsCategoryPolicy.php index ba2ccf8d..32a6c7d2 100644 --- a/app/Policies/NewsCategoryPolicy.php +++ b/app/Policies/NewsCategoryPolicy.php @@ -90,7 +90,6 @@ class NewsCategoryPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool @@ -102,7 +101,6 @@ class NewsCategoryPolicy * Determine whether the user can force delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function forceDelete(Model $authModel): bool diff --git a/app/Policies/NewsPolicy.php b/app/Policies/NewsPolicy.php index b692287c..6c5ae3a4 100644 --- a/app/Policies/NewsPolicy.php +++ b/app/Policies/NewsPolicy.php @@ -90,7 +90,6 @@ class NewsPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool @@ -102,7 +101,6 @@ class NewsPolicy * Determine whether the user can force delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function forceDelete(Model $authModel): bool diff --git a/app/Policies/NewsTagPolicy.php b/app/Policies/NewsTagPolicy.php index 5fd74a78..d1f775a0 100644 --- a/app/Policies/NewsTagPolicy.php +++ b/app/Policies/NewsTagPolicy.php @@ -90,7 +90,6 @@ class NewsTagPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool @@ -102,7 +101,6 @@ class NewsTagPolicy * Determine whether the user can force delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function forceDelete(Model $authModel): bool diff --git a/app/Providers/DynamicPageRouteServiceProvider.php b/app/Providers/DynamicPageRouteServiceProvider.php index 9ba17f7c..b71a0317 100644 --- a/app/Providers/DynamicPageRouteServiceProvider.php +++ b/app/Providers/DynamicPageRouteServiceProvider.php @@ -53,7 +53,9 @@ class DynamicPageRouteServiceProvider extends ServiceProvider $slug = $dynamicPageModel->getTranslation('slug', $locale); // If no slug for the locale → skip. - if (!empty($slug) && !$slug) continue; + if (!empty($slug) && !$slug) { + continue; + } // Retrieves the parent segments for this locale. $segments = DynamicPageHelper::getAllDynamicPageSegments( @@ -63,7 +65,9 @@ class DynamicPageRouteServiceProvider extends ServiceProvider ); // If a parent does not have a slug in this locale → skip. - if ($segments === null) continue; + if ($segments === null) { + continue; + } $segmentsPath = implode('/', $segments); $finalPath = $segmentsPath ? "/{$segmentsPath}/{$slug}" : "/{$slug}"; @@ -75,9 +79,9 @@ class DynamicPageRouteServiceProvider extends ServiceProvider }) ->defaults('dynamicPage', $dynamicPageModel) ->name("front.dynamic-pages.{$dynamicPageModel->id_key}.{$locale}"); - } + } //end foreach }); - } + } //end foreach // Share all published dynamic pages to all blade views. foreach ($dynamicPageModels as $dynamicPageModel) { diff --git a/app/Traits/Models/HasCache.php b/app/Traits/Models/HasCache.php index 664622ac..396366f1 100644 --- a/app/Traits/Models/HasCache.php +++ b/app/Traits/Models/HasCache.php @@ -61,9 +61,12 @@ trait HasCache /** @var \Illuminate\Database\Eloquent\Model $class */ return $class::query() - ->when(property_exists($class, 'cacheRelations') && is_array($class::$cacheRelations), function ($query) use ($class) { - $query->with($class::$cacheRelations); - }) + ->when( + property_exists($class, 'cacheRelations') && is_array($class::$cacheRelations), + function ($query) use ($class) { + $query->with($class::$cacheRelations); + } + ) ->get(); }); } diff --git a/app/Traits/Models/HasUwilImages.php b/app/Traits/Models/HasUwilImages.php index f8319db4..593843ab 100644 --- a/app/Traits/Models/HasUwilImages.php +++ b/app/Traits/Models/HasUwilImages.php @@ -5,7 +5,6 @@ namespace App\Traits\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; use Uwil\LaravelCommon\Helpers\FileHelper; use Uwil\LaravelCommon\Helpers\ToolboxHelper; @@ -18,15 +17,16 @@ trait HasUwilImages * - champs basique translatable - image et wisigiw * - prise en compte du trait softDetele * - * non testé : - * - la suppression totale des images dans un champs translatable // ça fonctionne mais il y a des changements à mettre dans FileHelper + * Non testé : + * - la suppression totale des images dans un champs translatable + * (ça fonctionne mais il y a des changements à mettre dans FileHelper) * - le cas ou le champs (ancien et current) ne sont que des tableaux (non translatable) - * - la récursivité dans traverseAndManage, je ne suis pour l'instant passé qu'une fois dans cette méthode, via un champs translatable + * - la récursivité dans traverseAndManage, + * je ne suis pour l'instant passé qu'une fois dans cette méthode, via un champs translatable * * TODO : * - ajouter la possibilité de viser un nest array dans les tableau de fields * - job pour nettoyer les models - * */ protected const UPDATE_ACTION = 'update'; @@ -61,8 +61,7 @@ trait HasUwilImages /** * Get the field that are images, from the array in the model * - * @param Model $model - * + * @param \Illuminate\Database\Eloquent\Model $model * @return array */ protected static function getImageFields(Model $model): array @@ -76,8 +75,7 @@ trait HasUwilImages /** * Get the field that are wysiwyg, from the array in the model * - * @param Model $model - * + * @param \Illuminate\Database\Eloquent\Model $model * @return array */ protected static function getWysiwygFields(Model $model): array @@ -91,13 +89,14 @@ trait HasUwilImages /** * Loop over the image or wysiwyg fields * - * @param array $fields - * @param Model $model - * @param boolean $isTranslatable - * @param mixed $locale - * @param array $availableLocales - * @param bool $forceDeleteImage - * @param string $fieldType + * @param array $fields + * @param \Illuminate\Database\Eloquent\Model $model + * @param boolean $isTranslatable + * @param mixed $locale + * @param array $availableLocales + * @param boolean $forceDeleteImage + * @param string $fieldType + * @return void */ protected static function loopOverFields( array $fields, @@ -109,7 +108,7 @@ trait HasUwilImages string $fieldType = self::IMAGE ): void { foreach ($fields as $field) { - $currentValue = data_get($model->getAttributes(), $field); + $currentValue = data_get($model->getAttributes(), $field); $originalValue = data_get($model->getOriginal(), $field); if (is_null($currentValue) && is_null($originalValue)) { @@ -117,12 +116,8 @@ trait HasUwilImages } if (is_array($originalValue) && $isTranslatable) { - $localesToProcess = ($forceDeleteImage) - ? $availableLocales // on delete it's all the locales - : [$locale]; // on update it's only the currentLocale - + $localesToProcess = ($forceDeleteImage) ? $availableLocales : [$locale]; foreach ($localesToProcess as $lang) { - $oldLocaleVal = $originalValue[$lang] ?? []; $newLocaleVal = json_decode(data_get($model->getAttributes(), $field), true)[$lang] ?? []; @@ -137,9 +132,9 @@ trait HasUwilImages ); } continue; - } + } //end if - // PAS TESTE + // PAS TESTE. if (is_array($originalValue) && is_array($currentValue)) { dd('juste array'); static::traverseAndManage( @@ -154,7 +149,7 @@ trait HasUwilImages } static::manageField($model, $originalValue, $currentValue, $field, $forceDeleteImage, $fieldType); - } + } //end foreach } /** @@ -163,22 +158,38 @@ trait HasUwilImages * Determines field types, handles localization, and delegates processing to `loopOverFields()` * for each supported field type. Used during update or forced delete events. * - * @param Model $model The Eloquent model to process. - * @param string $eventType The event type (e.g. self::UPDATE_ACTION or self::FORCE_DELETE_ACTION). - * + * @param \Illuminate\Database\Eloquent\Model $model The Eloquent model to process. + * @param string $eventType The event type + * (e.g. self::UPDATE_ACTION or self::FORCE_DELETE_ACTION). * @return void */ protected static function initLoop(Model $model, string $eventType = self::UPDATE_ACTION): void { $forceDeleteImage = $eventType === self::FORCE_DELETE_ACTION; - $imagesFields = self::getImageFields($model); - $wysiwygFields = self::getWysiwygFields($model); - $isTranslatable = method_exists($model, 'getTranslations') ?? false; - $locale = config('app.locale'); + $imagesFields = self::getImageFields($model); + $wysiwygFields = self::getWysiwygFields($model); + $isTranslatable = method_exists($model, 'getTranslations') ?? false; + $locale = config('app.locale'); $availableLocales = array_keys(config('laravellocalization.supportedLocales', ['fr' => "Frenchouz"])); - self::loopOverFields($imagesFields, $model, $isTranslatable, $locale, $availableLocales, $forceDeleteImage, self::IMAGE); - self::loopOverFields($wysiwygFields, $model, $isTranslatable, $locale, $availableLocales, $forceDeleteImage, self::WYSIWYG); + self::loopOverFields( + $imagesFields, + $model, + $isTranslatable, + $locale, + $availableLocales, + $forceDeleteImage, + self::IMAGE, + ); + self::loopOverFields( + $wysiwygFields, + $model, + $isTranslatable, + $locale, + $availableLocales, + $forceDeleteImage, + self::WYSIWYG, + ); } /** @@ -187,35 +198,37 @@ trait HasUwilImages * Compares old and new values, determines if fields are lists, and delegates handling * of each field to `manageField()`. Supports recursive traversal for nested arrays. * - * @param Model $model The Eloquent model being processed. - * @param array $old The previous state of the data. - * @param array $new The new state of the data. - * @param string $fieldPath The current dot-notated path of the field. - * @param bool $forceDeleteImage Whether to force deletion of old images. - * @param string $fieldType The type of field being managed (default: self::IMAGE). - * @param string|null $locale The locale associated with the field, if any. + * @param \Illuminate\Database\Eloquent\Model $model The Eloquent model being processed. + * @param array $old The previous state of the data. + * @param array $new The new state of the data. + * @param string $fieldPath The current dot-notated path of the field. + * @param boolean $forceDeleteImage Whether to force deletion of old images. + * @param string $fieldType The type of field being managed + * (default: self::IMAGE). + * @param string|null $locale The locale associated with the field, if any. * * @return void */ protected static function traverseAndManage( - Model $model, - array $old, - array $new, - string $fieldPath, - bool $forceDeleteImage, - string $fieldType = self::IMAGE, + Model $model, + array $old, + array $new, + string $fieldPath, + bool $forceDeleteImage, + string $fieldType = self::IMAGE, ?string $locale = null ): void { $allKeys = self::getFieldKeys($old, $new); - // This boolean is used to know if we need to keep the index (key) of the array or not e.g do we want to keep content.fr.0 or just content.fr + // This boolean is used to know if we need to keep the index (key) of the array, + // or not e.g do we want to keep content.fr.0 or just content.fr. $isList = self::isMeaningfulList($old) || self::isMeaningfulList($new); foreach ($allKeys as $key) { $oldValue = $old[$key] ?? null; $newValue = $new[$key] ?? null; - $path = $isList ? "$fieldPath.$key" : (is_int($key) ? $fieldPath : "$fieldPath.$key"); - // TODO cette récursivité n'a pas encore été testé + $path = $isList ? "$fieldPath.$key" : (is_int($key) ? $fieldPath : "$fieldPath.$key"); + // TODO cette récursivité n'a pas encore été testé. if (is_array($oldValue) || is_array($newValue)) { dd('pas testé'); static::traverseAndManage( @@ -243,8 +256,8 @@ trait HasUwilImages * This helps distinguish between true lists of complex data * and simple value arrays like ["foo", "bar"]. * - * @param array $array - * @return bool + * @param array $array + * @return boolean */ private static function isMeaningfulList(array $array): bool { @@ -260,8 +273,8 @@ trait HasUwilImages * Useful for comparing field values or recursively traversing * nested array structures. * - * @param array $old - * @param array $new + * @param array $old + * @param array $new * @return \Illuminate\Support\Collection */ protected static function getFieldKeys(array $old, array $new): \Illuminate\Support\Collection @@ -274,13 +287,13 @@ trait HasUwilImages /** * Get the image field and manage the store image. * - * @param Model $model - * @param mixed $oldValue - * @param mixed $newValue - * @param mixed $fieldName The fieldName, can be nested e.g content.image - * @param bool $forceDeleteImage Does the image be force deleted, even if old and new value are the same (on delete model most of case) - * @param string $fieldType Choice between WYSIWYG and IMAGE - * + * @param \Illuminate\Database\Eloquent\Model $model + * @param mixed $oldValue + * @param mixed $newValue + * @param mixed $fieldName The fieldName, can be nested e.g content.image. + * @param boolean $forceDeleteImage Does the image be force deleted, + * even if old and new value are the same (on delete model most of case). + * @param string $fieldType Choice between WYSIWYG and IMAGE. * @return void */ protected static function manageField( @@ -289,31 +302,30 @@ trait HasUwilImages mixed $newValue, mixed $fieldName, bool $forceDeleteImage, - $fieldType = self::IMAGE + string $fieldType = self::IMAGE ) { if ($fieldType === self::IMAGE) { - // Cas 1 : Valeurs identiques -> only for force deleting model + // Cas 1 : Valeurs identiques -> only for force deleting model. if ((is_string($oldValue) === is_string($newValue)) && $forceDeleteImage) { - // In this case we need to remove the actual file, not the old as we do in other conditions + // In this case we need to remove the actual file, not the old as we do in other conditions. $path = ToolboxHelper::mbReplace('storage/', '', $newValue); if (Storage::disk('public')->exists($path)) { Storage::disk('public')->delete($path); } } - // // Cas 2 : ancienne = string, nouvelle = null → suppression + // // Cas 2 : ancienne = string, nouvelle = null → suppression. if (is_string($oldValue) && is_null($newValue)) { - // Action suppression + // Action suppression. FileHelper::removeOldFile($model, $fieldName); } - // // Cas 3 : ancienne = null, nouvelle = string → ajout - - // // Cas 4 : ancienne = string, nouvelle = autre string → remplacement + // // Cas 3 : ancienne = null, nouvelle = string → ajout. + // // Cas 4 : ancienne = string, nouvelle = autre string → remplacement. if (is_string($oldValue) && is_string($newValue) && $oldValue !== $newValue) { FileHelper::removeOldFile($model, $fieldName); } - } + } //end if if ($fieldType === self::WYSIWYG) { $valueToPass = $forceDeleteImage ? '' : ($newValue ?? ''); @@ -329,7 +341,7 @@ trait HasUwilImages * Recursively processes attribute values to store uploaded files via `FileHelper::storeFile()`, * and applies the transformed data to the model using `fill()`. * - * @param array $attributes The attributes to fill the model with. + * @param array $attributes The attributes to fill the model with. * @return void */ public function inertiaFill(array $attributes): void @@ -343,12 +355,13 @@ trait HasUwilImages /** * Store recursively all uploaded files in array. * + * @param array $content * @return array */ private function processContentFiles(array $content): array { return collect($content) - ->map(function ($value, $key) { + ->map(function ($value) { // Check the pattern of the key and the type of value. if ($value instanceof UploadedFile) { return FileHelper::storeFile($this, $value); diff --git a/app/Traits/Requests/Api/HasLaravelFailedValidation.php b/app/Traits/Requests/Api/HasLaravelFailedValidation.php index 7f834473..3f273d07 100644 --- a/app/Traits/Requests/Api/HasLaravelFailedValidation.php +++ b/app/Traits/Requests/Api/HasLaravelFailedValidation.php @@ -9,8 +9,10 @@ trait HasLaravelFailedValidation { /** * Set manually a failed ajax response. - * - * @return \Illuminate\Http\Exceptions\HttpResponseException + * + * @param \Illuminate\Contracts\Validation\Validator $validator + * @return void + * @throws \Illuminate\Http\Exceptions\HttpResponseException Override ajax code error. */ protected function failedValidation(Validator $validator): \Illuminate\Http\Exceptions\HttpResponseException { diff --git a/app/Traits/Requests/HasInertiaPicture.php b/app/Traits/Requests/HasInertiaPicture.php index 45b5682b..f38ed71c 100644 --- a/app/Traits/Requests/HasInertiaPicture.php +++ b/app/Traits/Requests/HasInertiaPicture.php @@ -2,7 +2,7 @@ namespace App\Traits\Requests; -use \Illuminate\Http\UploadedFile; +use Illuminate\Http\UploadedFile; trait HasInertiaPicture { @@ -17,7 +17,7 @@ trait HasInertiaPicture return; } $original = $this->all(); - $merged = self::arrayMergeRecursiveDistinct($original, $this->convertedFiles); + $merged = self::arrayMergeRecursiveDistinct($original, $this->convertedFiles); $this->replace($merged); } @@ -89,6 +89,7 @@ trait HasInertiaPicture // String path validations. if (is_string($value)) { // Validate the path. + // phpcs:ignore Generic.Files.LineLength $pattern = '/^storage\/modelfiles\/[a-zA-Z0-9_]+\/[0-9]{2}\/[0-9]{2}\/[0-9]{2}\/[a-zA-Z0-9]{2}\/[a-zA-Z0-9_-]+/'; if (!preg_match($pattern, $value)) { $fail(trans('validation.file_path', ['attribute' => $this->attributes()[$attribute]])); @@ -99,7 +100,7 @@ trait HasInertiaPicture $mimesRule = collect($rules)->first(fn($r) => str_starts_with($r, 'mimes:')); if ($mimesRule) { $allowedExtensions = explode(',', str_replace('mimes:', '', $mimesRule)); - $ext = strtolower(pathinfo($value, PATHINFO_EXTENSION)); + $ext = strtolower(pathinfo($value, PATHINFO_EXTENSION)); if (!in_array($ext, $allowedExtensions)) { $fail(trans('validation.mimetypes', [ 'attribute' => $this->attributes()[$attribute], @@ -109,7 +110,7 @@ trait HasInertiaPicture } return; - } + } //end if // Unmanaged case (not null, not UploadedFile, not string). $fail("Invalide type for $attribute."); diff --git a/app/View/Components/Front/News/NewsNextEventComponent.php b/app/View/Components/Front/News/NewsNextEventComponent.php index 1f9a4cad..ae85b805 100644 --- a/app/View/Components/Front/News/NewsNextEventComponent.php +++ b/app/View/Components/Front/News/NewsNextEventComponent.php @@ -2,18 +2,14 @@ namespace App\View\Components\Front\News; -use Closure; use App\Models\News; use App\Models\NewsTag; use App\Models\NewsCategory; use Illuminate\View\Component; -use App\Enums\News\NewsStatusEnum; -use Illuminate\Contracts\View\View; -use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Cache; class NewsNextEventComponent extends Component { + /** @var array<\App\Models\News> $nextEvents List of published news. */ public $nextEvents; /** @@ -43,8 +39,10 @@ class NewsNextEventComponent extends Component /** * Get the view / contents that represent the component. + * + * @return \Illuminate\Contracts\View\View */ - public function render(): View|Closure|string + public function render(): \Illuminate\Contracts\View\View { return view('components.front.news.news-next-event-component', [ 'nextEvents' => $this->nextEvents diff --git a/app/View/Components/Front/Pages/KnowUs/OurImplantations.php b/app/View/Components/Front/Pages/KnowUs/OurImplantations.php index 344e5fdd..d2b43285 100644 --- a/app/View/Components/Front/Pages/KnowUs/OurImplantations.php +++ b/app/View/Components/Front/Pages/KnowUs/OurImplantations.php @@ -8,15 +8,25 @@ use Illuminate\View\Component; class OurImplantations extends Component { + /** @var string $id Identification of the section. */ public string $id; + + /** @var $implantations Content section. */ public $implantations; + + /** @var array<\App\Models\Company> $companyModels List of published companies. */ public $companyModels; + + /** @var array<\App\Models\CompanyActivity> $companyActivityModels List of published company activities. */ public $companyActivityModels; /** * Create a new component instance. + * + * @param string $id + * @param array $implantations */ - public function __construct($id, $implantations) + public function __construct(string $id, array $implantations) { $this->id = $id; $this->implantations = $implantations; @@ -32,13 +42,14 @@ class OurImplantations extends Component /** * Get the view / contents that represent the component. * - * @return \Illuminate\Contracts\View\View|\Closure|string + * @return \Illuminate\Contracts\View\View */ - public function render(): \Illuminate\Contracts\View\View|\Closure|string + public function render(): \Illuminate\Contracts\View\View { return view('components.front.pages.know-us.our-implantations', [ 'companyModels' => $this->companyModels, 'companyActivityModels' => $this->companyActivityModels, + 'implantations' => $this->implantations, ]); } } diff --git a/config/app.php b/config/app.php index 849f6840..da6e0304 100644 --- a/config/app.php +++ b/config/app.php @@ -80,7 +80,7 @@ return [ 'locale' => env('APP_LOCALE', 'fr'), - // FIXME: need this because of uwil packages + // FIXME: need this because of uwil packages. 'locales' => [ 'en', 'fr', diff --git a/config/cache.php b/config/cache.php index 041581a2..838d7090 100644 --- a/config/cache.php +++ b/config/cache.php @@ -59,9 +59,7 @@ return [ env('MEMCACHED_USERNAME'), env('MEMCACHED_PASSWORD'), ], - 'options' => [ - // Memcached::OPT_CONNECT_TIMEOUT => 2000, - ], + 'options' => [], 'servers' => [ [ 'host' => env('MEMCACHED_HOST', '127.0.0.1'), diff --git a/config/database.php b/config/database.php index 9180f7a4..b73302c5 100644 --- a/config/database.php +++ b/config/database.php @@ -108,8 +108,6 @@ return [ 'charset' => env('DB_CHARSET', 'utf8'), 'prefix' => '', 'prefix_indexes' => true, - // 'encrypt' => env('DB_ENCRYPT', 'yes'), - // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), ], ], diff --git a/config/sentry.php b/config/sentry.php index 834cf88e..81860abd 100644 --- a/config/sentry.php +++ b/config/sentry.php @@ -51,11 +51,11 @@ return [ 'missing_routes' => false, ], - // @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#send-default-pii. + // See: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#send-default-pii. 'send_default_pii' => env('SENTRY_SEND_DEFAULT_PII', false), - // @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate. - 'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float)env('SENTRY_TRACES_SAMPLE_RATE'), + // See: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate. + 'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float) env('SENTRY_TRACES_SAMPLE_RATE'), 'before_send' => [\Uwil\LaravelCommon\Helpers\ExceptionsHelper::class, 'sentryEventHandler'], ]; diff --git a/database/factories/CompanyActivityFactory.php b/database/factories/CompanyActivityFactory.php index ad54f07a..e25765db 100644 --- a/database/factories/CompanyActivityFactory.php +++ b/database/factories/CompanyActivityFactory.php @@ -3,7 +3,6 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\CompanyActivity> diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php index a4974a8a..1c5a90df 100644 --- a/database/factories/CompanyFactory.php +++ b/database/factories/CompanyFactory.php @@ -2,11 +2,9 @@ namespace Database\Factories; -use App\Enums\DynamicFieldTypes; use App\Models\CompanyActivity; use App\Models\CompanySector; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Company> diff --git a/database/factories/CompanySectorFactory.php b/database/factories/CompanySectorFactory.php index 9c8afb13..bdc03832 100644 --- a/database/factories/CompanySectorFactory.php +++ b/database/factories/CompanySectorFactory.php @@ -3,7 +3,6 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\CompanySector> diff --git a/database/factories/DocumentFactory.php b/database/factories/DocumentFactory.php index f8938b51..6c077250 100644 --- a/database/factories/DocumentFactory.php +++ b/database/factories/DocumentFactory.php @@ -4,11 +4,7 @@ namespace Database\Factories; use App\Enums\Document\DocumentStatusEnum; use App\Enums\YearsEnum; -use App\Models\Document; -use App\Models\DocumentCategory; -use App\Models\DocumentTag; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Document> @@ -23,10 +19,10 @@ class DocumentFactory extends Factory public function definition(): array { return [ - 'name' => $this->faker->sentence(3), - 'exercice' => $this->faker->randomElement(YearsEnum::cases()), - 'status' => $this->faker->randomElement(DocumentStatusEnum::cases()), - 'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'), + 'name' => $this->faker->sentence(3), + 'exercice' => $this->faker->randomElement(YearsEnum::cases()), + 'status' => $this->faker->randomElement(DocumentStatusEnum::cases()), + 'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'), ]; } } diff --git a/database/factories/DynamicPageFactory.php b/database/factories/DynamicPageFactory.php index 37a427b3..44787159 100644 --- a/database/factories/DynamicPageFactory.php +++ b/database/factories/DynamicPageFactory.php @@ -46,9 +46,11 @@ class DynamicPageFactory extends Factory * * @param \App\Models\PageConfig $configModel * @return array + * @phpcs:disable Generic.Metrics.CyclomaticComplexity */ private function getDataFromConfig(PageConfig $configModel): array { + // phpcs:enable foreach ($configModel->config as $field) { switch ($field['type']) { case DynamicFieldTypes::string->value: @@ -87,7 +89,7 @@ class DynamicPageFactory extends Factory default: $configValue = []; break; - } + } //end switch } //end foreach return $configValue; } diff --git a/database/factories/NewsFactory.php b/database/factories/NewsFactory.php index 96b0ea35..dee015fc 100644 --- a/database/factories/NewsFactory.php +++ b/database/factories/NewsFactory.php @@ -3,8 +3,6 @@ namespace Database\Factories; use App\Enums\News\NewsStatusEnum; -use App\Models\News; -use App\Models\NewsCategory; use Illuminate\Database\Eloquent\Factories\Factory; /** diff --git a/database/factories/PageConfigFactory.php b/database/factories/PageConfigFactory.php index 558b4eb6..18215f5c 100644 --- a/database/factories/PageConfigFactory.php +++ b/database/factories/PageConfigFactory.php @@ -35,7 +35,7 @@ class PageConfigFactory extends Factory ]; if ($enum->value === DynamicFieldTypes::list->value) { // Set only one string input for the example. - $defaultEnum = DynamicFieldTypes::string; + $defaultEnum = DynamicFieldTypes::string; $data['config'][0]['children'] = [ [ 'type' => $defaultEnum->value(), diff --git a/lang/en/back.php b/lang/en/back.php index 2bfda18b..f7572ab5 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -368,6 +368,7 @@ return [ ], "static_route" => [ "no_route_defined" => "no route defined in the config file", + "select_value" => "select a value from the list", ], "associated_model" => "associated :model|associated :model", ]; diff --git a/lang/en/front.php b/lang/en/front.php index c3e50453..77ef01cb 100644 --- a/lang/en/front.php +++ b/lang/en/front.php @@ -127,6 +127,7 @@ return [ 'search' => [ 'seo_title' => 'You searched for :terms', 'seo_description' => 'Search for a word on the entire LDC.fr website', + 'title' => 'Search', 'placeholder' => 'Your search', 'results_total' => ':nbr results for ":terms"', 'no_results' => 'No results found.', diff --git a/lang/fr/back.php b/lang/fr/back.php index 9a3100a3..ffedbaf9 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -369,6 +369,7 @@ return [ ], "static_route" => [ "no_route_defined" => "aucune route définie dans le fichier de config", + "select_value" => "sélectionnez une valeur dans la liste", ], "associated_model" => ":model associés|:model associées", ]; diff --git a/lang/fr/front.php b/lang/fr/front.php index 2125549f..5b94a04e 100644 --- a/lang/fr/front.php +++ b/lang/fr/front.php @@ -128,6 +128,7 @@ return [ 'search' => [ 'seo_title' => 'Vous avez cherché :terms', 'seo_description' => 'Recherche de mot sur la globalité du site LDC.fr', + 'title' => 'Recherche', 'placeholder' => 'Votre recherche', 'results_total' => ':nbr résultats pour ":terms"', 'no_results' => 'Aucun résultat trouvé.', @@ -141,8 +142,8 @@ return [ 'recaptcha_protect' => 'Ce site est protégé par reCAPTCHA et la politique de confidentialité et les conditions d\'utilisation de Google s\'appliquent.', 'pratical' => 'pratique', 'our_offers' => [ - 'title' => 'nos offres', - 'subtitle' => 'd\'emploi, de stage et d\'alternance', + 'title' => 'nos offres', + 'subtitle' => 'd\'emploi, de stage et d\'alternance', 'link_text' => 'accédez à notre portail de recrutement' ], 'discover_our_jobs' => 'découvrez nos métiers' diff --git a/package-lock.json b/package-lock.json index 0f74969c..4c2e8353 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "@tiptap/extension-image": "^3.17.0", "@tiptap/extension-invisible-characters": "^3.17.1", "@tiptap/extension-italic": "^3.17.0", + "@tiptap/extension-link": "^3.19.0", "@tiptap/extension-list": "^3.17.1", "@tiptap/extension-ordered-list": "^3.17.0", "@tiptap/extension-placeholder": "^3.17.0", @@ -47,6 +48,7 @@ "@types/react-dom": "^19.1.7", "axios": "^1.13.2", "chart.js": "^4.5.1", + "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "date-fns": "^4.1.0", @@ -55,6 +57,7 @@ "laravel-vite-plugin": "^1.3.0", "lucide-react": "^0.503.0", "motion": "^12.23.12", + "prosemirror-state": "^1.4.4", "react-color": "^2.19.3", "react-day-picker": "^9.11.1", "react-dropzone": "^14.3.8", @@ -85,7 +88,7 @@ "@typescript-eslint/parser": "^8.39.0", "@vitejs/plugin-react": "^4.7.0", "autoprefixer": "^10.4.21", - "class-variance-authority": "^0.7.1", + "baseline-browser-mapping": "^2.9.19", "concurrently": "^9.2.0", "eslint": "^8.57.1", "eslint-config-airbnb": "^19.0.4", @@ -4022,16 +4025,16 @@ } }, "node_modules/@tiptap/core": { - "version": "3.17.1", - "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.17.1.tgz", - "integrity": "sha512-f8hB9MzXqsuXoF9qXEDEH5Fb3VgwhEFMBMfk9EKN88l5adri6oM8mt2XOWVxVVssjpEW0177zXSLPKWzoS/vrw==", + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.19.0.tgz", + "integrity": "sha512-bpqELwPW+DG8gWiD8iiFtSl4vIBooG5uVJod92Qxn3rA9nFatyXRr4kNbMJmOZ66ezUvmCjXVe/5/G4i5cyzKA==", "license": "MIT", "funding": { "type": "github", "url": "https://github.com/sponsors/ueberdosis" }, "peerDependencies": { - "@tiptap/pm": "^3.17.1" + "@tiptap/pm": "^3.19.0" } }, "node_modules/@tiptap/extension-blockquote": { @@ -4281,9 +4284,9 @@ } }, "node_modules/@tiptap/extension-link": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.17.0.tgz", - "integrity": "sha512-qGL/s7RxgWL1dY3ZPsPtBYQsfiNpwnqoK5dVQ7NbqjphK1EF/Q4uBRVM3CKMZiRBHdRlSVZewBycHs4uyAKPbA==", + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.19.0.tgz", + "integrity": "sha512-HEGDJnnCPfr7KWu7Dsq+eRRe/mBCsv6DuI+7fhOCLDJjjKzNgrX2abbo/zG3D/4lCVFaVb+qawgJubgqXR/Smw==", "license": "MIT", "dependencies": { "linkifyjs": "^4.3.2" @@ -4293,8 +4296,8 @@ "url": "https://github.com/sponsors/ueberdosis" }, "peerDependencies": { - "@tiptap/core": "^3.17.0", - "@tiptap/pm": "^3.17.0" + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" } }, "node_modules/@tiptap/extension-list": { @@ -4538,9 +4541,9 @@ } }, "node_modules/@tiptap/pm": { - "version": "3.17.1", - "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.17.1.tgz", - "integrity": "sha512-UyVLkN8axV/zop6Se2DCBJRu5DM21X0XEQvwEC5P/vk8eC9OcQZ3FLtxeYy2ZjpAZUzBGLw0/BGsmEip/n7olw==", + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.19.0.tgz", + "integrity": "sha512-789zcnM4a8OWzvbD2DL31d0wbSm9BVeO/R7PLQwLIGysDI3qzrcclyZ8yhqOEVuvPitRRwYLq+mY14jz7kY4cw==", "license": "MIT", "dependencies": { "prosemirror-changeset": "^2.3.0", @@ -5804,9 +5807,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.8.29", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.29.tgz", - "integrity": "sha512-sXdt2elaVnhpDNRDz+1BDx1JQoJRuNk7oVlAlbGiFkLikHCAQiccexF/9e91zVi6RCgqspl04aP+6Cnl9zRLrA==", + "version": "2.9.19", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.19.tgz", + "integrity": "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==", "dev": true, "license": "Apache-2.0", "bin": { @@ -6087,7 +6090,6 @@ "version": "0.7.1", "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", - "dev": true, "license": "Apache-2.0", "dependencies": { "clsx": "^2.1.1" diff --git a/package.json b/package.json index 183e448d..82df468c 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "eslint-fix": "node ./node_modules/.bin/eslint --config './.eslintrc.cjs' --max-warnings 0 resources/ts --ext .ts,.tsx --fix", "eslint-ci": "node ./node_modules/.bin/eslint --config './.eslintrc.cjs' --max-warnings 0 resources/ts --ext .ts,.tsx -f junit", "stylelint": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --max-warnings 0 '**/resources/**/*.scss'", + "stylelint-fix": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --max-warnings 0 '**/resources/**/*.scss' --fix", "stylelint-ci": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --max-warnings 0 '**/resources/**/*.scss' -f json" }, "devDependencies": { @@ -32,7 +33,7 @@ "@typescript-eslint/parser": "^8.39.0", "@vitejs/plugin-react": "^4.7.0", "autoprefixer": "^10.4.21", - "class-variance-authority": "^0.7.1", + "baseline-browser-mapping": "^2.9.19", "concurrently": "^9.2.0", "eslint": "^8.57.1", "eslint-config-airbnb": "^19.0.4", @@ -85,6 +86,7 @@ "@tiptap/extension-image": "^3.17.0", "@tiptap/extension-invisible-characters": "^3.17.1", "@tiptap/extension-italic": "^3.17.0", + "@tiptap/extension-link": "^3.19.0", "@tiptap/extension-list": "^3.17.1", "@tiptap/extension-ordered-list": "^3.17.0", "@tiptap/extension-placeholder": "^3.17.0", @@ -104,6 +106,7 @@ "@types/react-dom": "^19.1.7", "axios": "^1.13.2", "chart.js": "^4.5.1", + "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "date-fns": "^4.1.0", @@ -112,6 +115,7 @@ "laravel-vite-plugin": "^1.3.0", "lucide-react": "^0.503.0", "motion": "^12.23.12", + "prosemirror-state": "^1.4.4", "react-color": "^2.19.3", "react-day-picker": "^9.11.1", "react-dropzone": "^14.3.8", diff --git a/public/assets/css/style.css b/public/assets/css/style.css index 9840ede4..19bcec9a 100644 --- a/public/assets/css/style.css +++ b/public/assets/css/style.css @@ -1163,16 +1163,6 @@ textarea:focus { display: none; } -/* TODO : Utilité ? */ -/*body > div.page-respect > div.textblock.fw.fw-container.textblock_bg.toghether-footprint > div > div:nth-child(3) > div.textblock__image.textblock__block > div:nth-child(2) { - display: none; -} -.page-template-page-finance .btn__icon_dl { - background-image: url('../img/btn__icon_eye.png'); - width: 21px; - height: 14px; -} -*/ .wp-image-3124 { display: none; } diff --git a/resources/sass/back/app.scss b/resources/sass/back/app.scss index ba467341..6c67bc4f 100644 --- a/resources/sass/back/app.scss +++ b/resources/sass/back/app.scss @@ -1,7 +1,6 @@ @use '/node_modules/flag-icons/css/flag-icons.min.css'; @use './fonts'; @use './inputs/wysiwyg'; - @tailwind base; @tailwind components; @tailwind utilities; @@ -196,7 +195,7 @@ html { } .jer-edit-buttons > div:hover { - opacity: 80%; + opacity: 0.8; } .jer-copy-pulse:hover { @@ -205,4 +204,4 @@ html { .jer-collection-item-count { @apply cursor-pointer; -} \ No newline at end of file +} diff --git a/resources/sass/back/inputs/_color.scss b/resources/sass/back/inputs/_color.scss new file mode 100644 index 00000000..15f7746d --- /dev/null +++ b/resources/sass/back/inputs/_color.scss @@ -0,0 +1,101 @@ +.sketch-picker { + display: flex; + width: 100% !important; + flex-direction: column; + padding: 0 !important; + border: 0 !important; + box-shadow: none !important; +} + +.sketch-picker, +.sketch-picker .flexbox-fix { + gap: 0.375rem; +} + +.sketch-picker > div, +.sketch-picker .flexbox-fix > div { + padding: 0 !important; + margin: 0 !important; +} + +.sketch-picker > div:first-child { + border-radius: calc(var(--radius) - 2px); + aspect-ratio: 1 / 1; +} + +.sketch-picker > div:last-child { + justify-content: space-between; + padding-top: 0.375rem !important; +} + +.sketch-picker > div:nth-child(3) > div { + flex: auto !important; +} + +.sketch-picker > div:last-child > div { + width: 20px !important; + height: 20px !important; +} + +.sketch-picker > div:last-child > div > span > div { + border-radius: calc(var(--radius) - 2px) !important; + box-shadow: none !important; + outline: 1px solid hsl(var(--input)) !important; +} + +.sketch-picker > div:nth-child(2) > div:first-child { + display: flex; + flex-direction: column; + gap: 0.375rem; +} + +.sketch-picker > div:nth-child(2) > div:last-child { + display: none; +} + +.sketch-picker > div:nth-child(3) > div:first-child { + width: 16rem; +} + +.sketch-picker > div:nth-child(2) > div:first-child > div { + height: 20px !important; + border-radius: calc(var(--radius) - 2px); + margin: 0 !important; + cursor: pointer; + outline: 1px solid hsl(var(--input)); +} + +/* stylelint-disable-next-line selector-max-compound-selectors */ +.sketch-picker > div:first-child > div > div > div:last-child > div { + width: 10px !important; + height: 10px !important; + border-radius: 50% !important; + background-color: #fff; + box-shadow: none !important; + transform: translate(-5px, -5px) !important; +} + +/* stylelint-disable-next-line selector-max-compound-selectors */ +.sketch-picker > div:nth-child(2) > div:first-child > div > div > div > div > div { + width: 0.5rem !important; + height: 20px !important; + border: 1px hsl(var(--input)) solid; + border-radius: 0 !important; + margin-top: 0 !important; + background: #fff !important; + box-shadow: none !important; + transform: translateX(-4px) !important; +} + +.sketch-picker input { + width: 100% !important; + height: 2.5rem; + padding: 0.5rem 0.75rem !important; + border: 1px hsl(var(--input)) solid !important; + border-radius: calc(var(--radius) - 2px) !important; + background-color: hsl(var(--background)); + box-shadow: none !important; + color: var(--foreground); + outline: none; + text-align: center; +} diff --git a/resources/sass/back/inputs/_wysiwyg.scss b/resources/sass/back/inputs/_wysiwyg.scss index ed85066a..aaf4d392 100644 --- a/resources/sass/back/inputs/_wysiwyg.scss +++ b/resources/sass/back/inputs/_wysiwyg.scss @@ -16,7 +16,7 @@ @apply cursor-pointer; } - [data-type="taskList"] > li { + [data-type='taskList'] > li { @apply flex flex-row justify-start items-center gap-1.5; } diff --git a/resources/sass/common/_wysiwyg.scss b/resources/sass/common/_wysiwyg.scss index b6b82174..d2c96f03 100644 --- a/resources/sass/common/_wysiwyg.scss +++ b/resources/sass/common/_wysiwyg.scss @@ -1,44 +1,45 @@ $primary-color: #ff4e4e; -$secondary-color: #666666; -$tertiary-color: #222222; +$secondary-color: #666; +$tertiary-color: #222; +$quaternary-color: #fff; .description { - font-weight: 500; - font-size: 14px; - color: $secondary-color; - line-height: 1.75; display: flow-root; + color: $secondary-color; + font-size: 14px; + font-weight: 500; + line-height: 1.75; } .description.small { - font-style: italic; font-size: 14px; + font-style: italic; } .description h1 { + margin-bottom: 0.9em; font-size: 35px; line-height: 1.2; - margin-bottom: 0.9em; } .description h2 { + margin-bottom: 0.7em; font-size: 28px; line-height: 1.2; - margin-bottom: 0.7em; } .description h3 { + margin-bottom: 15px; + color: $tertiary-color; + font-size: 24px; font-weight: 500; line-height: 1.3; - font-size: 24px; - color: $tertiary-color; - margin-bottom: 15px; } .description h4 { - font-weight: 700; - font-size: 18px; margin-bottom: 10px; + font-size: 18px; + font-weight: 700; } .description p { @@ -53,10 +54,6 @@ $tertiary-color: #222222; color: $tertiary-color; } -.description a:hover { - cursor: pointer; -} - .description a:not(.btn) { display: contents; color: $primary-color; @@ -64,6 +61,7 @@ $tertiary-color: #222222; } .description a:hover { + cursor: pointer; text-decoration: none; } @@ -77,40 +75,40 @@ $tertiary-color: #222222; } .description ol { - list-style: decimal; padding-left: 0.75rem; + list-style: decimal; } .description ol li::marker { - font-size: 12px; - margin-right: 12px; margin-top: 6px; + margin-right: 12px; + font-size: 12px; } .description ul li { display: flex; - list-style: none; - font-weight: 500; - font-size: 16px; - color: $tertiary-color; margin-bottom: 15px; + color: $tertiary-color; + font-size: 16px; + font-weight: 500; + list-style: none; } .description ul li::before { - content: "\2714 \fe0e"; - flex: 0 0 auto; display: flex; - align-items: center; - justify-content: center; width: 18px; height: 18px; + flex: 0 0 auto; + align-items: center; + justify-content: center; border-radius: 100%; - background: $primary-color; - font-size: 12px; - color: white; - line-height: 1; - margin-right: 12px; margin-top: 6px; + margin-right: 12px; + background: $primary-color; + color: $quaternary-color; + content: '\2714 \fe0e'; + font-size: 12px; + line-height: 1; } .description figure figcaption { @@ -118,53 +116,61 @@ $tertiary-color: #222222; } .description blockquote, +/* stylelint-disable-next-line selector-class-pattern */ .manifest__quote { - font-size: 30px; margin-bottom: 15px; + font-size: 30px; } .description blockquote, +/* stylelint-disable-next-line selector-class-pattern */ .quote__text { - color: #222222; width: 90%; - font-family: "Satisfy"; + margin-bottom: 20px; + color: #222; + font-family: Satisfy, cursive; font-size: 2vw; line-height: 1.4; - margin-bottom: 20px; } .description blockquote::before, .description blockquote::after, +/* stylelint-disable-next-line selector-class-pattern */ .quote__text::before, +/* stylelint-disable-next-line selector-class-pattern */ .quote__text::after { - content: '"'; - color: #ff4e4e; + color: $primary-color; + content: '"'; } +/* stylelint-disable-next-line no-descending-specificity */ .description blockquote p, +/* stylelint-disable-next-line no-descending-specificity, selector-class-pattern */ .quote__text p { - display: inline; + display: inline; } -@media screen and (max-width: 1240px) { +@media screen and (width <= 1240px) { .description { font-size: 14px; } } -@media screen and (max-width: 767px) { + +@media screen and (width <= 767px) { .description { font-size: 17px; } + .description h3 { - line-height: 1.3; font-size: 24px; + line-height: 1.3; } + .description ul li { font-size: 17px; } + .description ul li::before { - color: white !important; + color: $quaternary-color !important; } } - - diff --git a/resources/sass/front/base/_common.scss b/resources/sass/front/base/_common.scss index d7f16195..013bbd5e 100644 --- a/resources/sass/front/base/_common.scss +++ b/resources/sass/front/base/_common.scss @@ -1,13 +1,12 @@ #newsletter-message { - margin: 6px 0; &.text-success { - color: green; + color: #008000; } &.text-danger { - color: red; + color: #f00; } &.d-none { diff --git a/resources/ts/back/Components/ApplicationLogo.tsx b/resources/ts/back/Components/ApplicationLogo.tsx index c4dd4774..1e7286ba 100644 --- a/resources/ts/back/Components/ApplicationLogo.tsx +++ b/resources/ts/back/Components/ApplicationLogo.tsx @@ -12,19 +12,27 @@ type ApplicationLogoProps = { isCollapsed?: boolean; }; +/** + * Get the logo. + * + * @param isCollapsed boolean + * @param forceLight boolean + * @param theme string + * @return string + */ +function getLogo(isCollapsed: boolean, forceLight: boolean, theme: string) { + if (isCollapsed) return logoTinyUwilCMS; + if (forceLight || theme === "dark") return logoUwilCMSLight; + return logoUwilCMSDark; +} + export default function ApplicationLogo({ forceLight = false, isCollapsed = false, }: ApplicationLogoProps) { const { theme } = useTheme(); const wrapperClasses = isCollapsed ? "h-8" : "w-full max-w-[10rem] mx-auto"; - const logo = isCollapsed - ? logoTinyUwilCMS - : forceLight - ? logoUwilCMSLight - : theme === "dark" - ? logoUwilCMSLight - : logoUwilCMSDark; + const logo = getLogo(isCollapsed, forceLight, theme); return ( { - const { companies } = props; - const columns = [ + +const getColumns = () => { + return [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( { accessorKey: "published", header: ({ column }: { column: { id: string } }) => ( { )} {str( - useTrans( + GetTranslation( row.getValue("published") ? "back.yes" : "back.no", ), ) @@ -70,7 +72,9 @@ const AssociatedCompaniesList = (props: Props) => { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( { ), cell: ({ row }: { row: Row }) => ( - {useFormatedDate(row.getValue("updated_at"))} + {GetFormatedDate(row.getValue("updated_at"))} ), }, ]; +}; + +export default function AssociatedCompaniesList(props: Props) { + const { companies } = props; + const columns = getColumns(); return ( <> @@ -109,6 +118,4 @@ const AssociatedCompaniesList = (props: Props) => { /> ); -}; - -export default AssociatedCompaniesList; +} diff --git a/resources/ts/back/Components/BtnOptionnalLinkWithTooltip.tsx b/resources/ts/back/Components/BtnOptionnalLinkWithTooltip.tsx index dc77b441..f4eebe55 100644 --- a/resources/ts/back/Components/BtnOptionnalLinkWithTooltip.tsx +++ b/resources/ts/back/Components/BtnOptionnalLinkWithTooltip.tsx @@ -1,6 +1,11 @@ // * Packages import { Link } from "@inertiajs/react"; -import { CSSProperties, MouseEventHandler, ReactNode } from "react"; +import { + ButtonHTMLAttributes, + CSSProperties, + MouseEventHandler, + ReactNode, +} from "react"; import { VariantProps } from "class-variance-authority"; // * Components shadcn import { Button, buttonVariants } from "@/components/ui/button"; @@ -9,12 +14,10 @@ import { TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; -// * Other -import { cn } from "@/lib/utils"; type ButtonVariant = VariantProps["variant"]; type ButtonSize = VariantProps["size"]; -type ButtonType = React.ButtonHTMLAttributes["type"]; +type ButtonType = ButtonHTMLAttributes["type"]; type BtnOptionnalLinkWithTooltipProps = { link?: string | null; @@ -27,7 +30,7 @@ type BtnOptionnalLinkWithTooltipProps = { externalLink?: boolean; disabled?: boolean; style?: CSSProperties; - onClick?: (e: React.MouseEvent) => void; + onClick?: MouseEventHandler; }; export default function BtnOptionnalLinkWithTooltip({ @@ -44,6 +47,22 @@ export default function BtnOptionnalLinkWithTooltip({ onClick, ...props }: BtnOptionnalLinkWithTooltipProps) { + let innerContent: ReactNode = content; + + if (link !== null) { + if (externalLink) { + innerContent = disabled ? ( + + ) : ( + + {content} + + ); + } else { + innerContent = {content}; + } + } + return ( @@ -56,24 +75,10 @@ export default function BtnOptionnalLinkWithTooltip({ disabled={disabled} onClick={onClick} style={style} + // eslint-disable-next-line react/jsx-props-no-spreading {...props} > - {link !== null ? ( - externalLink ? ( - - {content} - - ) : ( - {content} - ) - ) : ( - content - )} + {innerContent} {tooltipContent} diff --git a/resources/ts/back/Components/CustomSidebarTrigger.tsx b/resources/ts/back/Components/CustomSidebarTrigger.tsx index d552c7f5..871c96fd 100644 --- a/resources/ts/back/Components/CustomSidebarTrigger.tsx +++ b/resources/ts/back/Components/CustomSidebarTrigger.tsx @@ -28,7 +28,11 @@ export default function CustomSidebarTrigger() { className="rotate-180" size="icon" > - {state === "collapsed" ? : } + {state === "collapsed" ? ( + + ) : ( + + )} diff --git a/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx index 4cc541df..f11df65c 100644 --- a/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx +++ b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx @@ -7,43 +7,39 @@ import str from "@/hooks/use-string"; import DataTable from "@/back/Components/Table/DataTable"; import useTrans from "@/hooks/use-translations"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import { - AppEnv, - DocumentModel, - Resource, - TranslationField, -} from "@/back/types/global"; -import { Views } from "@/lib/utils"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { AppEnv, Resource } from "@/back/types/global"; +import { TranslationField } from "@/back/types/i18n"; +import { DocumentModel } from "@/back/types/others"; +import { GetTranslation, Views } from "@/lib/utils"; interface Props { documents: Resource; } -const AssociatedDocumentList = (props: Props) => { - const { documents } = props; - const { appEnv } = usePage().props as unknown as { - appEnv: AppEnv; - }; - const documentColumns = [ + +const getColumns = (appEnv: AppEnv) => { + return [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("name")); - }, + cell: ({ row }: { row: Row }) => ( + + ), }, { accessorKey: "path", header: ({ column }: { column: { id: string } }) => ( { - {appEnv.url + - "/" + + {`${appEnv.url}/${ (row.getValue("path") as TranslationField)[ appEnv.locale - ]} + ] + }`} ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, }, ]; +}; + +export default function AssociatedDocumentList(props: Props) { + const { documents } = props; + const { appEnv } = usePage().props as unknown as { + appEnv: AppEnv; + }; + const documentColumns = getColumns(appEnv); return ( <> @@ -104,6 +107,4 @@ const AssociatedDocumentList = (props: Props) => { /> ); -}; - -export default AssociatedDocumentList; +} diff --git a/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx b/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx index 783e47b8..99f2c146 100644 --- a/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx +++ b/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx @@ -9,9 +9,7 @@ type YearsEnumBadgeProps = { value: number; }; -export default function YearsEnumeBadge({ - value, -}: YearsEnumBadgeProps) { +export default function YearsEnumeBadge({ value }: YearsEnumBadgeProps) { const { enumYears } = usePage().props as unknown as { enumYears: LaravelEnum; }; @@ -19,9 +17,5 @@ export default function YearsEnumeBadge({ (status) => status.value === value, ); - return ( - - {enumValue?.label} - - ); + return {enumValue?.label}; } diff --git a/resources/ts/back/Components/Documents/Filters.tsx b/resources/ts/back/Components/Documents/Filters.tsx index 6e0bdbab..6539a292 100644 --- a/resources/ts/back/Components/Documents/Filters.tsx +++ b/resources/ts/back/Components/Documents/Filters.tsx @@ -7,17 +7,12 @@ import EnumFilter from "@/back/Components/Filters/EnumFilter"; import SwitchFilter from "@/back/Components/Filters/SwitchFilter"; import MultiSelectRelationFilter from "@/back/Components/Filters/MultiSelectRelationFilter"; import FiltersWrapper from "@/back/Components/FiltersWrapper"; -import { - DocumentCategoryModel, - DocumentTagModel, - LaravelEnum, -} from "@/back/types/global"; +import { LaravelEnum } from "@/back/types/global"; -const Filters = () => { +function Filters() { const modelName = usePage().props.modelName as string; - const categories = usePage().props.categories as DocumentCategoryModel[]; - const tags = usePage().props.tags as DocumentTagModel[]; - const enumDocumentStatus = usePage().props.enumDocumentStatus as LaravelEnum; + const enumDocumentStatus = usePage().props + .enumDocumentStatus as LaravelEnum; return ( @@ -25,17 +20,11 @@ const Filters = () => { enums={enumDocumentStatus} modelName={modelName} fieldName="status" - label={str( - useTrans( - "back.model_filters.select_status.label", - ), - ) + label={str(useTrans("back.model_filters.select_status.label")) .ucFirst() .value()} placeholder={str( - useTrans( - "back.model_filters.select_status.placeholder", - ), + useTrans("back.model_filters.select_status.placeholder"), ) .ucFirst() .value()} @@ -43,28 +32,18 @@ const Filters = () => { { targetModel="document_tag" fieldName="tags" modelName={modelName} - label={str( - useTrans( - "back.model_filters.tags.label", - ), - ) + label={str(useTrans("back.model_filters.tags.label")) .ucFirst() .value()} placeholder={str( - useTrans( - "back.model_filters.tags.placeholder", - ), + useTrans("back.model_filters.tags.placeholder"), ) .ucFirst() .value()} /> ); -}; +} export default Filters; diff --git a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx index 535bc7dd..00fa52a3 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx @@ -1,6 +1,5 @@ // * Packages import { usePage } from "@inertiajs/react"; -import { useEffect, useRef } from "react"; // * Other import SimpleString from "@/back/Components/Inputs/SimpleString"; import SimpleNumber from "@/back/Components/Inputs/SimpleNumber"; @@ -14,25 +13,23 @@ import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker"; import SimpleYoutubeId from "@/back/Components/Inputs/SimpleYoutubeId"; import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId"; import EnumSelect from "@/back/Components/Inputs/EnumSelect"; - +import StaticRouteSelect from "@/back/Components/Inputs/StaticRouteSelect"; +import DynamicWrapperModelSelect from "@/back/Components/DynamicPages/DynamicWrapperModelSelect"; +import { LaravelEnum } from "@/back/types/global"; import { ConfigField, DynamicFieldTypes, DynamicInternalField, - LaravelEnum, -} from "@/back/types/global"; +} from "@/back/types/dynamic-pages"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import { - extractExcludedIdFromExists, extractLaravelValidationValue, extractMinMaxFromValidation, extractRequiredValidation, - extractTableFromExists, } from "@/hooks/use-laravel-validation"; -import { ModelSelect } from "../Inputs/ModelSelect"; -import StaticRouteSelect from "../Inputs/StaticRouteSelect"; +/* eslint-disable no-unused-vars */ type DynamicInputsProps = { name: string; config: ConfigField[]; @@ -45,6 +42,7 @@ type DynamicInputsProps = { reset: (name?: string) => void; parentErrors?: Record | null; }; +/* eslint-enable no-unused-vars */ // Allows to get specific input from enum value. export default function DynamicInputs({ @@ -57,8 +55,10 @@ export default function DynamicInputs({ parentErrors, }: DynamicInputsProps) { // Enums. - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; - const enumElementPosition = usePage().props.enumElementPosition as LaravelEnum; + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; + const enumElementPosition = usePage().props + .enumElementPosition as LaravelEnum; // Translations. const transAssociateTo = useTrans("back.form_associate_to"); @@ -91,7 +91,8 @@ export default function DynamicInputs({ const fieldName = `${name}.${field.key}`; // Set the content value from the config key. - const fieldValue = content?.[field.key as keyof typeof content] ?? ""; + const fieldValue = + content?.[field.key as keyof typeof content] ?? ""; switch (field.type) { // String input. @@ -311,7 +312,7 @@ export default function DynamicInputs({ name={fieldName} setData={setData} date={fieldValue as Date} - hasTime={true} + hasTime label={getTrans(field.label)} /> ); @@ -323,47 +324,24 @@ export default function DynamicInputs({ setData={setData} value={String(fieldValue)} label={getTrans(field.label)} - required={extractRequiredValidation(field.validation)} + required={extractRequiredValidation( + field.validation, + )} /> ); // Model select. case enumDynamicFieldTypes.model.value: - // Extract only the model name from the validation. - const targetModel = extractTableFromExists(field.validation) || "dynamic_pages"; - - // Add a custom prefix in the last part of the name. - const newName = fieldName.replace(/([^.\s]+)$/, "reserved_$1"); - - // Set a state at false. - const initializedRef = useRef(false); - - // Set the model name in the custom key only once. - useEffect(() => { - if (initializedRef.current) return; - initializedRef.current = true; - - // If the value isn't already present in content. - if (content && !content[`reserved_${field.key}` as keyof typeof content]) { - setData(newName, targetModel); - } - }, [newName, targetModel]); - return ( - ); - // Contact Page Select + // Static route select. case enumDynamicFieldTypes.staticroute.value: return ( ); // Position select. @@ -384,7 +364,9 @@ export default function DynamicInputs({ selected={fieldValue as number} options={enumElementPosition} setData={setData} - required={extractRequiredValidation(field.validation)} + required={extractRequiredValidation( + field.validation, + )} /> ); default: diff --git a/resources/ts/back/Components/DynamicPages/DynamicList.tsx b/resources/ts/back/Components/DynamicPages/DynamicList.tsx index 3ea15d85..591d7f15 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicList.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicList.tsx @@ -1,12 +1,29 @@ // * Packages import { CSS } from "@dnd-kit/utilities"; -import { GripVerticalIcon, TrashIcon } from "lucide-react"; -import { closestCenter, DndContext, DragEndEvent, PointerSensor, useSensor, useSensors } from "@dnd-kit/core"; -import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; -import { useState } from "react"; +import { + closestCenter, + DndContext, + DragEndEvent, + PointerSensor, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import { + arrayMove, + SortableContext, + useSortable, + verticalListSortingStrategy, +} from "@dnd-kit/sortable"; import { usePage } from "@inertiajs/react"; +import { useState } from "react"; +import { GripVerticalIcon, TrashIcon } from "lucide-react"; // * Components shadcn -import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion"; import { Card, CardContent } from "@/components/ui/card"; import { Label } from "@/components/ui/label"; // * Other @@ -14,326 +31,372 @@ import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithT import AddNewFieldBtn from "@/back/Components/PageConfigs/AddNewFieldBtn"; import DynamicInputs from "@/back/Components/DynamicPages/DynamicInputs"; import useTrans from "@/hooks/use-translations"; -import { extractMinMaxFromValidation, extractRequiredValidation } from "@/hooks/use-laravel-validation"; -import { ConfigField, DynamicInternalField } from "@/back/types/global"; -import { cn } from "@/lib/utils"; - -type DynamicListProps = { - name: string, - parentName: string, - value: DynamicInternalField[], - enumLabel: string, - field: ConfigField, - content: DynamicInternalField | null; - isChildren: boolean; - setData: (name: string, value: string | boolean | File | object | null) => void; - reset: (name?: string) => void; -} - -// Allows to get recursive list inputs. -export default function DynamicList({ - name, - parentName, - value, - enumLabel, - field, - content, - isChildren, - setData, - reset, -}: DynamicListProps) { - // Notice user there must be children config. - if (!field.children && field.children!.length > 0) { - return ( -

- {useTrans('back.list_children_needed', { - params: { enumLabel } - })} -

- ); - } - - // Errors. - const { errors } = usePage().props; - const [localErrors, setLocalErrors] = useState>(errors) - - // Drag & drop module for user interactions (mouse, touch, keyboard or other). - const sensors = useSensors(useSensor(PointerSensor)); - - // Define a local identifier for each element to enable unique identification during drag and drop. - const localValue = value.map((elmt, index) => { - return { ...elmt, id: elmt.id ?? index + 1 }; - }); - - // Order all elements depending on order values. - const sortedListItems = [...localValue].sort((a, b) => a.order - b.order); - - // Extract some values from laravel rules validation. - const isRequired = extractRequiredValidation(field.validation); - const configLimitMax = extractMinMaxFromValidation(field.validation).max ?? 1; - - // Accordion open index. - const [openIndex, setOpenIndex] = useState(""); - - /** - * Get all elements without each unique identification values. - * @param fields DynamicInternalField[] - * @returns Omit[] - */ - const removeIds = (fields: DynamicInternalField[]): Omit[] => { - return fields.map(({ id, ...rest }) => { - const newObj: any = {}; - - for (const key in rest) { - const value = rest[key as keyof typeof rest]; - // If it is an array, we treat it recursively. - if (Array.isArray(value)) { - newObj[key] = removeIds(value); - } - // Otherwise, we keep the value as it is. - else { - newObj[key] = value; - } - } - return newObj; - }); - }; - - /** - * Remove a specific element from the list. - * @param parentName string - * @param fieldKey string - * @param index number - * @return void - */ - const handleRemoveField = (parentName: string, fieldKey: string, index: number) => { - // Get the current list of elements. - const list = Array.isArray(content?.[fieldKey as keyof typeof content]) - // @ts-ignore - ? [...content[fieldKey as keyof typeof content]] - : []; - // Remove the targeted element. - list.splice(index, 1); - // Save the new list updated. - setData(`${parentName}.${fieldKey}`, list); - // Reset all errors because of alter elements list. - setLocalErrors({}); - } - - /** - * Reorder the elements list. - * @param event DragEndEvent - * @return void - */ - const handleOnDragEnd = (event: DragEndEvent) => { - const { active, over } = event; - - // Check the unique identification value. - if (!over || active.id === over.id) return; - - // Get the two elements that are switchable by drag and drop. - const oldIndex = sortedListItems.findIndex((i) => i.id === active.id); - const newIndex = sortedListItems.findIndex((i) => i.id === over.id); - - // Reorder all elements list to update visually all elements. - const reorderedList = arrayMove(sortedListItems, oldIndex, newIndex) - .map((item, index) => ({ - ...item, - order: index + 1, - })); - - // Save the new ordered list elements. - setData(`${parentName}.${field.key}`, reorderedList); - } - - /** - * Add a new field to the list. - * @return void - */ - const handleAddNewField = () => { - // Set new element with unique identification and order. - const newItem = Object.fromEntries( - (field.children ?? []).map(child => [child.key, ""]) - ); - const maxOrder = Math.max(0, ...sortedListItems.map((field) => field.order ?? 0)) + 1; - const maxIndex = Math.max(0, ...sortedListItems.map((field) => field.id ?? 0)) + 1; - const newIndex = value.length; - const newItemWithOrder = { ...newItem, id: maxIndex, order: maxOrder }; - - // Save the list with the new element. - setData(`${parentName}.${field.key}.${newIndex}`, newItemWithOrder); - } - - return ( -
- - {value.length > 0 && ( - - {/* - The main provider for dnd-kit. - It manages the entire drag-and-drop system: sensors, movement, collision detection, and lifecycle callbacks (onDragStart, onDragEnd, etc.). - */} - - {/* - Defines a reorderable list area. - It registers sortable items and applies the chosen sorting strategy (vertical, horizontal, grid) to handle item repositioning. - */} - item.id)} - strategy={verticalListSortingStrategy} - > - {/* Use the recursive component for each elements. */} - {sortedListItems.map((item, itemIndex) => ( - - ))} - - - - )} - -
- ) -} +import { + extractMinMaxFromValidation, + extractRequiredValidation, +} from "@/hooks/use-laravel-validation"; +import { ConfigField, DynamicInternalField } from "@/back/types/dynamic-pages"; +import { cn, GetTranslation } from "@/lib/utils"; +/* eslint-disable no-unused-vars */ type SortableItemProps = { - id: number; - item: any; - itemIndex: number; - name: string; - parentName: string; - field: any; - setData: (name: string, value: string | boolean | File | object | null) => void; - reset: (name?: string) => void; - removeField: (parentName: string, fieldKey: string, index: number) => void; - parentAccordionState: string; - setParentAccordionState: (key: string) => void; - localErrors: Record; -} + id: number; + item: DynamicInternalField | null; + itemIndex: number; + name: string; + parentName: string; + field: ConfigField; + setData: ( + name: string, + value: string | boolean | File | object | null, + ) => void; + reset: (name?: string) => void; + removeField: (parentName: string, fieldKey: string, index: number) => void; + parentAccordionState: string; + setParentAccordionState: (key: string) => void; + localErrors: Record; +}; +/* eslint-enable no-unused-vars */ // Recursive component. function SortableItem({ - id, - item, - itemIndex, - name, - parentName, - field, - setData, - reset, - removeField, - parentAccordionState, - setParentAccordionState, - localErrors, + id, + item, + itemIndex, + name, + parentName, + field, + setData, + reset, + removeField, + parentAccordionState, + setParentAccordionState, + localErrors, }: SortableItemProps) { - // Provides the necessary props and helpers to make this item draggable and reorderable. - // Includes event listeners, accessibility attributes, DOM ref, drag transform/transition values, - // and a flag indicating whether the item is dragging. - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id }); + // Provides the necessary props and helpers to make this item draggable and reorderable. + // Includes event listeners, accessibility attributes, DOM ref, drag transform/transition values, + // and a flag indicating whether the item is dragging. + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); - // Style applied to the sortable item: - // - handles drag movement (transform), - // - animations (transition), - // - and visual feedback (opacity, zIndex) while dragging. - const style = { - transform: CSS.Transform.toString(transform), - transition, - opacity: isDragging ? 0.5 : 1, - zIndex: isDragging ? 50 : 0, - }; + // Style applied to the sortable item: + // - handles drag movement (transform), + // - animations (transition), + // - and visual feedback (opacity, zIndex) while dragging. + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + zIndex: isDragging ? 50 : 0, + }; - // Translations. - const transDragAndDrop = useTrans("back.dnd_field"); - const transDelete = useTrans("back.delete_field"); - - return ( -
- - key.startsWith(`${name}.${itemIndex}`)), - })}> - -
-
- {/* Define a drag-and-drop button to swap the order between the current element and another one. */} -
- } - tooltipContent={transDragAndDrop} - className="cursor-grab h-full w-full" - type="button" - variant="outline" - size="icon" - disabled={parentAccordionState !== ""} - {...listeners} - {...attributes} - /> -
- {/* Define a delete button to destroy the current element. */} - } - tooltipContent={transDelete} - type="button" - variant="destructive" - size="icon" - onClick={() => { - if (parentAccordionState === `item-${itemIndex}`) { - setParentAccordionState("") - } - removeField(parentName, field.key, itemIndex) - }} - /> -
- {/* Define the trigger button to open or close the current accordion. */} -
- - Élément n°{itemIndex + 1} - -
-
- - {/* Get specific input from the config value. */} - - -
-
-
-
- ); -} \ No newline at end of file + // Translations. + const transDragAndDrop = useTrans("back.dnd_field"); + const transDelete = useTrans("back.delete_field"); + + return ( +
+ + + key.startsWith(`${name}.${itemIndex}`), + ), + })} + > + +
+
+ {/* Define a drag-and-drop button to swap the order between the current element and another one. */} +
+ + } + tooltipContent={transDragAndDrop} + className="cursor-grab h-full w-full" + type="button" + variant="outline" + size="icon" + disabled={parentAccordionState !== ""} + /* eslint-disable react/jsx-props-no-spreading */ + {...listeners} + {...attributes} + /* eslint-enable react/jsx-props-no-spreading */ + /> +
+ {/* Define a delete button to destroy the current element. */} + } + tooltipContent={transDelete} + type="button" + variant="destructive" + size="icon" + onClick={() => { + if ( + parentAccordionState === + `item-${itemIndex}` + ) { + setParentAccordionState(""); + } + removeField( + parentName, + field.key, + itemIndex, + ); + }} + /> +
+ {/* Define the trigger button to open or close the current accordion. */} +
+ + Élément n°{itemIndex + 1} + +
+
+ + {/* Get specific input from the config value. */} + {field.children?.length && ( + + )} + +
+
+
+
+ ); +} + +/* eslint-disable no-unused-vars */ +type DynamicListProps = { + name: string; + parentName: string; + value: DynamicInternalField[]; + enumLabel: string; + field: ConfigField; + content: DynamicInternalField | null; + isChildren: boolean; + setData: ( + name: string, + value: string | boolean | File | object | null, + ) => void; + reset: (name?: string) => void; +}; +/* eslint-enable no-unused-vars */ + +// Allows to get recursive list inputs. +export default function DynamicList({ + name, + parentName, + value, + enumLabel, + field, + content, + isChildren, + setData, + reset, +}: DynamicListProps) { + // Errors. + const { errors } = usePage().props; + const [localErrors, setLocalErrors] = + useState>(errors); + + // Drag & drop module for user interactions (mouse, touch, keyboard or other). + const sensors = useSensors(useSensor(PointerSensor)); + + // Define a local identifier for each element to enable unique identification during drag and drop. + const localValue = value.map((elmt, index) => { + return { ...elmt, id: elmt.id ?? index + 1 }; + }); + + // Order all elements depending on order values. + const sortedListItems = [...localValue].sort((a, b) => a.order - b.order); + + // Extract some values from laravel rules validation. + const isRequired = extractRequiredValidation(field.validation); + const configLimitMax = + extractMinMaxFromValidation(field.validation).max ?? 1; + + // Accordion open index. + const [openIndex, setOpenIndex] = useState(""); + + // Notice user there must be children config. + if (!field.children && field.children!.length > 0) { + return ( +

+ {GetTranslation("back.list_children_needed", { + params: { enumLabel }, + })} +

+ ); + } + + /** + * Remove a specific element from the list. + * @param currentParentName string + * @param fieldKey string + * @param index number + * @return void + */ + const handleRemoveField = ( + currentParentName: string, + fieldKey: string, + index: number, + ) => { + // Get the current list of elements. + const list = Array.isArray(content?.[fieldKey as keyof typeof content]) + ? // @ts-expect-error Weird error type. + [...content[fieldKey as keyof typeof content]] + : []; + // Remove the targeted element. + list.splice(index, 1); + // Save the new list updated. + setData(`${currentParentName}.${fieldKey}`, list); + // Reset all errors because of alter elements list. + setLocalErrors({}); + }; + + /** + * Reorder the elements list. + * @param event DragEndEvent + * @return void + */ + const handleOnDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + + // Check the unique identification value. + if (!over || active.id === over.id) return; + + // Get the two elements that are switchable by drag and drop. + const oldIndex = sortedListItems.findIndex((i) => i.id === active.id); + const newIndex = sortedListItems.findIndex((i) => i.id === over.id); + + // Reorder all elements list to update visually all elements. + const reorderedList = arrayMove( + sortedListItems, + oldIndex, + newIndex, + ).map((item, index) => ({ + ...item, + order: index + 1, + })); + + // Save the new ordered list elements. + setData(`${parentName}.${field.key}`, reorderedList); + }; + + /** + * Add a new field to the list. + * @return void + */ + const handleAddNewField = () => { + // Set new element with unique identification and order. + const newItem = Object.fromEntries( + (field.children ?? []).map((child) => [child.key, ""]), + ); + const maxOrder = + Math.max( + 0, + ...sortedListItems.map( + (currentField) => currentField.order ?? 0, + ), + ) + 1; + const maxIndex = + Math.max( + 0, + ...sortedListItems.map((currentField) => currentField.id ?? 0), + ) + 1; + const newIndex = value.length; + const newItemWithOrder = { ...newItem, id: maxIndex, order: maxOrder }; + + // Save the list with the new element. + setData(`${parentName}.${field.key}.${newIndex}`, newItemWithOrder); + }; + + return ( +
+ + {value.length > 0 && ( + + {/* + The main provider for dnd-kit. + It manages the entire drag-and-drop system: sensors, movement, collision detection, and lifecycle callbacks (onDragStart, onDragEnd, etc.). + */} + + {/* + Defines a reorderable list area. + It registers sortable items and applies the chosen sorting strategy (vertical, horizontal, grid) to handle item repositioning. + */} + item.id)} + strategy={verticalListSortingStrategy} + > + {/* Use the recursive component for each elements. */} + {sortedListItems.map((item, itemIndex) => ( + + handleRemoveField( + currentParentName, + fieldKey, + index, + ) + } + parentAccordionState={openIndex} + setParentAccordionState={setOpenIndex} + localErrors={localErrors} + /> + ))} + + + + )} + +
+ ); +} diff --git a/resources/ts/back/Components/DynamicPages/DynamicPageDetails.tsx b/resources/ts/back/Components/DynamicPages/DynamicPageDetails.tsx index d665266d..86f3ad89 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicPageDetails.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicPageDetails.tsx @@ -10,83 +10,141 @@ import { // * Other import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { ConfigField } from "@/back/types/global"; -import { cn } from "@/lib/utils"; +import { ConfigField } from "@/back/types/dynamic-pages"; +import { cn, GetTranslation } from "@/lib/utils"; + +type ChildItem = Record; + +const RenderRows = ( + currentValue: string | number | object, + currentConfig: ConfigField[], + hasBorders: boolean = false, + path: string = "", +): ReactNode => { + const tableNotKnownTrans = str(useTrans("back.table_not_known")) + .ucFirst() + .value(); + + return currentConfig.map((field, index) => { + const hasChildren = !!field.children?.length; + const accordionKey = path + ? `${path}.${field.key}-${index}` + : `${field.key}-${index}`; + + const rowContent = (currentHasChildren: boolean = false) => { + const cellClasses = "break-words whitespace-normal"; + const placeholderClasses = + "text-sm text-muted-foreground break-words whitespace-normal"; + const fieldValue = + currentValue[field.key as keyof typeof currentValue]; + + let cellContent: ReactNode; + if (currentHasChildren) { + const count = Array.isArray(fieldValue) + ? Object.values(fieldValue).length + : 0; + cellContent = ( +

+ {GetTranslation("back.element", { + params: { count: String(count) }, + choice: count > 1 ? 2 : 1, + })} +

+ ); + } else if (fieldValue !== null && fieldValue !== undefined) { + cellContent = ( +

+ {typeof fieldValue === "boolean" + ? GetTranslation( + fieldValue ? "back.yes" : "back.no", + ) + : fieldValue} +

+ ); + } else { + cellContent = ( +

{tableNotKnownTrans}

+ ); + } + + return ( +
+

{field.label}

+ {cellContent} + {!currentHasChildren &&
} +
+ ); + }; + + return ( + + {hasChildren ? ( + + {rowContent(hasChildren)} + + ) : ( +
{rowContent()}
+ )} + + {hasChildren && + Array.isArray( + currentValue[field.key as keyof typeof currentValue], + ) && + Object.values( + currentValue[field.key as keyof typeof currentValue], + ).length > 0 && ( + +
+ {Object.values( + currentValue[ + field.key as keyof typeof currentValue + ] as ChildItem[], + ).map((childItem: ChildItem) => ( +
+ {RenderRows( + childItem, + field.children!, + false, + `${accordionKey}-${childItem.id}`, + )} +
+ ))} +
+
+ )} +
+ ); + }); +}; type DynamicPageDetailsProps = { value: string | object; config: ConfigField[]; }; -export default function DynamicPageDetails({ value, config }: DynamicPageDetailsProps) { - const transLabel = str(useTrans("validation.custom.label")).ucFirst().value(); - const transValue = str(useTrans("validation.custom.value")).ucFirst().value(); - const tableNotKnownTrans = str(useTrans("back.table_not_known")).ucFirst().value(); - - const RenderRows = (value: string | number | object, config: ConfigField[], hasBorders: boolean = false, path: string = ""): ReactNode => - config.map((field, index) => { - const hasChildren = !!field.children?.length; - const accordionKey = path ? `${path}.${field.key}-${index}` : `${field.key}-${index}`; - - const rowContent = (hasChildren: boolean = false) => { - const cellClasses = "break-words whitespace-normal"; - const placeholderClasses = "text-sm text-muted-foreground break-words whitespace-normal"; - - const fieldValue = value[field.key as keyof typeof value]; - - const cellContent = hasChildren - ? (() => { - const count = Array.isArray(fieldValue) - ? Object.values(fieldValue).length - : 0; - return ( -

- {useTrans('back.element', { - params: { count: String(count) }, - choice: count > 1 ? 2 : 1, - })} -

- ); - })() - : fieldValue !== null && fieldValue !== undefined - ?

- {(typeof fieldValue === 'boolean') ? useTrans(fieldValue ? 'back.yes' : 'back.no') : fieldValue} -

- :

{tableNotKnownTrans}

; - - return ( -
-

{field.label}

- {cellContent} - {!hasChildren &&
} -
- ); - }; - - return ( - - {hasChildren ? ( - - {rowContent(hasChildren)} - - ) : ( -
{rowContent()}
- )} - - {hasChildren && Array.isArray(value[field.key as keyof typeof value]) && Object.values(value[field.key as keyof typeof value]).length > 0 && ( - -
- {Object.values(value[field.key as keyof typeof value]).map((childItem: any, childIndex: number) => ( -
- {RenderRows(childItem, field.children!, false, `${accordionKey}-${childIndex}`)} -
- ))} -
-
- )} -
- ); - }); +export default function DynamicPageDetails({ + value, + config, +}: DynamicPageDetailsProps) { + const transLabel = str(useTrans("validation.custom.label")) + .ucFirst() + .value(); + const transValue = str(useTrans("validation.custom.value")) + .ucFirst() + .value(); return ( @@ -94,7 +152,7 @@ export default function DynamicPageDetails({ value, config }: DynamicPageDetails
{transLabel}
{transValue}
-
+
{/* ROWS */} diff --git a/resources/ts/back/Components/DynamicPages/DynamicStatusBadge.tsx b/resources/ts/back/Components/DynamicPages/DynamicStatusBadge.tsx index 58dc290d..39c887fd 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicStatusBadge.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicStatusBadge.tsx @@ -12,7 +12,7 @@ type DynamicStatusBadgeProps = { // Get a stylised badge for a specific enum value. export default function DynamicStatusBadge({ value }: DynamicStatusBadgeProps) { - // Get all enum values, labels and names. + // Get all enum values, labels and names. const { enumDynamicPageStatus } = usePage().props as unknown as { enumDynamicPageStatus: LaravelEnum; }; @@ -39,9 +39,8 @@ export default function DynamicStatusBadge({ value }: DynamicStatusBadgeProps) { ); // Get the color and icon for the current enum value. - const { color, Icon } = statusStyles[ - enumValue?.value as keyof typeof statusStyles - ]; + const { color, Icon } = + statusStyles[enumValue?.value as keyof typeof statusStyles]; return ( diff --git a/resources/ts/back/Components/DynamicPages/DynamicWrapperModelSelect.tsx b/resources/ts/back/Components/DynamicPages/DynamicWrapperModelSelect.tsx new file mode 100644 index 00000000..79a86eec --- /dev/null +++ b/resources/ts/back/Components/DynamicPages/DynamicWrapperModelSelect.tsx @@ -0,0 +1,74 @@ +// * Packages +import { useEffect, useRef } from "react"; +// * Other +import { ModelSelect } from "@/back/Components/Inputs/ModelSelect"; +import { + extractExcludedIdFromExists, + extractRequiredValidation, + extractTableFromExists, +} from "@/hooks/use-laravel-validation"; +import { ConfigField, DynamicInternalField } from "@/back/types/dynamic-pages"; + +/* eslint-disable no-unused-vars */ +type DynamicWrapperModelSelectProps = { + field: ConfigField; + fieldName: string; + fieldValue: string | number | boolean | File | Date; + content: DynamicInternalField | null; + setData: ( + name: string, + value: string | number | boolean | File | object | null, + ) => void; + getTrans: (fieldLabel: string) => string; +}; +/* eslint-enable no-unused-vars */ + +export default function DynamicWrapperModelSelect({ + field, + fieldName, + fieldValue, + content, + setData, + getTrans, +}: DynamicWrapperModelSelectProps) { + // Extract only the model name from the validation. + const targetModel = + extractTableFromExists(field.validation) || "dynamic_pages"; + + // Add a custom prefix in the last part of the name. + const newName = fieldName.replace(/([^.\s]+)$/, "reserved_$1"); + + // Set a state at false. + const initializedRef = useRef(false); + + // Set the model name in the custom key only once. + useEffect(() => { + if (initializedRef.current) return; + initializedRef.current = true; + + // If the value isn't already present in content. + if ( + content && + !content[`reserved_${field.key}` as keyof typeof content] + ) { + setData(newName, targetModel); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [newName, targetModel]); + + return ( + + ); +} diff --git a/resources/ts/back/Components/FieldsetWrapper.tsx b/resources/ts/back/Components/FieldsetWrapper.tsx index 33f58f29..0658e446 100644 --- a/resources/ts/back/Components/FieldsetWrapper.tsx +++ b/resources/ts/back/Components/FieldsetWrapper.tsx @@ -29,7 +29,8 @@ export default function FieldsetWrapper({ return ( @@ -41,7 +42,9 @@ export default function FieldsetWrapper({ diff --git a/resources/ts/back/Components/Filters/EnumFilter.tsx b/resources/ts/back/Components/Filters/EnumFilter.tsx index c7c56715..1a0d8efa 100644 --- a/resources/ts/back/Components/Filters/EnumFilter.tsx +++ b/resources/ts/back/Components/Filters/EnumFilter.tsx @@ -3,7 +3,7 @@ import { route } from "ziggy-js"; // * Other import EnumSelect from "@/back/Components/Inputs/EnumSelect"; import { LaravelEnum } from "@/back/types/global"; -import { addFilterToUrl } from "@/lib/filters"; +import addFilterToUrl from "@/lib/filters"; type Props = { enums: LaravelEnum; @@ -11,13 +11,13 @@ type Props = { modelName: string; label: string; placeholder: string; -} +}; -const EnumFilter = (props: Props) => { +function EnumFilter(props: Props) { const { enums, fieldName, modelName, label, placeholder } = props; const selectedEnumParam = Object.values(enums).find( - status => status.name === route().params.status + (status) => status.name === route().params.status, ); return ( { selected={selectedEnumParam?.value ?? undefined} setData={(name, value) => { const selectedStatusName = Object.values(enums).find( - enumValue => enumValue.value === value + (enumValue) => enumValue.value === value, )?.name; const params = { ...route().params, [name]: selectedStatusName, }; - addFilterToUrl({modelName, params}); + addFilterToUrl({ modelName, params }); }} /> - ) + ); } export default EnumFilter; diff --git a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx index 670c3675..9e8a2466 100644 --- a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx +++ b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx @@ -1,12 +1,8 @@ // * Packages -import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; // * Other -import { MultiSelect } from "@/back/Components/Inputs/MultiSelect"; -import { mapPivotOptions } from "@/lib/mapPivotOptions"; -import { AppEnv, Model } from "@/back/types/global"; -import { addFilterToUrl } from "@/lib/filters"; -import { ModelSelect } from "../Inputs/ModelSelect"; +import { ModelSelect } from "@/back/Components/Inputs/ModelSelect"; +import addFilterToUrl from "@/lib/filters"; type Props = { fieldName: string; @@ -15,21 +11,20 @@ type Props = { placeholder: string; /** Model target to display options */ targetModel?: string; -} +}; -const MultiSelectRelationFilter = (props: Props) => { - const { targetModel, fieldName, label, placeholder, modelName} = props; +function MultiSelectRelationFilter(props: Props) { + const { targetModel, fieldName, label, placeholder, modelName } = props; const valuesFromUrl: string[] = typeof route().params[fieldName] === "string" ? route().params[fieldName].split(",") : []; - return ( { const valuesArray = Array.isArray(value) ? value : [value]; const params = { ...route().params, - [name]: valuesArray.length ? valuesArray.join(",") : undefined, + [name]: valuesArray.length + ? valuesArray.join(",") + : undefined, }; addFilterToUrl({ modelName, params }); }} @@ -54,10 +51,10 @@ const MultiSelectRelationFilter = (props: Props) => { }, desktop: { maxCount: 5, - } + }, }} /> - ) + ); } export default MultiSelectRelationFilter; diff --git a/resources/ts/back/Components/Filters/SwitchFilter.tsx b/resources/ts/back/Components/Filters/SwitchFilter.tsx index 7794155a..92021eef 100644 --- a/resources/ts/back/Components/Filters/SwitchFilter.tsx +++ b/resources/ts/back/Components/Filters/SwitchFilter.tsx @@ -2,15 +2,15 @@ import { route } from "ziggy-js"; // * Other import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch"; -import { addFilterToUrl } from "@/lib/filters"; +import addFilterToUrl from "@/lib/filters"; type Props = { fieldName: string; modelName: string; label: string; -} +}; -const SwitchFilter = (props: Props) => { +function SwitchFilter(props: Props) { const { label, fieldName, modelName } = props; return ( { addFilterToUrl({ modelName, params }); }} /> - ) + ); } export default SwitchFilter; diff --git a/resources/ts/back/Components/FiltersWrapper.tsx b/resources/ts/back/Components/FiltersWrapper.tsx index 62e75cac..67fc95af 100644 --- a/resources/ts/back/Components/FiltersWrapper.tsx +++ b/resources/ts/back/Components/FiltersWrapper.tsx @@ -15,7 +15,7 @@ import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithT import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -const FiltersWrapper = ({ children }: { children: ReactNode }) => { +function FiltersWrapper({ children }: { children: ReactNode }) { return (
@@ -57,6 +57,6 @@ const FiltersWrapper = ({ children }: { children: ReactNode }) => {
); -}; +} export default FiltersWrapper; diff --git a/resources/ts/back/Components/GoToFrontView.tsx b/resources/ts/back/Components/GoToFrontView.tsx index de256205..be0c1605 100644 --- a/resources/ts/back/Components/GoToFrontView.tsx +++ b/resources/ts/back/Components/GoToFrontView.tsx @@ -2,31 +2,35 @@ import { usePage } from "@inertiajs/react"; import { ExternalLinkIcon } from "lucide-react"; // * Components shadcn -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; // * Other import { AppEnv } from "@/back/types/global"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import { cn } from "@/lib/utils"; +import { cn, GetTranslation } from "@/lib/utils"; interface GoToFrontViewProps { /** Model Name used to translate the helper */ modelName: string; - /** Field data to build path */ + /** Field data to build path */ pathField: string; /** Additionnal segment used in the url */ - additionalGroupPath?: string|null; + additionalGroupPath?: string | null; /** Does the actual page status available in front */ isAvailable?: boolean; /** Set visually in column */ - isColumn?: boolean, + isColumn?: boolean; /** Add locale to the url */ - addLocale?: boolean, + addLocale?: boolean; } export default function GoToFrontView({ @@ -47,8 +51,13 @@ export default function GoToFrontView({ const cleanUrl = url.endsWith("/") ? url.slice(0, -1) : url; + let localePath = ""; + if (addLocale && locale !== "fr") { + localePath = `/${locale}`; + } + const definitivePath = [ - cleanUrl + (addLocale ? (locale === "fr" ? '' : '/' + locale) : ''), + cleanUrl + localePath, additionalGroupPath, pathField, ] @@ -56,21 +65,27 @@ export default function GoToFrontView({ .join("/"); return ( - + {isAvailable ? ( <> - {str(useTrans('back.access_to_front_page', { - params: { - model: modelName, - }, - })).ucFirst().value()} + {str( + GetTranslation("back.access_to_front_page", { + params: { + model: modelName, + }, + }), + ) + .ucFirst() + .value()} - - {anchorAccessPage} - + {anchorAccessPage} ) : ( <> - {str(useTrans("back.access_to_front_page_when_published", { - params: { - model: modelName, - }, - })).ucFirst().value()}: - - {definitivePath} - + {str( + GetTranslation( + "back.access_to_front_page_when_published", + { + params: { + model: modelName, + }, + }, + ), + ) + .ucFirst() + .value()} + :{definitivePath} )} - ) + ); } diff --git a/resources/ts/back/Components/InputError.tsx b/resources/ts/back/Components/InputError.tsx index b086961b..d32233d6 100644 --- a/resources/ts/back/Components/InputError.tsx +++ b/resources/ts/back/Components/InputError.tsx @@ -31,8 +31,8 @@ export default function InputError({ {all && {errorsTrans}} - {messages.map((errorMessage, errorMessageIndex) => { - return

{errorMessage}

; + {messages.map((errorMessage) => { + return

{errorMessage}

; })}
diff --git a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx index a49fc0a4..c9d1bd52 100644 --- a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx +++ b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx @@ -14,8 +14,10 @@ import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithT 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 { AppEnv } from "@/back/types/global"; +import { DynamicFieldTypes } from "@/back/types/dynamic-pages"; +import { FileValidation } from "@/back/types/others"; +import { cn, GetTranslation } from "@/lib/utils"; type FileWithPreview = FileWithPath & { preview: string; @@ -28,12 +30,12 @@ type CompleteInputFileProps = FileValidation & { /** Original data is the data directly from the model, not in the form state */ originalData?: string | undefined; /** Add custom event when refresh to the originalData */ - onRefreshFile?: () => void + onRefreshFile?: () => void; label?: string; required?: boolean; fileName?: string; hasRefreshBtn?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; setData: (name: string, value: File | string | null) => void; reset: (name?: string) => void; hasFile?: (hasFile: boolean) => void; @@ -41,7 +43,8 @@ type CompleteInputFileProps = FileValidation & { /* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */ export default function CompleteInputFile(props: CompleteInputFileProps) { - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; const { value, setData, @@ -57,19 +60,35 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { inputType = enumDynamicFieldTypes.image.value, fileName = "image", hasRefreshBtn = true, - hasFile + hasFile, + parentErrors, } = props; const { toast } = useToast(); const { errors } = usePage().props; const { url } = usePage().props.appEnv as AppEnv; const [isReset, setIsReset] = useState(false); + const [isDialogOpen, setDialogOpen] = useState(false); + const [accept, setAccept] = useState>>({ + "image/*": [], + }); + const [extensions, setExtensions] = useState(); + const finalFileName = `${fileName}.png`; - const transValueIntoFile = (localData: string | undefined | null) => { - if (localData) { - const fileName = getFileNameFromPath(localData); - return { preview: `${url}/${localData}`, name: fileName ?? '' } as FileWithPreview; - } return null; - } + const isRefreshDisabled = value != null && typeof value === "string"; + const localErrors = parentErrors ?? errors; + + 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; /** * Get the fileName from the path given by the database value @@ -84,8 +103,16 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { return last || null; }; - - const isRefreshDisabled = value != null && typeof value === 'string'; + const transValueIntoFile = (localData: string | undefined | null) => { + if (localData) { + const currentFileName = getFileNameFromPath(localData); + return { + preview: `${url}/${localData}`, + name: currentFileName ?? "", + } as FileWithPreview; + } + return null; + }; const [selectedFile, setSelectedFile] = useState( () => { @@ -97,42 +124,10 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { } // When there is already an image stored. - return transValueIntoFile(value) - } + return transValueIntoFile(value); + }, ); - const localErrors = props.parentErrors ?? errors; - - 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"; @@ -144,6 +139,38 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { return `${currentBytes} ${currentSize}`; }; + // Translations + const transSelectImgZone = useTrans("back.image_cropper.select_img_zone"); + const transValidationAllFormats = str( + useTrans("back.image_cropper.validation.all_formats"), + ) + .ucFirst() + .value(); + const transCropperFileUploaded = useTrans( + "back.image_cropper.state_file_uploaded", + ); + const transCancel = useTrans("back.cancel"); + const transRulesWeight = useTrans( + "back.image_cropper.validation.rules_weight", + { + params: { + size: formatFileSize(localMaxFileSize).toString(), + }, + }, + ); + const transRefresh = useTrans("back.refresh_original"); + const getTransValidationAllowedFormats = (targetExtensions: string) => { + return str( + GetTranslation("back.image_cropper.validation.allowed_formats", { + params: { + formats: targetExtensions, + }, + }), + ) + .ucFirst() + .value(); + }; + const buildDropzoneAccept = (): Record => { if (!allowedFormats) return {}; @@ -187,23 +214,33 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { }, []); useEffect(() => { - hasFile?.(selectedFile ? true : false); + hasFile?.(!!selectedFile); }, [selectedFile, hasFile]); // 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(), + 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(), + ) + .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( @@ -266,10 +303,13 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
- + {selectedFile ? (
- {inputType === enumDynamicFieldTypes.image.value && ( + {inputType === + enumDynamicFieldTypes.image.value && (

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

- - {selectedFile.name} - + {selectedFile.name}
)} @@ -313,17 +353,18 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { setSelectedFile(null); setData(name, null); }} - tooltipContent={str(useTrans("back.cancel")).ucFirst().value()} + tooltipContent={str(transCancel) + .ucFirst() + .value()} />
- ) : ( @@ -356,18 +393,16 @@ export default function CompleteInputFile(props: CompleteInputFileProps) { { - setData(name, originalData) - setSelectedFile(transValueIntoFile(originalData)) + setData(name, originalData); + setSelectedFile(transValueIntoFile(originalData)); if (onRefreshFile) { - onRefreshFile() + onRefreshFile(); } }} - content={ - - } - tooltipContent={str(useTrans("back.refresh_original")).ucFirst().value()} + content={} + tooltipContent={str(transRefresh).ucFirst().value()} /> )}
diff --git a/resources/ts/back/Components/Inputs/EnumSelect.tsx b/resources/ts/back/Components/Inputs/EnumSelect.tsx index 5d9668da..c51f98b9 100644 --- a/resources/ts/back/Components/Inputs/EnumSelect.tsx +++ b/resources/ts/back/Components/Inputs/EnumSelect.tsx @@ -4,11 +4,15 @@ import { useEffect, useState } from "react"; import { CheckIcon, ChevronsUpDownIcon, SearchIcon, XIcon } from "lucide-react"; // * Components shadcn import { Label } from "@/components/ui/label"; -import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; // * Other -import BtnOptionnalLinkWithTooltip from "@/back/Components//BtnOptionnalLinkWithTooltip"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import InputError from "@/back/Components/InputError"; import { AppEnv } from "@/back/types/global"; import { cn } from "@/lib/utils"; @@ -16,196 +20,231 @@ import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; type EnumSelectProps = { - name: string; - label: string; - options?: Record; - placeholder?: string; - exclude?: number[]; - selected?: number|null; - required?: boolean; - disabled?: boolean; - parentErrors?: Record | null, - setData: (name: string, value: number | null) => void; - onSelectValue?: (value: number | null) => void; + name: string; + label: string; + options?: Record; + placeholder?: string; + exclude?: number[]; + selected?: number | null; + required?: boolean; + disabled?: boolean; + parentErrors?: Record | null; + // eslint-disable-next-line no-unused-vars + setData: (name: string, value: number | null) => void; + // eslint-disable-next-line no-unused-vars + onSelectValue?: (value: number | null) => void; }; export default function EnumSelect({ - name, - label, - options = {}, - placeholder = "ex: Magnifique libellé", - exclude = [], - selected = null, - required = true, - disabled = false, - parentErrors = null, - setData, - onSelectValue, + name, + label, + options = {}, + placeholder = "ex: Magnifique libellé", + exclude = [], + selected = null, + required = true, + disabled = false, + parentErrors = null, + setData, + onSelectValue, }: EnumSelectProps) { - const { locale } = usePage().props.appEnv as AppEnv; - const { errors } = usePage().props; - const localErrors = parentErrors ?? errors; + const { locale } = usePage().props.appEnv as AppEnv; + const { errors } = usePage().props; + const localErrors = parentErrors ?? errors; - // List of options. - const initalOptions = Object.fromEntries( - Object.entries(options).filter(([key, item]) => - !exclude.includes(item.value) - ) - ) - const [currentOptions, setCurrentOptions] = useState>(initalOptions); - - // Model key selected. - const initial = selected === 0 || selected === null || selected === undefined ? null : Number(selected); - const [selectedEnum, setSelectedEnum] = useState(initial); - - // String research in models collection. - const [search, setSearch] = useState(""); - - // Component states. - const [open, setOpen] = useState(false); - - /** - * Get the identification field of specific option. - * @param option Model - * @return string - */ - const getEnumLabel = (value: number): string => { - const targetEnum = Object.values(initalOptions).find(option => option.value === value); - if (!targetEnum) return String(value); - if (typeof value === "object") return String(targetEnum.label[locale as keyof typeof targetEnum.label] ?? ""); - return targetEnum.label; - }; - - /** - * Updates when selecting new value. - * @param value number - * @return void - */ - const handleSelect = (value: number) => { - setSelectedEnum(value); - setData(name, value); - onSelectValue?.(value); - setOpen(false); - }; - - /** - * Updates when clear the selected value. - * @return void - */ - const handleClear = () => { - setSelectedEnum(null); - setData(name, null); - onSelectValue?.(null); - }; - - /** - * Reset the search. - * @return void - */ - const handleClearSearch = () => { - setSearch(""); - }; - - // Fetch with debounce. - useEffect(() => { - // Reset options list if empty search or null - if (search.length === 0) { - setCurrentOptions(initalOptions); - return; - } - - const optionsFiltered = Object.fromEntries( - Object.entries(initalOptions).filter(([key, item]) => - item.label.toLowerCase().includes(search) - ) + // List of options. + const initalOptions = Object.fromEntries( + Object.entries(options).filter( + ([, item]) => !exclude.includes(item.value), + ), ); + const [currentOptions, setCurrentOptions] = + useState< + Record + >(initalOptions); - // Get updated options list with search. - setCurrentOptions(optionsFiltered); - }, [search, options]); + // Model key selected. + const initial = + selected === 0 || selected === null || selected === undefined + ? null + : Number(selected); + const [selectedEnum, setSelectedEnum] = useState(initial); - return ( -
- -
- - - - - -
-
- -
- setSearch(e.target.value)} - className="w-[calc(100%-2.5rem-40px)] border-0 mx-9" - /> - } - tooltipContent={

{str(useTrans("crud.actions.delete")).ucFirst().value()}

} - type="button" - variant="ghost" - size="icon" - className="absolute top-1/2 right-0 transform -translate-y-1/2 text-muted-foreground" - onClick={handleClearSearch} - disabled={search.length < 1 || disabled} - /> + // String research in models collection. + const [search, setSearch] = useState(""); + + // Component states. + const [open, setOpen] = useState(false); + + const transNoResults = useTrans("back.table_no_results"); + const transDelete = useTrans("crud.actions.delete"); + + /** + * Get the identification field of specific option. + * @param option Model + * @return string + */ + const getEnumLabel = (value: number): string => { + const targetEnum = Object.values(initalOptions).find( + (option) => option.value === value, + ); + if (!targetEnum) return String(value); + if (typeof value === "object") + return String( + targetEnum.label[locale as keyof typeof targetEnum.label] ?? "", + ); + return targetEnum.label; + }; + + /** + * Updates when selecting new value. + * @param value number + * @return void + */ + const handleSelect = (value: number) => { + setSelectedEnum(value); + setData(name, value); + onSelectValue?.(value); + setOpen(false); + }; + + /** + * Updates when clear the selected value. + * @return void + */ + const handleClear = () => { + setSelectedEnum(null); + setData(name, null); + onSelectValue?.(null); + }; + + /** + * Reset the search. + * @return void + */ + const handleClearSearch = () => { + setSearch(""); + }; + + // Fetch with debounce. + useEffect(() => { + // Reset options list if empty search or null + if (search.length === 0) { + setCurrentOptions(initalOptions); + return; + } + + const optionsFiltered = Object.fromEntries( + Object.entries(initalOptions).filter(([, item]) => + item.label.toLowerCase().includes(search), + ), + ); + + // Get updated options list with search. + setCurrentOptions(optionsFiltered); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [search, options]); + + return ( +
+ +
+ + + + + +
+
+ +
+ setSearch(e.target.value)} + className="w-[calc(100%-2.5rem-40px)] border-0 mx-9" + /> + } + tooltipContent={ +

+ {str(useTrans("crud.actions.delete")) + .ucFirst() + .value()} +

+ } + type="button" + variant="ghost" + size="icon" + className="absolute top-1/2 right-0 transform -translate-y-1/2 text-muted-foreground" + onClick={handleClearSearch} + disabled={search.length < 1 || disabled} + /> +
+
5 ? "h-[225px]" : "h-auto"}`, + )} + > + {Object.values(currentOptions).length === 0 && ( +

+ {transNoResults} +

+ )} +
+ {Object.values(currentOptions).map((option) => ( + + ))} +
+
+
+
+ {!required && selectedEnum !== null && ( + } + tooltipContent={ +

{str(transDelete).ucFirst().value()}

+ } + type="button" + variant="destructive" + size="icon" + onClick={handleClear} + /> + )}
-
5 ? "h-[225px]" : "h-auto"}`)} - > - {Object.values(currentOptions).length === 0 && ( -

{useTrans("back.table_no_results")}

- )} -
- {Object.values(currentOptions).map((option) => ( - - ))} -
-
- - - {!required && selectedEnum !== null && ( - } - tooltipContent={

{str(useTrans("crud.actions.delete")).ucFirst().value()}

} - type="button" - variant="destructive" - size="icon" - onClick={handleClear} - /> - )} -
- -
- ); + +
+ ); } diff --git a/resources/ts/back/Components/Inputs/ImageCropper.tsx b/resources/ts/back/Components/Inputs/ImageCropper.tsx index 6404101f..aa9c7aee 100644 --- a/resources/ts/back/Components/Inputs/ImageCropper.tsx +++ b/resources/ts/back/Components/Inputs/ImageCropper.tsx @@ -7,8 +7,8 @@ import { useRef, useState, type SyntheticEvent, - } from "react"; - import { +} from "react"; +import { ChevronDownIcon, CropIcon, FlipHorizontalIcon, @@ -20,15 +20,15 @@ import { ZoomInIcon, ZoomOutIcon, RefreshCwIcon, - } from "lucide-react"; - import { usePage } from "@inertiajs/react"; - import ReactCrop, { type Crop, type PixelCrop } from "react-image-crop"; - import { FileWithPath } from "react-dropzone"; - import "react-image-crop/dist/ReactCrop.css"; - import { route } from "ziggy-js"; - // * Components shadcn - import { Button } from "@/components/ui/button"; - import { +} from "lucide-react"; +import { usePage } from "@inertiajs/react"; +import ReactCrop, { type Crop, type PixelCrop } from "react-image-crop"; +import { FileWithPath } from "react-dropzone"; +import "react-image-crop/dist/ReactCrop.css"; +import { route } from "ziggy-js"; +// * Components shadcn +import { Button } from "@/components/ui/button"; +import { Dialog, DialogClose, DialogContent, @@ -36,35 +36,35 @@ import { DialogFooter, DialogTitle, DialogTrigger, - } from "@/components/ui/dialog"; - import { +} from "@/components/ui/dialog"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger, - } from "@/components/ui/collapsible"; - import { Slider } from "@/components/ui/slider"; - import { +} from "@/components/ui/collapsible"; +import { Slider } from "@/components/ui/slider"; +import { Tooltip, TooltipContent, TooltipTrigger, - } from "@/components/ui/tooltip"; - // * Other - import useTrans, { UseTransOptions } from "@/hooks/use-translations"; - import str from "@/hooks/use-string"; - import useDeviceType from "@/hooks/use-device-type"; -import { cn } from "@/lib/utils"; +} from "@/components/ui/tooltip"; +// * Other +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; +import useDeviceType from "@/hooks/use-device-type"; +import { cn, GetTranslation } from "@/lib/utils"; - interface CropValidationRules { +interface CropValidationRules { width: number; height: number; - } +} - type FileWithPreview = FileWithPath & { +type FileWithPreview = FileWithPath & { preview: string; - }; +}; - /* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */ - interface ImageCropperProps { +/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */ +interface ImageCropperProps { dialogOpen: boolean; name: string; value?: string | File | null; @@ -77,10 +77,10 @@ import { cn } from "@/lib/utils"; setDialogOpen: Dispatch>; reset: (name?: string) => void; setIsReset: (value: boolean) => void; - } - /* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */ +} +/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */ - export default function ImageCropper({ +export default function ImageCropper({ dialogOpen, setDialogOpen, selectedFile, @@ -93,7 +93,7 @@ import { cn } from "@/lib/utils"; isReset, url, finalFileName, - }: ImageCropperProps) { +}: ImageCropperProps) { const { errors } = usePage().props; const aspect = 1; @@ -114,8 +114,8 @@ import { cn } from "@/lib/utils"; const [isDragging, setIsDragging] = useState(false); const [dragStart, setDragStart] = useState({ x: 0, y: 0 }); const [originalDimensions, setOriginalDimensions] = useState({ - width: 0, - height: 0, + width: 0, + height: 0, }); // États pour les filtres @@ -147,8 +147,12 @@ import { cn } from "@/lib/utils"; // Position de l'image affichée avec zoom const displayedWidth = originalDimensions.width * displayScale; const displayedHeight = originalDimensions.height * displayScale; - const offsetX = imagePosition.x - (displayedWidth - originalDimensions.width * scaleFactor) / 2; - const offsetY = imagePosition.y - (displayedHeight - originalDimensions.height * scaleFactor) / 2; + const offsetX = + imagePosition.x - + (displayedWidth - originalDimensions.width * scaleFactor) / 2; + const offsetY = + imagePosition.y - + (displayedHeight - originalDimensions.height * scaleFactor) / 2; // Centre de l'image dans le container d'affichage const imageCenterX = offsetX + displayedWidth / 2; @@ -162,13 +166,8 @@ import { cn } from "@/lib/utils"; const deltaX = cropCenterX - imageCenterX; const deltaY = cropCenterY - imageCenterY; - // Calculer le ratio de qualité : on veut travailler à la résolution originale - // Le ratio est : taille originale / taille affichée - const qualityRatio = 1 / displayScale; - // Taille du canvas temporaire basée sur la résolution originale de la zone croppée // On limite toutefois pour éviter des canvas trop grands (max 4x la taille finale) - const maxRatio = Math.min(qualityRatio, 4); const tmpWidth = Math.ceil(crop.width / displayScale); const tmpHeight = Math.ceil(crop.height / displayScale); @@ -201,7 +200,7 @@ import { cn } from "@/lib/utils"; -originalDimensions.width / 2 - originalDeltaX, -originalDimensions.height / 2 - originalDeltaY, originalDimensions.width, - originalDimensions.height + originalDimensions.height, ); tmpCtx.restore(); @@ -216,7 +215,7 @@ import { cn } from "@/lib/utils"; 0, 0, canvas.width, - canvas.height + canvas.height, ); return canvas.toDataURL("image/png"); @@ -229,23 +228,23 @@ import { cn } from "@/lib/utils"; * @param errorCallback (error: string) => void */ function urlToBase64( - targetUrl: string, - // eslint-disable-next-line no-unused-vars - callback: (base64: string | ArrayBuffer | null) => void, - // eslint-disable-next-line no-unused-vars - errorCallback?: (error: string) => void, + targetUrl: string, + // eslint-disable-next-line no-unused-vars + callback: (base64: string | ArrayBuffer | null) => void, + // eslint-disable-next-line no-unused-vars + errorCallback?: (error: string) => void, ): void { - fetch(targetUrl) - .then((response) => response.blob()) - .then((blob) => { - const reader = new FileReader(); + fetch(targetUrl) + .then((response) => response.blob()) + .then((blob) => { + const reader = new FileReader(); - reader.onloadend = () => callback(reader.result); - reader.readAsDataURL(blob); - }) - .catch((error) => { - if (errorCallback) errorCallback(error); - }); + reader.onloadend = () => callback(reader.result); + reader.readAsDataURL(blob); + }) + .catch((error) => { + if (errorCallback) errorCallback(error); + }); } /** @@ -255,62 +254,62 @@ import { cn } from "@/lib/utils"; * @return File */ function base64ToFile(dataUrl: string): File { - const [meta, base64] = dataUrl.split(","); - const mimeMatch = meta.match(/:(.*?);/); - const mime = mimeMatch ? mimeMatch[1] : "image/png"; - const decodedBase64 = atob(base64); - const { length } = decodedBase64; - const u8arr = new Uint8Array(length); + const [meta, base64] = dataUrl.split(","); + const mimeMatch = meta.match(/:(.*?);/); + const mime = mimeMatch ? mimeMatch[1] : "image/png"; + const decodedBase64 = atob(base64); + const { length } = decodedBase64; + const u8arr = new Uint8Array(length); - for (let i = 0; i < length; i += 1) { - u8arr[i] = decodedBase64.charCodeAt(i); - } + for (let i = 0; i < length; i += 1) { + u8arr[i] = decodedBase64.charCodeAt(i); + } - return new File([u8arr], finalFileName, { type: mime }); + return new File([u8arr], finalFileName, { type: mime }); } // Fonctions de gestion du drag function handleMouseDown(e: MouseEvent) { - setIsDragging(true); - setDragStart({ - x: e.clientX - imagePosition.x, - y: e.clientY - imagePosition.y, - }); + setIsDragging(true); + setDragStart({ + x: e.clientX - imagePosition.x, + y: e.clientY - imagePosition.y, + }); } function handleMouseMove(e: MouseEvent) { - if (!isDragging) return; + if (!isDragging) return; - setImagePosition({ - x: e.clientX - dragStart.x, - y: e.clientY - dragStart.y, - }); + setImagePosition({ + x: e.clientX - dragStart.x, + y: e.clientY - dragStart.y, + }); } function handleMouseUp() { - setIsDragging(false); + setIsDragging(false); } // Reset de la position et dimensions quand l'image change useEffect(() => { - setImagePosition({ x: 0, y: 0 }); - setOriginalDimensions({ width: 0, height: 0 }); + setImagePosition({ x: 0, y: 0 }); + setOriginalDimensions({ width: 0, height: 0 }); }, [selectedFile]); useEffect(() => { - if (!value || !isDuplicating) return; - const pathFileBase = `${url}/${value}`; - urlToBase64( - pathFileBase, - (base64) => { - if (typeof base64 === "string") { - const file = base64ToFile(base64); - setData(name, file); - } - }, - (err) => console.error(err), - ); - // eslint-disable-next-line react-hooks/exhaustive-deps + if (!value || !isDuplicating) return; + const pathFileBase = `${url}/${value}`; + urlToBase64( + pathFileBase, + (base64) => { + if (typeof base64 === "string") { + const file = base64ToFile(base64); + setData(name, file); + } + }, + (err) => console.error(err), + ); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); /** @@ -318,40 +317,40 @@ import { cn } from "@/lib/utils"; * @return Promise */ async function onCrop(): Promise { - try { - if (imgRef.current && cropZone) { - // Recalculer les coordonnées en pixels à partir de cropZone actuel - // cropZone est en % par rapport au container de ReactCrop - const cropX = (cropZone.x / 100) * maxContainerWidth; - const cropY = (cropZone.y / 100) * maxContainerHeight; - const cropWidth = (cropZone.width / 100) * maxContainerWidth; - const cropHeight = (cropZone.height / 100) * maxContainerHeight; + try { + if (imgRef.current && cropZone) { + // Recalculer les coordonnées en pixels à partir de cropZone actuel + // cropZone est en % par rapport au container de ReactCrop + const cropX = (cropZone.x / 100) * maxContainerWidth; + const cropY = (cropZone.y / 100) * maxContainerHeight; + const cropWidth = (cropZone.width / 100) * maxContainerWidth; + const cropHeight = (cropZone.height / 100) * maxContainerHeight; - // Créer l'objet cropLocalization mis à jour - const currentCropLocalization: PixelCrop = { - unit: "px", - x: cropX, - y: cropY, - width: cropWidth, - height: cropHeight, - }; + // Créer l'objet cropLocalization mis à jour + const currentCropLocalization: PixelCrop = { + unit: "px", + x: cropX, + y: cropY, + width: cropWidth, + height: cropHeight, + }; - const finalImage = getCroppedImg( - imgRef.current, - currentCropLocalization, - ); - setCroppedImage(finalImage); - const file = base64ToFile(finalImage); - if (!isReset) { - setData(name, file); - } else { - reset(name); - } - setDialogOpen(false); + const finalImage = getCroppedImg( + imgRef.current, + currentCropLocalization, + ); + setCroppedImage(finalImage); + const file = base64ToFile(finalImage); + if (!isReset) { + setData(name, file); + } else { + reset(name); + } + setDialogOpen(false); + } + } catch (error: Error | unknown) { + throw new Error(`Something went wrong : ${error}`); } - } catch (error: Error | unknown) { - throw new Error(`Something went wrong : ${error}`); - } } /** @@ -361,56 +360,58 @@ import { cn } from "@/lib/utils"; * @param currentScaleFactor number */ function placeCropZone( - width: number, - height: number, - currentScaleFactor: number, + width: number, + height: number, + currentScaleFactor: number, ): void { - const displayedWidth = width * currentScaleFactor; - const displayedHeight = height * currentScaleFactor; + const displayedWidth = width * currentScaleFactor; + const displayedHeight = height * currentScaleFactor; - // Calculer l'offset pour centrer l'image dans le container - const centerOffsetX = (maxContainerWidth - displayedWidth) / 2; - const centerOffsetY = (maxContainerHeight - displayedHeight) / 2; + // Calculer l'offset pour centrer l'image dans le container + const centerOffsetX = (maxContainerWidth - displayedWidth) / 2; + const centerOffsetY = (maxContainerHeight - displayedHeight) / 2; - // Initialiser la position centrée (seulement si imagePosition est à 0,0) - if (imagePosition.x === 0 && imagePosition.y === 0) { - setImagePosition({ x: centerOffsetX, y: centerOffsetY }); - } + // Initialiser la position centrée (seulement si imagePosition est à 0,0) + if (imagePosition.x === 0 && imagePosition.y === 0) { + setImagePosition({ x: centerOffsetX, y: centerOffsetY }); + } - // Zone de crop simple : garder les dimensions d'origine, réduire seulement si ça dépasse le container - let finalCropWidth = validationRules.width; - let finalCropHeight = validationRules.height; + // Zone de crop simple : garder les dimensions d'origine, réduire seulement si ça dépasse le container + let finalCropWidth = validationRules.width; + let finalCropHeight = validationRules.height; - // Si la zone dépasse le container, la réduire proportionnellement - if ( - finalCropWidth > maxContainerWidth * 0.9 || - finalCropHeight > maxContainerHeight * 0.9 - ) { - const containerWidthRatio = (maxContainerWidth * 0.9) / finalCropWidth; - const containerHeightRatio = (maxContainerHeight * 0.9) / finalCropHeight; - const reductionRatio = Math.min( - containerWidthRatio, - containerHeightRatio, + // Si la zone dépasse le container, la réduire proportionnellement + if ( + finalCropWidth > maxContainerWidth * 0.9 || + finalCropHeight > maxContainerHeight * 0.9 + ) { + const containerWidthRatio = + (maxContainerWidth * 0.9) / finalCropWidth; + const containerHeightRatio = + (maxContainerHeight * 0.9) / finalCropHeight; + const reductionRatio = Math.min( + containerWidthRatio, + containerHeightRatio, + ); + + finalCropWidth = validationRules.width * reductionRatio; + finalCropHeight = validationRules.height * reductionRatio; + } + + // Convertir en pourcentage par rapport au CONTAINER (pas à l'image) + const cropWidthPercent = (finalCropWidth / maxContainerWidth) * 100; + const cropHeightPercent = (finalCropHeight / maxContainerHeight) * 100; + + setCropZone( + cropZone ?? { + unit: "%", + width: cropWidthPercent, + height: cropHeightPercent, + x: (100 - cropWidthPercent) / 2, // Centrer horizontalement + y: (100 - cropHeightPercent) / 2, // Centrer verticalement + }, ); - - finalCropWidth = validationRules.width * reductionRatio; - finalCropHeight = validationRules.height * reductionRatio; - } - - // Convertir en pourcentage par rapport au CONTAINER (pas à l'image) - const cropWidthPercent = (finalCropWidth / maxContainerWidth) * 100; - const cropHeightPercent = (finalCropHeight / maxContainerHeight) * 100; - - setCropZone( - cropZone ?? { - unit: "%", - width: cropWidthPercent, - height: cropHeightPercent, - x: (100 - cropWidthPercent) / 2, // Centrer horizontalement - y: (100 - cropHeightPercent) / 2, // Centrer verticalement - }, - ); - }; + } /** * Load image when open the dialog. @@ -418,18 +419,18 @@ import { cn } from "@/lib/utils"; * @return void */ function onImageLoad(e: SyntheticEvent): void { - const { naturalWidth: width, naturalHeight: height } = e.currentTarget; + const { naturalWidth: width, naturalHeight: height } = e.currentTarget; - // STOCKER les dimensions naturelles originales - setOriginalDimensions({ width, height }); + // STOCKER les dimensions naturelles originales + setOriginalDimensions({ width, height }); - // Calculer le facteur d'échelle pour l'image - const imageWidthRatio = maxContainerWidth / width; - const imageHeightRatio = maxContainerHeight / height; - const imageScaleFactor = Math.min(imageWidthRatio, imageHeightRatio, 1); // Ne pas agrandir l'image + // Calculer le facteur d'échelle pour l'image + const imageWidthRatio = maxContainerWidth / width; + const imageHeightRatio = maxContainerHeight / height; + const imageScaleFactor = Math.min(imageWidthRatio, imageHeightRatio, 1); // Ne pas agrandir l'image - setScaleFactor(imageScaleFactor); - placeCropZone(width, height, imageScaleFactor); + setScaleFactor(imageScaleFactor); + placeCropZone(width, height, imageScaleFactor); } /** @@ -437,521 +438,618 @@ import { cn } from "@/lib/utils"; * @return void */ function resetToInitialState(): void { - // Options reset. - setRotation(0); - setFlipX(false); - setFlipY(false); - setZoom(0); - setBrightness(100); - setContrast(100); - setSaturation(100); - setSepia(0); - setGrayscale(0); - if (value) setIsReset(true); + // Options reset. + setRotation(0); + setFlipX(false); + setFlipY(false); + setZoom(0); + setBrightness(100); + setContrast(100); + setSaturation(100); + setSepia(0); + setGrayscale(0); + if (value) setIsReset(true); - // Recalculer et forcer le centrage de l'image ET de la zone de crop - if (imgRef.current && originalDimensions.width > 0) { - const displayedWidth = originalDimensions.width * scaleFactor; - const displayedHeight = originalDimensions.height * scaleFactor; + // Recalculer et forcer le centrage de l'image ET de la zone de crop + if (imgRef.current && originalDimensions.width > 0) { + const displayedWidth = originalDimensions.width * scaleFactor; + const displayedHeight = originalDimensions.height * scaleFactor; - // Calculer l'offset pour centrer l'image dans le container - const centerOffsetX = (maxContainerWidth - displayedWidth) / 2; - const centerOffsetY = (maxContainerHeight - displayedHeight) / 2; + // Calculer l'offset pour centrer l'image dans le container + const centerOffsetX = (maxContainerWidth - displayedWidth) / 2; + const centerOffsetY = (maxContainerHeight - displayedHeight) / 2; - // Forcer la position centrée - setImagePosition({ x: centerOffsetX, y: centerOffsetY }); + // Forcer la position centrée + setImagePosition({ x: centerOffsetX, y: centerOffsetY }); - // IMPORTANT: Recalculer la zone de crop centrée - let finalCropWidth = validationRules.width; - let finalCropHeight = validationRules.height; + // IMPORTANT: Recalculer la zone de crop centrée + let finalCropWidth = validationRules.width; + let finalCropHeight = validationRules.height; - // Si la zone dépasse le container, la réduire proportionnellement - if ( - finalCropWidth > maxContainerWidth * 0.9 || - finalCropHeight > maxContainerHeight * 0.9 - ) { - const containerWidthRatio = (maxContainerWidth * 0.9) / finalCropWidth; - const containerHeightRatio = - (maxContainerHeight * 0.9) / finalCropHeight; - const reductionRatio = Math.min( - containerWidthRatio, - containerHeightRatio, - ); + // Si la zone dépasse le container, la réduire proportionnellement + if ( + finalCropWidth > maxContainerWidth * 0.9 || + finalCropHeight > maxContainerHeight * 0.9 + ) { + const containerWidthRatio = + (maxContainerWidth * 0.9) / finalCropWidth; + const containerHeightRatio = + (maxContainerHeight * 0.9) / finalCropHeight; + const reductionRatio = Math.min( + containerWidthRatio, + containerHeightRatio, + ); - finalCropWidth = validationRules.width * reductionRatio; - finalCropHeight = validationRules.height * reductionRatio; + finalCropWidth = validationRules.width * reductionRatio; + finalCropHeight = validationRules.height * reductionRatio; + } + + // Convertir en pourcentage et centrer + const cropWidthPercent = (finalCropWidth / maxContainerWidth) * 100; + const cropHeightPercent = + (finalCropHeight / maxContainerHeight) * 100; + + setCropZone({ + unit: "%", + width: cropWidthPercent, + height: cropHeightPercent, + x: (100 - cropWidthPercent) / 2, // Centrer horizontalement + y: (100 - cropHeightPercent) / 2, // Centrer verticalement + }); + } else { + // Si pas d'image, remettre à 0,0 + setImagePosition({ x: 0, y: 0 }); } - - // Convertir en pourcentage et centrer - const cropWidthPercent = (finalCropWidth / maxContainerWidth) * 100; - const cropHeightPercent = (finalCropHeight / maxContainerHeight) * 100; - - setCropZone({ - unit: "%", - width: cropWidthPercent, - height: cropHeightPercent, - x: (100 - cropWidthPercent) / 2, // Centrer horizontalement - y: (100 - cropHeightPercent) / 2, // Centrer verticalement - }); - } else { - // Si pas d'image, remettre à 0,0 - setImagePosition({ x: 0, y: 0 }); - } } // Translations. - const transBrightness = str(useTrans("back.image_cropper.filters.brightness")).ucFirst().value(); - const transContrast = str(useTrans("back.image_cropper.filters.contrast")).ucFirst().value(); - const transSaturation = str(useTrans("back.image_cropper.filters.saturation")).ucFirst().value(); - const transSepia = str(useTrans("back.image_cropper.filters.sepia")).ucFirst().value(); - const transGrayscale = str(useTrans("back.image_cropper.filters.grayscale")).ucFirst().value(); - const transRotation = str(useTrans("back.image_cropper.filters.rotation")).ucFirst().value(); - const transZoom = str(useTrans("back.image_cropper.filters.zoom")).ucFirst().value(); - - const GetTranslation = (keyName: string, options?: UseTransOptions) => { - return useTrans(keyName, options); - }; + const transBrightness = str( + useTrans("back.image_cropper.filters.brightness"), + ) + .ucFirst() + .value(); + const transContrast = str(useTrans("back.image_cropper.filters.contrast")) + .ucFirst() + .value(); + const transSaturation = str( + useTrans("back.image_cropper.filters.saturation"), + ) + .ucFirst() + .value(); + const transSepia = str(useTrans("back.image_cropper.filters.sepia")) + .ucFirst() + .value(); + const transGrayscale = str(useTrans("back.image_cropper.filters.grayscale")) + .ucFirst() + .value(); + const transRotation = str(useTrans("back.image_cropper.filters.rotation")) + .ucFirst() + .value(); + const transZoom = str(useTrans("back.image_cropper.filters.zoom")) + .ucFirst() + .value(); // Filters (brightness, contrast, saturation, sepia, grayscale). const imageFilterOptions = [ - { - label: () => `${transBrightness}: ${brightness}%`, - tooltip: "brightness", - slider: { - min: 0, - max: 200, - step: 1, - value: [brightness], - onValueChange: (e: number[]) => { - setIsReset(false); - setBrightness(parseInt(e[0].toString(), 10)); - }, + { + label: () => `${transBrightness}: ${brightness}%`, + tooltip: "brightness", + slider: { + min: 0, + max: 200, + step: 1, + value: [brightness], + onValueChange: (e: number[]) => { + setIsReset(false); + setBrightness(parseInt(e[0].toString(), 10)); + }, + }, }, - }, - { - label: () => `${transContrast}: ${contrast}%`, - tooltip: "contrast", - slider: { - min: 0, - max: 200, - step: 1, - value: [contrast], - onValueChange: (e: number[]) => { - setContrast(parseInt(e[0].toString(), 10)); - setIsReset(false); - }, + { + label: () => `${transContrast}: ${contrast}%`, + tooltip: "contrast", + slider: { + min: 0, + max: 200, + step: 1, + value: [contrast], + onValueChange: (e: number[]) => { + setContrast(parseInt(e[0].toString(), 10)); + setIsReset(false); + }, + }, }, - }, - { - label: () => `${transSaturation}: ${saturation}%`, - tooltip: "saturation", - slider: { - min: 0, - max: 200, - step: 1, - value: [saturation], - onValueChange: (e: number[]) => { - setSaturation(parseInt(e[0].toString(), 10)); - setIsReset(false); - }, + { + label: () => `${transSaturation}: ${saturation}%`, + tooltip: "saturation", + slider: { + min: 0, + max: 200, + step: 1, + value: [saturation], + onValueChange: (e: number[]) => { + setSaturation(parseInt(e[0].toString(), 10)); + setIsReset(false); + }, + }, }, - }, - { - label: () => `${transSepia}: ${sepia}%`, - tooltip: "sepia", - slider: { - min: 0, - max: 100, - step: 1, - value: [sepia], - onValueChange: (e: number[]) => { - setSepia(parseInt(e[0].toString(), 10)); - setIsReset(false); - }, + { + label: () => `${transSepia}: ${sepia}%`, + tooltip: "sepia", + slider: { + min: 0, + max: 100, + step: 1, + value: [sepia], + onValueChange: (e: number[]) => { + setSepia(parseInt(e[0].toString(), 10)); + setIsReset(false); + }, + }, }, - }, - { - label: () => `${transGrayscale}: ${grayscale}%`, - tooltip: "grayscale", - slider: { - min: 0, - max: 100, - step: 1, - value: [grayscale], - onValueChange: (e: number[]) => { - setGrayscale(parseInt(e[0].toString(), 10)); - setIsReset(false); - }, + { + label: () => `${transGrayscale}: ${grayscale}%`, + tooltip: "grayscale", + slider: { + min: 0, + max: 100, + step: 1, + value: [grayscale], + onValueChange: (e: number[]) => { + setGrayscale(parseInt(e[0].toString(), 10)); + setIsReset(false); + }, + }, }, - }, ]; // Main options (rotation, zoom). const mainOptions = [ - { - label: () => `${transRotation}: ${rotation}°`, - tooltip: "rotation", - slider: { - min: -180, - max: 180, - step: 1, - value: [rotation], - onValueChange: (e: number[]) => { - setRotation(parseInt(e[0].toString(), 10)); - setIsReset(false); - }, - }, - buttons: [ - { - icon: RotateCcwIcon, - tooltip: "rotation_back", - fn: () => setRotation((r) => r - 10), - }, - { - icon: RotateCwIcon, - tooltip: "rotation_forward", - fn: () => setRotation((r) => r + 10), - }, - ], - }, - { - label: () => `${transZoom}: ${Math.round((1 + zoom) * 100)}%`, - tooltip: "zoom", - slider: { - min: -0.99, - max: 500, - step: 0.1, - value: [Math.round((1 + zoom) * 100)], - onValueChange: (e: number[]) => { - setZoom(e[0] / 100 - 1); - setIsReset(false); - }, - }, - buttons: [ - { - icon: ZoomOutIcon, - tooltip: "zoomOut", - fn: () => { - setZoom((currentValue) => { - const newValue = currentValue - 0.1; - return newValue < -0.99 ? -0.99 : parseFloat(newValue.toFixed(1)); - }); - setIsReset(false); + { + label: () => `${transRotation}: ${rotation}°`, + tooltip: "rotation", + slider: { + min: -180, + max: 180, + step: 1, + value: [rotation], + onValueChange: (e: number[]) => { + setRotation(parseInt(e[0].toString(), 10)); + setIsReset(false); + }, }, - }, - { - icon: ZoomInIcon, - tooltip: "zoomIn", - fn: () => { - setZoom((currentValue) => { - const newValue = currentValue + 0.1; - return newValue > 4 ? 4 : parseFloat(newValue.toFixed(1)); - }); - setIsReset(false); + buttons: [ + { + icon: RotateCcwIcon, + tooltip: "rotation_back", + fn: () => setRotation((r) => r - 10), + }, + { + icon: RotateCwIcon, + tooltip: "rotation_forward", + fn: () => setRotation((r) => r + 10), + }, + ], + }, + { + label: () => `${transZoom}: ${Math.round((1 + zoom) * 100)}%`, + tooltip: "zoom", + slider: { + min: -0.99, + max: 500, + step: 0.1, + value: [Math.round((1 + zoom) * 100)], + onValueChange: (e: number[]) => { + setZoom(e[0] / 100 - 1); + setIsReset(false); + }, }, - }, - ], - }, + buttons: [ + { + icon: ZoomOutIcon, + tooltip: "zoomOut", + fn: () => { + setZoom((currentValue) => { + const newValue = currentValue - 0.1; + return newValue < -0.99 + ? -0.99 + : parseFloat(newValue.toFixed(1)); + }); + setIsReset(false); + }, + }, + { + icon: ZoomInIcon, + tooltip: "zoomIn", + fn: () => { + setZoom((currentValue) => { + const newValue = currentValue + 0.1; + return newValue > 4 + ? 4 + : parseFloat(newValue.toFixed(1)); + }); + setIsReset(false); + }, + }, + ], + }, ]; // Other options (reset, horizontal and vertical flip) const otherOptions = [ - { - icon: FlipHorizontalIcon, - fn: () => setFlipX((prev) => !prev), - tooltip: "horizontal_flip", - }, - { - icon: FlipVerticalIcon, - fn: () => setFlipY((prev) => !prev), - tooltip: "vertical_flip", - }, - { - icon: RefreshCwIcon, - fn: resetToInitialState, - tooltip: "reset", - }, + { + icon: FlipHorizontalIcon, + fn: () => setFlipX((prev) => !prev), + tooltip: "horizontal_flip", + }, + { + icon: FlipVerticalIcon, + fn: () => setFlipY((prev) => !prev), + tooltip: "vertical_flip", + }, + { + icon: RefreshCwIcon, + fn: resetToInitialState, + tooltip: "reset", + }, ]; return ( - -
- - - -
- - {useTrans("back.image_cropper.modale_title")} -
- {/* Cropper content */} -
- setCropZone(percentCrop)} - aspect={aspect} - className="w-full" - locked - > -
- {useTrans('back.image_cropper.preview_image')} 0 ? `${originalDimensions.width * scaleFactor}px` : "auto", - height: originalDimensions.height > 0 ? `${originalDimensions.height * scaleFactor}px` : "auto", - transform: `scale(${1 + zoom}) rotate(${rotation}deg) scaleX(${flipX ? -1 : 1}) scaleY(${flipY ? -1 : 1})`, - filter: `brightness(${brightness}%) contrast(${contrast}%) saturate(${saturation}%) sepia(${sepia}%) grayscale(${grayscale}%)`, - transformOrigin: "center center", - transition: !isDragging ? "transform 0.2s ease, filter 0.2s ease" : "none", - cursor: isDragging ? "grabbing" : "grab", - userSelect: "none", - }} - draggable={false} - /> -
-
-
- {/* Cropper filters */} -
-
- - {useTrans("back.image_cropper.modale_description")} - - {mainOptions.map((option) => ( -
-
- - - - - - - {str( - GetTranslation( - `back.image_cropper.filters.${option.tooltip}`, - ), - ) - .ucFirst() - .value()} - - -
-
- {option.buttons.map((currentOption) => ( - - - - - - {str( - GetTranslation( - `back.image_cropper.filters.${currentOption.tooltip}`, - ), - ) - .ucFirst() - .value()} - - - ))} -
-
- ))} - {/* FILTRES - Collapsible */} - - - - - -
- {imageFilterOptions.map((option) => ( -
- - - - - - - {str( - GetTranslation( - `back.image_cropper.filters.${option.tooltip}`, - ), - ) - .ucFirst() - .value()} - - -
- ))} -
-
-
- {/* Others actions */} -
- {otherOptions.map((option) => { - return ( - - - - - - {str( - GetTranslation( - `back.image_cropper.filters.${option.tooltip}`, - ), - ) - .ucFirst() - .value()} - - - ); - })} -
-
- - - - - - - - {str( - useTrans("back.image_cropper.action_the_crop", { - params: { - action: str(useTrans("back.cancel")) - .ucFirst() - .value(), - }, - }), - ) - .ucFirst() - .value()} - - - - - + +
+ - - - {str( - useTrans("back.image_cropper.action_the_crop", { - params: { - action: str(useTrans("back.validate")) - .ucFirst() - .value(), - }, - }), - ) - .ucFirst() - .value()} - - - +
-
- -
+ + + {useTrans("back.image_cropper.modale_title")} + +
+ {/* Cropper content */} +
+ + setCropZone(percentCrop) + } + aspect={aspect} + className="w-full" + locked + > +
+ {useTrans( 0 + ? `${originalDimensions.width * scaleFactor}px` + : "auto", + height: + originalDimensions.height > 0 + ? `${originalDimensions.height * scaleFactor}px` + : "auto", + transform: `scale(${1 + zoom}) rotate(${rotation}deg) scaleX(${flipX ? -1 : 1}) scaleY(${flipY ? -1 : 1})`, + filter: `brightness(${brightness}%) contrast(${contrast}%) saturate(${saturation}%) sepia(${sepia}%) grayscale(${grayscale}%)`, + transformOrigin: "center center", + transition: !isDragging + ? "transform 0.2s ease, filter 0.2s ease" + : "none", + cursor: isDragging + ? "grabbing" + : "grab", + userSelect: "none", + }} + draggable={false} + /> +
+
+
+ {/* Cropper filters */} +
+
+ + {useTrans( + "back.image_cropper.modale_description", + )} + + {mainOptions.map((option) => ( +
+
+ + + + + + + {str( + GetTranslation( + `back.image_cropper.filters.${option.tooltip}`, + ), + ) + .ucFirst() + .value()} + + +
+
+ {option.buttons.map((currentOption) => ( + + + + + + {str( + GetTranslation( + `back.image_cropper.filters.${currentOption.tooltip}`, + ), + ) + .ucFirst() + .value()} + + + ))} +
+
+ ))} + {/* FILTRES - Collapsible */} + + + + + +
+ {imageFilterOptions.map((option) => ( +
+ + + + + + + {str( + GetTranslation( + `back.image_cropper.filters.${option.tooltip}`, + ), + ) + .ucFirst() + .value()} + + +
+ ))} +
+
+
+ {/* Others actions */} +
+ {otherOptions.map((option) => { + return ( + + + + + + {str( + GetTranslation( + `back.image_cropper.filters.${option.tooltip}`, + ), + ) + .ucFirst() + .value()} + + + ); + })} +
+
+ + + + + + + + {str( + useTrans( + "back.image_cropper.action_the_crop", + { + params: { + action: str( + useTrans( + "back.cancel", + ), + ) + .ucFirst() + .value(), + }, + }, + ), + ) + .ucFirst() + .value()} + + + + + + + + + {str( + useTrans( + "back.image_cropper.action_the_crop", + { + params: { + action: str( + useTrans( + "back.validate", + ), + ) + .ucFirst() + .value(), + }, + }, + ), + ) + .ucFirst() + .value()} + + + +
+
+
+ ); - } +} diff --git a/resources/ts/back/Components/Inputs/ModelSelect.tsx b/resources/ts/back/Components/Inputs/ModelSelect.tsx index 594dfd27..09c852a4 100644 --- a/resources/ts/back/Components/Inputs/ModelSelect.tsx +++ b/resources/ts/back/Components/Inputs/ModelSelect.tsx @@ -24,6 +24,8 @@ import { ChevronLeftIcon, ChevronRightIcon, } from "lucide-react"; +import axios, { isAxiosError } from "axios"; +import { route } from "ziggy-js"; // * Components shadcn import { Separator } from "@/components/ui/separator"; import { Button } from "@/components/ui/button"; @@ -42,21 +44,14 @@ import { } from "@/components/ui/command"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; +import { Skeleton } from "@/components/ui/skeleton"; // * Other import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import InputError from "@/back/Components/InputError"; -import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import { cn } from "@/lib/utils"; -import axios from "axios"; -import { route } from "ziggy-js"; -import { - AppEnv, - Model, - Paginator, - TranslationField, -} from "@/back/types/global"; -import { Skeleton } from "@/components/ui/skeleton"; +import { cn, GetTranslation } from "@/lib/utils"; +import { AppEnv, DefaultModel, Paginator } from "@/back/types/global"; +import { TranslationField } from "@/back/types/i18n"; /** * Animation types and configurations @@ -115,13 +110,15 @@ interface ModelSelectProps * Callback function triggered when the selected values change. * Receives an array of the new selected values. */ + // eslint-disable-next-line no-unused-vars onValueChange?: (value: number[]) => void; /** * Callback function triggered when the selected values change. * Receives a single or array of selected Model(s). */ - onModelChange?: (value: Model[]) => void; + // eslint-disable-next-line no-unused-vars + onModelChange?: (value: DefaultModel[]) => void; /** The default selected values when the component mounts. */ defaultValues?: number[]; @@ -161,6 +158,7 @@ interface ModelSelectProps * If true, renders the multi-select component as a child of another component. * Optional, defaults to false. */ + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars asChild?: boolean; /** @@ -294,6 +292,7 @@ interface ModelSelectProps /** * The fonction to set the data in useForm inertia */ + // eslint-disable-next-line no-unused-vars setData: (name: string, value: number[] | number | null) => void; /** @@ -357,6 +356,7 @@ export interface ModelSelectRef { /** * Set selected values programmatically */ + // eslint-disable-next-line no-unused-vars setSelectedValues: (values: number[]) => void; /** * Clear all selected values @@ -388,6 +388,7 @@ export const ModelSelect = forwardRef( animationConfig, maxCount = 3, modalPopover = false, + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars asChild = false, className, hideSelectAll = false, @@ -415,7 +416,9 @@ export const ModelSelect = forwardRef( const [selectedValues, setSelectedValues] = useState(defaultValues); - const [selectedModels, setSelectedModels] = useState([]); + const [selectedModels, setSelectedModels] = useState( + [], + ); const [isPopoverOpen, setIsPopoverOpen] = useState(false); const [isAnimating, setIsAnimating] = useState(false); @@ -445,8 +448,8 @@ export const ModelSelect = forwardRef( const [loading, setLoading] = useState(false); const [initialLoading, setInitialLoading] = useState(true); - const [options, setOptions] = useState([]); - const [optionsMerged, setOptionsMerged] = useState([]); + const [options, setOptions] = useState([]); + const [optionsMerged, setOptionsMerged] = useState([]); // Custom by field parameter or predefined values (title, name or label). const [dynamicField, setDynamicField] = useState( field ?? null, @@ -489,16 +492,6 @@ export const ModelSelect = forwardRef( return response.data; }; - /** - * Get specific page. - * @param pageNumber number - * @return void - */ - const goToPage = async (pageNumber: number) => { - if (pageNumber < 1 || pageNumber > lastPage) return; - await getData(pageNumber); - }; - /** * Get new options list with his target field. * @param pageNumber number @@ -506,27 +499,30 @@ export const ModelSelect = forwardRef( */ const getData = async (pageNumber = 1) => { // Increment search id. - const requestId = ++requestIdRef.current; + requestIdRef.current += 1; + const requestId = requestIdRef.current; setLoading(true); try { const data = (await fetchOptions(pageNumber)) as { items: Paginator; field: string; - model: Model[]; + model: DefaultModel[]; }; // Ignore obsolete answers. if (requestId !== requestIdRef.current) return; - const dataModel: Model[] = data.model + const dataModel: DefaultModel[] = data.model ? Object.values(data.model) : []; - const dataItems: Model[] = Array.isArray(data?.items?.data) + const dataItems: DefaultModel[] = Array.isArray( + data?.items?.data, + ) ? data.items.data : []; setOptionsMerged(() => { const merged = [...dataModel, ...dataItems] // Supprime les éléments undefined ou sans id .filter( - (item): item is Model => + (item): item is DefaultModel => !!item && item.id !== undefined, ) // Supprime les doublons par id @@ -542,11 +538,14 @@ export const ModelSelect = forwardRef( setOptions(data.items.data ?? []); setPage(data.items.current_page); setLastPage(data.items.last_page ?? 1); - } catch (err: any) { + } catch (err: unknown) { // Ignore obsolete errors. if (requestId !== requestIdRef.current) return; console.error(err); - setErrorsAjax(err.response?.data?.errors); + if (isAxiosError(err) && err.response?.data?.errors) { + setErrorsAjax(err.response?.data?.errors); + } + setOptions([]); setLastPage(1); } finally { @@ -557,23 +556,42 @@ export const ModelSelect = forwardRef( setInitialLoading(false); } }; + + /** + * Get specific page. + * @param pageNumber number + * @return void + */ + const goToPage = async (pageNumber: number) => { + if (pageNumber < 1 || pageNumber > lastPage) return; + await getData(pageNumber); + }; + useEffect(() => { if (disabled) { - return; + return undefined; } // Reset options list if empty search or null if (targetModel && searchValue.length === 0) { getData(); - return; + return undefined; } // Nothing to do if search is below 3 caracters. - if (searchValue.length < 3) return; + if (searchValue.length < 3) return undefined; // Get updated options list with search. const handler = setTimeout(() => getData(), 300); - return () => clearTimeout(handler); + + function cleanup(): void { + if (handler) { + clearTimeout(handler); + } + } + + return cleanup; + // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchValue, targetModel]); const announce = useCallback( @@ -595,15 +613,19 @@ export const ModelSelect = forwardRef( const selectedCountId = `${multiSelectId}-count`; // Translations. - const transDelete = useTrans("crud.actions.delete"); - const transClose = useTrans("back.close"); - const transClear = useTrans("back.clear"); - const transNoResults = useTrans("back.table_no_results"); - const transSearchOptions = useTrans("back.multi_select.search_options"); - const transSelectAll = useTrans("back.multi_select.select_all"); - const transMore = useTrans("back.multi_select.more"); - const transClosePopover = useTrans("back.multi_select.close_popover"); - const transClearList = useTrans("back.multi_select.clear_list"); + const transDelete = GetTranslation("crud.actions.delete"); + const transClose = GetTranslation("back.close"); + const transClear = GetTranslation("back.clear"); + const transNoResults = GetTranslation("back.table_no_results"); + const transSearchOptions = GetTranslation( + "back.multi_select.search_options", + ); + const transSelectAll = GetTranslation("back.multi_select.select_all"); + const transMore = GetTranslation("back.multi_select.more"); + const transClosePopover = GetTranslation( + "back.multi_select.close_popover", + ); + const transClearList = GetTranslation("back.multi_select.clear_list"); const prevDefaultValueRef = useRef(defaultValues); @@ -622,6 +644,7 @@ export const ModelSelect = forwardRef( onValueChange(defaultValues); } setData(name, multiple ? defaultValues : defaultValues[0]); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [defaultValues, onValueChange]); const buttonRef = useRef(null); @@ -665,6 +688,7 @@ export const ModelSelect = forwardRef( } }, }), + // eslint-disable-next-line react-hooks/exhaustive-deps [resetToDefault, selectedValues, onValueChange], ); @@ -673,7 +697,7 @@ export const ModelSelect = forwardRef( >("desktop"); useEffect(() => { - if (typeof window === "undefined") return; + if (typeof window === "undefined") return undefined; const handleResize = () => { const width = window.innerWidth; if (width < 640) { @@ -696,7 +720,7 @@ export const ModelSelect = forwardRef( const getResponsiveSettings = () => { if (!responsive) { return { - maxCount: maxCount, + maxCount, hideIcons: false, compactMode: false, }; @@ -780,13 +804,12 @@ export const ModelSelect = forwardRef( return ""; }; - const getAllOptions = useCallback((): Model[] => { + const getAllOptions = useCallback((): DefaultModel[] => { if (optionsMerged.length === 0) return []; - let allOptions: Model[]; - allOptions = optionsMerged; + const allOptions: DefaultModel[] = optionsMerged; const valueSet = new Set(); const duplicates: string[] = []; - const uniqueOptions: Model[] = []; + const uniqueOptions: DefaultModel[] = []; allOptions.forEach((option) => { if (valueSet.has(option.id.toString())) { duplicates.push(option.id.toString()); @@ -817,13 +840,11 @@ export const ModelSelect = forwardRef( ); } return deduplicateOptions ? uniqueOptions : allOptions; - }, [options, deduplicateOptions]); + }, [optionsMerged, deduplicateOptions]); const getOptionByValue = useCallback( - (id: number): Model | undefined => { - const option = getAllOptions().find( - (option) => option.id === id, - ); + (id: number): DefaultModel | undefined => { + const option = getAllOptions().find((opt) => opt.id === id); if (!option && process.env.NODE_ENV === "development") { console.warn( `MultiSelect: Option with value "${id}" not found in options list`, @@ -860,7 +881,7 @@ export const ModelSelect = forwardRef( } }; - const toggleOption = (option: Model) => { + const toggleOption = (option: DefaultModel) => { if (disabled) return; // MODE SINGLE SELECT if (!multiple) { @@ -1067,73 +1088,77 @@ export const ModelSelect = forwardRef( } }, [isPopoverOpen]); - useEffect(() => { - const selectedCount = selectedValues.length; - const allOptions = getAllOptions(); - const totalOptions = allOptions.length; - if (selectedCount !== prevSelectedCount.current) { - const diff = selectedCount - prevSelectedCount.current; - if (diff > 0) { - const addedItems = selectedValues.slice(-diff); - const addedLabels = addedItems - .map( - (value) => - allOptions.find((opt) => opt.id === value)?.[ - dynamicField as keyof Model - ], - ) - .filter(Boolean); + useEffect( + () => { + const selectedCount = selectedValues.length; + const allOptions = getAllOptions(); + const totalOptions = allOptions.length; + if (selectedCount !== prevSelectedCount.current) { + const diff = selectedCount - prevSelectedCount.current; + if (diff > 0) { + const addedItems = selectedValues.slice(-diff); + const addedLabels = addedItems + .map( + (value) => + allOptions.find( + (opt) => opt.id === value, + )?.[dynamicField as keyof DefaultModel], + ) + .filter(Boolean); - if (addedLabels.length === 1) { + if (addedLabels.length === 1) { + announce( + `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`, + ); + } else { + announce( + `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`, + ); + } + } else if (diff < 0) { announce( - `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`, - ); - } else { - announce( - `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`, + `Option removed. ${selectedCount} of ${totalOptions} options selected.`, ); } - } else if (diff < 0) { - announce( - `Option removed. ${selectedCount} of ${totalOptions} options selected.`, - ); + prevSelectedCount.current = selectedCount; } - prevSelectedCount.current = selectedCount; - } - if (isPopoverOpen !== prevIsOpen.current) { - if (isPopoverOpen) { - announce( - `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`, - ); - } else { - announce("Dropdown closed."); + if (isPopoverOpen !== prevIsOpen.current) { + if (isPopoverOpen) { + announce( + `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`, + ); + } else { + announce("Dropdown closed."); + } + prevIsOpen.current = isPopoverOpen; } - prevIsOpen.current = isPopoverOpen; - } - if ( - searchValue !== prevSearchValue.current && - searchValue !== undefined - ) { - if (searchValue && isPopoverOpen) { - const filteredCount = allOptions.length; + if ( + searchValue !== prevSearchValue.current && + searchValue !== undefined + ) { + if (searchValue && isPopoverOpen) { + const filteredCount = allOptions.length; - announce( - `${filteredCount} option${ - filteredCount === 1 ? "" : "s" - } found for "${searchValue}"`, - ); + announce( + `${filteredCount} option${ + filteredCount === 1 ? "" : "s" + } found for "${searchValue}"`, + ); + } + prevSearchValue.current = searchValue; } - prevSearchValue.current = searchValue; - } - }, [ - selectedValues, - isPopoverOpen, - searchValue, - announce, - getAllOptions, - ]); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [ + selectedValues, + isPopoverOpen, + searchValue, + announce, + getAllOptions, + ], + ); useEffect(() => { if ( @@ -1161,10 +1186,10 @@ export const ModelSelect = forwardRef( } }, [minSelection, maxSelection, multiple]); - const getModelField = (option: Model): string => { - const value = option[dynamicField as keyof Model] as unknown as - | TranslationField - | string; + const getModelField = (option: DefaultModel): string => { + const value = option[ + dynamicField as keyof DefaultModel + ] as unknown as TranslationField | string; if (typeof value === "object") return String(value[locale] ?? ""); return String(value ?? ""); }; @@ -1209,7 +1234,7 @@ export const ModelSelect = forwardRef( } selected: ${selectedValues .map((value) => { const option = getOptionByValue(value); - if (!option) return; + if (!option) return undefined; return getModelField(option); }) .filter(Boolean) @@ -1218,6 +1243,7 @@ export const ModelSelect = forwardRef( - )} - -
-
- - )} - - ) : ( + {selectedValues.length === 0 && (

{placeholder} @@ -1481,6 +1281,215 @@ export const ModelSelect = forwardRef(

)} + {selectedValues.length > 0 && + (initialLoading ? ( + + ) : ( +
+
+ {selectedValues + .slice( + 0, + responsiveSettings.maxCount, + ) + .map((value) => { + const option = + getOptionByValue(value); + if (!option) { + return null; + } + const badgeStyle: CSSProperties = + { + animationDuration: `${animation}s`, + }; + return multiple ? ( + svg]:pointer-events-auto", + )} + style={{ + ...badgeStyle, + animationDuration: `${ + animationConfig?.duration || + animation + }s`, + animationDelay: `${animationConfig?.delay || 0}s`, + }} + > + + {getModelField( + option, + )} + +
{ + event.stopPropagation(); + toggleOption( + option, + ); + }} + onKeyDown={( + event, + ) => { + if ( + event.key === + "Enter" || + event.key === + " " + ) { + event.preventDefault(); + event.stopPropagation(); + toggleOption( + option, + ); + } + }} + aria-label={`Remove ${option[dynamicField as keyof DefaultModel]} from selection`} + className="ml-2 h-4 w-4 cursor-pointer hover:bg-white/20 rounded-sm -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50" + > + +
+
+ ) : ( +

+ + {getModelField( + option, + )} + +

+ ); + }) + .filter(Boolean)} + {selectedValues.length > + responsiveSettings.maxCount && ( + svg]:pointer-events-auto", + )} + style={{ + animationDuration: `${animationConfig?.duration || animation}s`, + animationDelay: `${animationConfig?.delay || 0}s`, + }} + > + {`+ ${ + selectedValues.length - + responsiveSettings.maxCount + } ${transMore}`} + { + event.stopPropagation(); + clearExtraOptions(); + }} + /> + + )} +
+
+ {!required && ( + + )} + +
+
+ ))} ( content={ <> - {useTrans( + {GetTranslation( "pagination.previous", )} } tooltipContent={

- {useTrans( + {GetTranslation( "pagination.specific_page", { params: { @@ -1700,13 +1709,15 @@ export const ModelSelect = forwardRef( - {useTrans("pagination.next")} + {GetTranslation( + "pagination.next", + )} } tooltipContent={

- {useTrans( + {GetTranslation( "pagination.specific_page", { params: { diff --git a/resources/ts/back/Components/Inputs/MultiSelect.tsx b/resources/ts/back/Components/Inputs/MultiSelect.tsx index 64d805bc..64636e32 100644 --- a/resources/ts/back/Components/Inputs/MultiSelect.tsx +++ b/resources/ts/back/Components/Inputs/MultiSelect.tsx @@ -142,6 +142,7 @@ interface MultiSelectProps * Callback function triggered when the selected values change. * Receives an array of the new selected values. */ + // eslint-disable-next-line no-unused-vars onValueChange?: (value: string[]) => void; /** The default selected values when the component mounts. */ @@ -182,6 +183,7 @@ interface MultiSelectProps * If true, renders the multi-select component as a child of another component. * Optional, defaults to false. */ + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars asChild?: boolean; /** @@ -315,6 +317,7 @@ interface MultiSelectProps /** * The fonction to set the data in useForm inertia */ + // eslint-disable-next-line no-unused-vars setData: (name: string, value: string[]) => void; /** @@ -362,6 +365,7 @@ export interface MultiSelectRef { /** * Set selected values programmatically */ + // eslint-disable-next-line no-unused-vars setSelectedValues: (values: string[]) => void; /** * Clear all selected values @@ -393,6 +397,7 @@ export const MultiSelect = forwardRef( animationConfig, maxCount = 3, modalPopover = false, + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars asChild = false, className, hideSelectAll = false, @@ -482,6 +487,7 @@ export const MultiSelect = forwardRef( onValueChange(defaultValue); } setData(name, defaultValue); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [defaultValue, onValueChange]); const buttonRef = useRef(null); @@ -525,6 +531,7 @@ export const MultiSelect = forwardRef( } }, }), + // eslint-disable-next-line react-hooks/exhaustive-deps [resetToDefault, selectedValues, onValueChange], ); @@ -533,7 +540,7 @@ export const MultiSelect = forwardRef( >("desktop"); useEffect(() => { - if (typeof window === "undefined") return; + if (typeof window === "undefined") return undefined; const handleResize = () => { const width = window.innerWidth; if (width < 640) { @@ -556,7 +563,7 @@ export const MultiSelect = forwardRef( const getResponsiveSettings = () => { if (!responsive) { return { - maxCount: maxCount, + maxCount, hideIcons: false, compactMode: false, }; @@ -686,7 +693,7 @@ export const MultiSelect = forwardRef( const getOptionByValue = useCallback( (value: string): MultiSelectOption | undefined => { const option = getAllOptions().find( - (option) => option.value === value, + (opt) => opt.value === value, ); if (!option && process.env.NODE_ENV === "development") { console.warn( @@ -1053,6 +1060,7 @@ export const MultiSelect = forwardRef(

) : (
-

{placeholder}

+

+ {placeholder} +

)} @@ -1400,7 +1412,10 @@ export const MultiSelect = forwardRef( )} aria-hidden="true" > - +
( @@ -1466,7 +1481,10 @@ export const MultiSelect = forwardRef( )} aria-hidden="true" > - +
{option.icon && ( ( )} aria-hidden="true" > - + {option.icon && ( | null; + /* eslint-disable no-unused-vars */ setData: (name: string, value: string | null) => void; }; @@ -82,30 +83,41 @@ export default function SimpleColorPicker({ */ function isHex(val: string): boolean { return /^#([0-9A-Fa-f]{3,4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(val); - }; + } /** * Convert ColorResult → HEXA. * - * @param color ColorResult + * @param targetColor ColorResult * @return string */ - function toHEXA(color: ColorResult): string { - const r = color.rgb.r.toString(16).padStart(2, "0"); - const g = color.rgb.g.toString(16).padStart(2, "0"); - const b = color.rgb.b.toString(16).padStart(2, "0"); - const a = Math.round((color.rgb.a ?? 1) * 255).toString(16).padStart(2, "0") ?? "ff"; + function toHEXA(targetColor: ColorResult): string { + const r = targetColor.rgb.r.toString(16).padStart(2, "0"); + const g = targetColor.rgb.g.toString(16).padStart(2, "0"); + const b = targetColor.rgb.b.toString(16).padStart(2, "0"); + const a = + Math.round((targetColor.rgb.a ?? 1) * 255) + .toString(16) + .padStart(2, "0") ?? "ff"; return `#${r}${g}${b}${a}`; - }; + } /** - * Generate random HEXA color. - */ + * Generate random HEXA color. + */ function randomColor(): string { - const r = Math.floor(Math.random() * 256).toString(16).padStart(2, "0"); - const g = Math.floor(Math.random() * 256).toString(16).padStart(2, "0"); - const b = Math.floor(Math.random() * 256).toString(16).padStart(2, "0"); - const a = Math.floor(Math.random() * 256).toString(16).padStart(2, "0"); // alpha + const r = Math.floor(Math.random() * 256) + .toString(16) + .padStart(2, "0"); + const g = Math.floor(Math.random() * 256) + .toString(16) + .padStart(2, "0"); + const b = Math.floor(Math.random() * 256) + .toString(16) + .padStart(2, "0"); + const a = Math.floor(Math.random() * 256) + .toString(16) + .padStart(2, "0"); // alpha return `#${r}${g}${b}${a}`; } @@ -132,11 +144,11 @@ export default function SimpleColorPicker({ /** * Update color via picker. * - * @param color ColorResult + * @param targetColor ColorResult * @return void */ - function handleChangeComplete(color: ColorResult): void { - const hex = toHEXA(color); + function handleChangeComplete(targetColor: ColorResult): void { + const hex = toHEXA(targetColor); setColor(hex); setData(name, hex); } @@ -184,6 +196,7 @@ export default function SimpleColorPicker({ useEffect(() => { if (value !== color) setColor(value); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); return ( @@ -198,7 +211,7 @@ export default function SimpleColorPicker({ {/* Preview */} handleChange(newColor)} + onChangeComplete={(newCompleteColor) => + handleChangeComplete(newCompleteColor) + } disableAlpha={false} presetColors={presetColors} /> - {/* Force custom style */} - {/* Random Color */} @@ -326,7 +253,7 @@ export default function SimpleColorPicker({ type="button" variant="secondary" size="icon" - onClick={handleRandom} + onClick={() => handleRandom()} disabled={disabled} /> )} @@ -337,7 +264,7 @@ export default function SimpleColorPicker({ type="button" variant="secondary" size="icon" - onClick={handleReset} + onClick={() => handleReset()} disabled={disabled} /> {!required && ( @@ -347,7 +274,7 @@ export default function SimpleColorPicker({ type="button" variant="destructive" size="icon" - onClick={handleClear} + onClick={() => handleClear()} disabled={disabled} /> )} diff --git a/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx b/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx index d4c7e3c3..f18a6f0a 100644 --- a/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx +++ b/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx @@ -1,18 +1,23 @@ // * Other import { fr, enUS } from "date-fns/locale"; -import InputError from "@/back/Components/InputError"; import { usePage } from "@inertiajs/react"; -import { Calendar } from "@/components/ui/calendar"; -import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; -import { Button } from "@/components/ui/button"; import { CalendarIcon, RefreshCcw } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import useLocale from "@/store/use-locale-store"; -import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"; +// * Components shadcn +import { Calendar } from "@/components/ui/calendar"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Separator } from "@/components/ui/separator"; +import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"; +// * Other +import InputError from "@/back/Components/InputError"; +import { cn, GetFormatedDate } from "@/lib/utils"; import str from "@/hooks/use-string"; +import useLocale from "@/store/use-locale-store"; import useTrans from "@/hooks/use-translations"; type SimpleDatePickerProps = { @@ -24,10 +29,10 @@ type SimpleDatePickerProps = { className?: string; label: string; hasTime?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; // eslint-disable-next-line no-unused-vars setData: (name: string, value: Date | null) => void; -} +}; export default function SimpleDatePicker({ name, @@ -65,11 +70,11 @@ export default function SimpleDatePicker({ const resetDate = () => { setData(name, null); - } + }; function handleTimeChange(type: "hour" | "minute", value: string) { const currentDate = parsedDate || new Date(); - let newDate = new Date(currentDate); + const newDate = new Date(currentDate); if (type === "hour") { const hour = parseInt(value, 10); newDate.setHours(hour); @@ -86,12 +91,23 @@ export default function SimpleDatePicker({ - ))} + {hour} +

+ + ))}
- {minutes.map( - (minute) => ( - - ) - )} + {minute + .toString() + .padStart(2, "0")} +

+ + ))}
)} -
-
diff --git a/resources/ts/back/Components/Inputs/SimpleNumber.tsx b/resources/ts/back/Components/Inputs/SimpleNumber.tsx index 668591af..4f9cff35 100644 --- a/resources/ts/back/Components/Inputs/SimpleNumber.tsx +++ b/resources/ts/back/Components/Inputs/SimpleNumber.tsx @@ -20,7 +20,7 @@ type SimpleNumberProps = { placeholder?: string; required?: boolean; disabled?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; // eslint-disable-next-line no-unused-vars setData: (name: string, value: string) => void; }; @@ -44,15 +44,19 @@ export default function SimpleNumber({ const localLimits = { min: limits?.min ? limits.min : 1, - max: limits?.max ? limits.max : 1000 - } - const safeValue = value >= localLimits.min && value <= localLimits.max ? value : localLimits.min; + max: limits?.max ? limits.max : 1000, + }; + const safeValue = + value >= localLimits.min && value <= localLimits.max + ? value + : localLimits.min; const [inputValue, setInputValue] = useState(safeValue); useEffect(() => { setInputValue(safeValue); setData(name, String(safeValue)); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [safeValue]); return ( diff --git a/resources/ts/back/Components/Inputs/SimpleString.tsx b/resources/ts/back/Components/Inputs/SimpleString.tsx index f32747f1..e8d39b3a 100644 --- a/resources/ts/back/Components/Inputs/SimpleString.tsx +++ b/resources/ts/back/Components/Inputs/SimpleString.tsx @@ -26,7 +26,7 @@ type SimpleStringProps = { /** Pattern is regex without antislash */ pattern?: string; checkVisibility?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; // eslint-disable-next-line no-unused-vars setData: (name: string, value: string) => void; }; diff --git a/resources/ts/back/Components/Inputs/SimpleSwitch.tsx b/resources/ts/back/Components/Inputs/SimpleSwitch.tsx index e5bc012d..444f8dce 100644 --- a/resources/ts/back/Components/Inputs/SimpleSwitch.tsx +++ b/resources/ts/back/Components/Inputs/SimpleSwitch.tsx @@ -2,10 +2,10 @@ import { usePage } from "@inertiajs/react"; // * Components shadcn import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; // * Other import InputError from "@/back/Components/InputError"; import { cn } from "@/lib/utils"; -import { Label } from "@/components/ui/label"; type SimpleSwitchProps = { name: string; @@ -16,7 +16,7 @@ type SimpleSwitchProps = { className?: string; required?: boolean; disabled?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; // eslint-disable-next-line no-unused-vars setData: (name: string, value: boolean) => void; }; @@ -38,11 +38,11 @@ export default function SimpleSwitch({ return (
- {label && ()} + {label && ( + + )}
- {leftHelper && ( - {leftHelper} - )} + {leftHelper && {leftHelper}} - {rightHelper && ( - {rightHelper} - )} + {rightHelper && {rightHelper}}
diff --git a/resources/ts/back/Components/Inputs/SimpleTextarea.tsx b/resources/ts/back/Components/Inputs/SimpleTextarea.tsx index 9caf8d81..aeb4a581 100644 --- a/resources/ts/back/Components/Inputs/SimpleTextarea.tsx +++ b/resources/ts/back/Components/Inputs/SimpleTextarea.tsx @@ -19,7 +19,7 @@ type SimpleTextareaProps = { wordCounter?: boolean; required?: boolean; disabled?: boolean; - parentErrors?: Record | null, + parentErrors?: Record | null; // eslint-disable-next-line no-unused-vars setData: (name: string, value: string) => void; }; @@ -60,7 +60,9 @@ export default function SimpleTextarea({ }} required={required} disabled={disabled} - className={cn("w-full", { "border-destructive/50": localErrors[name] })} + className={cn("w-full", { + "border-destructive/50": localErrors[name], + })} /> diff --git a/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx b/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx index a45721ce..2c1c9292 100644 --- a/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx +++ b/resources/ts/back/Components/Inputs/SimpleVimeoId.tsx @@ -1,5 +1,6 @@ +// * Other +import SimpleString from "@/back/Components/Inputs/SimpleString"; import str from "@/hooks/use-string"; -import SimpleString from "./SimpleString"; import useTrans from "@/hooks/use-translations"; type SimpleVimeoIdProps = { @@ -9,17 +10,16 @@ type SimpleVimeoIdProps = { id?: string; required?: boolean; disabled?: boolean; - parentErrors?: Record | null, + 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}; + const label = str(useTrans("validation.custom.vimeo_id")).ucFirst().value(); + const localProps = { pattern, label, ...props }; - return ( - - ); + // eslint-disable-next-line react/jsx-props-no-spreading + return ; } diff --git a/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx b/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx index ccb53375..1da0fbd5 100644 --- a/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx +++ b/resources/ts/back/Components/Inputs/SimpleYoutubeId.tsx @@ -1,5 +1,6 @@ +// * Other +import SimpleString from "@/back/Components/Inputs/SimpleString"; import str from "@/hooks/use-string"; -import SimpleString from "./SimpleString"; import useTrans from "@/hooks/use-translations"; type SimpleYoutubeIdProps = { @@ -9,17 +10,18 @@ type SimpleYoutubeIdProps = { id?: string; required?: boolean; disabled?: boolean; - parentErrors?: Record | null, + 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}; + const label = str(useTrans("validation.custom.youtube_id")) + .ucFirst() + .value(); + const localProps = { pattern, label, ...props }; - return ( - - ); + // eslint-disable-next-line react/jsx-props-no-spreading + return ; } diff --git a/resources/ts/back/Components/Inputs/Slugifycator.tsx b/resources/ts/back/Components/Inputs/Slugifycator.tsx index a3da8362..34f7abca 100644 --- a/resources/ts/back/Components/Inputs/Slugifycator.tsx +++ b/resources/ts/back/Components/Inputs/Slugifycator.tsx @@ -1,18 +1,28 @@ -import str from "@/hooks/use-string" -import SimpleString from "./SimpleString" -import useTrans from "@/hooks/use-translations" -import BtnOptionnalLinkWithTooltip from "../BtnOptionnalLinkWithTooltip" -import { GavelIcon } from "lucide-react" +// * Packages +import { GavelIcon } from "lucide-react"; +// * Other +import SimpleString from "@/back/Components/Inputs/SimpleString"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import str from "@/hooks/use-string"; +import useTrans from "@/hooks/use-translations"; -interface Props { - setData: (name: string, value: string) => void; - value: string - targetValue: string +interface SlugifycatorProps { + value: string; + targetValue: string; wordCounter?: boolean; - disabled?: boolean, + disabled?: boolean; + // eslint-disable-next-line no-unused-vars + setData: (name: string, value: string) => void; } -const Slugifycator = (props: Props) => { - const {value, targetValue, setData, wordCounter = false, disabled = false} = props; + +export default function Slugifycator(props: SlugifycatorProps) { + const { + value, + targetValue, + setData, + wordCounter = false, + disabled = false, + } = props; return (
{ }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" wordCounter={wordCounter} value={value} @@ -33,14 +45,12 @@ const Slugifycator = (props: Props) => { /> } - tooltipContent={str(useTrans('back.slugify')).ucFirst().value()} + tooltipContent={str(useTrans("back.slugify")).ucFirst().value()} type="button" variant="secondary" onClick={() => setData("slug", str(targetValue).slug().value())} disabled={disabled} />
- ) + ); } - -export default Slugifycator; diff --git a/resources/ts/back/Components/Inputs/StaticRouteSelect.tsx b/resources/ts/back/Components/Inputs/StaticRouteSelect.tsx index 7ede8720..7c9589f6 100644 --- a/resources/ts/back/Components/Inputs/StaticRouteSelect.tsx +++ b/resources/ts/back/Components/Inputs/StaticRouteSelect.tsx @@ -1,5 +1,7 @@ +// * Packages import { usePage } from "@inertiajs/react"; -import EnumSelect from "./EnumSelect"; +// * Other +import EnumSelect from "@/back/Components/Inputs/EnumSelect"; import { LaravelEnum } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -9,26 +11,34 @@ interface Props { selected: number; required: boolean; label: string; + // eslint-disable-next-line no-unused-vars setData: (name: string, value: number | null) => void; } -const StaticRouteSelect = (props: Props) => { +export default function StaticRouteSelect(props: Props) { const { name, selected, required, label, setData } = props; - const contactFormRoutes = usePage().props.contactFormRoutes as LaravelEnum|null; - if (!contactFormRoutes) return str(useTrans('back.static_route.no_route_defined')).ucFirst().value(); + const enumStaticRoutes = usePage().props + .enumStaticRoutes as LaravelEnum | null; + + const transSelectValue = str(useTrans("back.static_route.select_value")) + .ucFirst() + .value(); + const transNoRoutes = str(useTrans("back.static_route.no_route_defined")) + .ucFirst() + .value(); + + if (!enumStaticRoutes) return transNoRoutes; return ( - ) + ); } - -export default StaticRouteSelect; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/Image.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/Image.tsx index f81a4b1b..9f62b493 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/Image.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/Image.tsx @@ -8,7 +8,7 @@ import ImageNodeView, { } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView"; import { imageDetails } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; -export const Image = TiptapImage.extend({ +const Image = TiptapImage.extend({ // Define attributes we need. addAttributes() { return { @@ -30,7 +30,9 @@ export const Image = TiptapImage.extend({ // Specific selector for a figure with his image and an optional figcaption. tag: "figure:has(img[src])", getAttrs: (element: HTMLElement) => { - const img = element.querySelector("img") as HTMLImageElement; + const img = element.querySelector( + "img", + ) as HTMLImageElement; const figcaption = element.querySelector("figcaption"); return { @@ -38,9 +40,11 @@ export const Image = TiptapImage.extend({ alt: img.getAttribute("alt"), width: parseInt( img.getAttribute("width") || imageDetails.width, + 10, ), height: parseInt( img.getAttribute("height") || imageDetails.height, + 10, ), style: null, caption: figcaption?.textContent, @@ -56,11 +60,13 @@ export const Image = TiptapImage.extend({ // Define the structure of the render. // Use for render html in front files. renderHTML({ node, HTMLAttributes }) { - delete HTMLAttributes.caption; - delete HTMLAttributes.float; + const attrsCopy = { ...HTMLAttributes }; + + delete attrsCopy.caption; + delete attrsCopy.float; const style = [ - HTMLAttributes.style ?? "margin: 0px;", + attrsCopy.style ?? "margin: 0px;", node.attrs.float ? FLOAT_STYLES[node.attrs.float as FloatOption] : null, @@ -68,12 +74,14 @@ export const Image = TiptapImage.extend({ .filter(Boolean) .join(" "); - delete HTMLAttributes.style; + delete attrsCopy.style; return [ "figure", { style }, - ["img", HTMLAttributes], + ["img", attrsCopy], ...(node.attrs.caption ? [["figcaption", node.attrs.caption]] : []), ]; }, }); + +export default Image; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton.tsx index 10ca781b..81e21280 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton.tsx @@ -19,12 +19,15 @@ import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; // * Other import ImageInputs from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs"; -import { imageTextSchema } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; -import { imageDetails } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; +import { + imageTextSchema, + imageDetails, +} from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; +import { GetTranslation } from "@/lib/utils"; type ImageProps = { /** Wysiwyg editor instance. */ @@ -79,13 +82,15 @@ export default function ImageButton({ editor, disabled }: ImageProps) { const transCaption = useTrans("back.wysiwyg.image.caption"); const transValidation = (attribute: string) => { return { - min: useTrans("validation.min.string", { + min: GetTranslation("validation.min.string", { params: { attribute, min: "3" }, }), - max: useTrans("validation.max.string", { + max: GetTranslation("validation.max.string", { params: { attribute, max: "255" }, }), - string: useTrans("validation.string", { params: { attribute } }), + string: GetTranslation("validation.string", { + params: { attribute }, + }), }; }; const transValidationAlt = transValidation(transAlt); @@ -140,18 +145,85 @@ export default function ImageButton({ editor, disabled }: ImageProps) { ) .refine( (file) => - file.size <= parseInt(imageDetails.size) * 1024 * 1024, + file.size <= parseInt(imageDetails.size, 10) * 1024 * 1024, { message: useTrans("validation.size.file", { params: { attribute: transImage, - size: imageDetails.size + " 000", + size: `${imageDetails.size} 000`, }, }), }, ), }); + /** + * Set new errors from object errors + * + * @param err unknown + * @return void + */ + const setNewErrors = (err: unknown): void => { + const fieldErrors: typeof errors = {}; + const fieldMapping: Record = { + upload: "image", + inputFile: "image", + alt: "alt", + caption: "caption", + }; + // Manage zod errors. + if (err instanceof z.ZodError) { + err.issues.forEach((error) => { + const key = error.path[0] as string | undefined; + const mappedKey = + (key && fieldMapping[key]) ?? + (error.path.length === 0 ? "form" : undefined); + if (mappedKey) fieldErrors[mappedKey] = error.message; + }); + + setErrors(fieldErrors); + return; + } + // Manage laravel errors. + if (err && typeof err === "object" && "response" in err) { + const currentErrors = err as { + response: { + data: { + errors: Record; + }; + }; + }; + + Object.entries(currentErrors.response.data.errors).forEach( + ([laravelField, [firstMessage]]) => { + const componentField = fieldMapping[laravelField]; + if (componentField && firstMessage) { + fieldErrors[componentField] = firstMessage; + } + }, + ); + + setErrors(fieldErrors); + } + }; + + /** + * Reset all states and values in the component. + * + * @return void + */ + const resetComponent = () => { + setFile(null); + setInputText({ + alt: "", + caption: null, + hasCaption: false, + }); + setInputType(ImageTypes[0]); + setErrors({}); + setLoading(false); + }; + /** * Upload image in storage. * @@ -237,74 +309,6 @@ export default function ImageButton({ editor, disabled }: ImageProps) { } }; - /** - * Set new errors from object errors - * - * @param err unknown - * @return void - */ - const setNewErrors = (err: unknown): void => { - const fieldErrors: typeof errors = {}; - const fieldMapping: Record = { - upload: "image", - inputFile: "image", - alt: "alt", - caption: "caption", - }; - // Manage zod errors. - if (err instanceof z.ZodError) { - err.issues.forEach((error) => { - const key = error.path[0] as string | undefined; - const mappedKey = - (key && fieldMapping[key]) ?? - (error.path.length === 0 ? "form" : undefined); - if (mappedKey) fieldErrors[mappedKey] = error.message; - }); - - setErrors(fieldErrors); - return; - } - // Manage laravel errors. - if (err && typeof err === "object" && "response" in err) { - let currentErrors = err as { - response: { - data: { - errors: Record; - }; - }; - }; - - Object.entries(currentErrors.response.data.errors).forEach( - ([laravelField, messages]) => { - const componentField = fieldMapping[laravelField]; - if (componentField && messages.length > 0) { - fieldErrors[componentField] = messages[0]; - } - }, - ); - - setErrors(fieldErrors); - return; - } - }; - - /** - * Reset all states and values in the component. - * - * @return void - */ - const resetComponent = () => { - setFile(null); - setInputText({ - alt: "", - caption: null, - hasCaption: false, - }); - setInputType(ImageTypes[0]) - setErrors({}); - setLoading(false); - }; - /** * Update url value from string input. * @@ -335,6 +339,7 @@ export default function ImageButton({ editor, disabled }: ImageProps) { caption: inputText.hasCaption ? inputText.caption : null, hasCaption: inputText.hasCaption, }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [inputText.hasCaption]); return ( @@ -396,7 +401,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {

- {useTrans(`back.wysiwyg.image.${type.name}`)} + {GetTranslation( + `back.wysiwyg.image.${type.name}`, + )}

))} @@ -410,9 +417,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) { .ucFirst() .value()} setData={handleSetImage} - reset={(name) => console.log("reset", name)} + reset={() => {}} value={null} - required={true} + required maxFileSize="5120" allowedFormats="jpg,jpeg,png,webp" validationRules={{ diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs.tsx index d79d0d17..53214bce 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs.tsx @@ -6,10 +6,11 @@ import str from "@/hooks/use-string"; type ImageInputsProps = { value: { - alt: string; - caption: string | null; - hasCaption: boolean; + alt: string; + caption: string | null; + hasCaption: boolean; }; + // eslint-disable-next-line no-unused-vars onChange: (value: ImageInputsProps["value"]) => void; errors?: Record; loading?: boolean; @@ -22,7 +23,9 @@ export default function ImageInputs({ errors = {}, loading = false, disabled = false, - }: ImageInputsProps) { +}: ImageInputsProps) { + const transImageCaption = useTrans("back.wysiwyg.image.caption"); + return ( <> {/* Input alt attribute of the image. */} @@ -32,18 +35,18 @@ export default function ImageInputs({ .ucFirst() .value()} placeholder="ex: John Doe" - required={true} + required value={value.alt} - setData={(_, v) => - onChange({ ...value, alt: v }) - } + setData={(_, v) => onChange({ ...value, alt: v })} disabled={disabled || loading} parentErrors={errors} />
{/* Input switch to set the caption visibility. */} - onChange({ ...value, caption: v }) - } + setData={(_, v) => onChange({ ...value, caption: v })} disabled={disabled || loading} parentErrors={errors} /> diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView.tsx index ecdb27ad..215cd350 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView.tsx @@ -11,6 +11,7 @@ import { ChevronsLeftRightEllipsisIcon, } from "lucide-react"; import { useEffect, useRef, useState } from "react"; +import type { MouseEvent as ReactMouseEvent } from "react"; import z from "zod"; // * Components shadcn import { Button } from "@/components/ui/button"; @@ -30,24 +31,16 @@ import { } from "@/components/ui/select"; // * Other import ImageInputs from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs"; -import { imageDetails } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; -import { imageTextSchema } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; +import { + imageDetails, + imageTextSchema, +} from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import { cn } from "@/lib/utils"; +import { cn, GetTranslation } from "@/lib/utils"; import { parseStyleString } from "@/hooks/use-inline-style"; -type ImageAttrs = { - src: string; - alt: string; - width: number; - height: number; - caption: string | null; - style: string; - float: FloatOption; -}; - export type AllowedAligns = "left" | "center" | "right"; export type FloatOption = "left" | "right"; @@ -86,6 +79,16 @@ const PLACEMENT_STYLES: Record = { "float-right": FLOAT_STYLES.right, }; +type ImageAttrs = { + src: string; + alt: string; + width: number; + height: number; + caption: string | null; + style: string; + float: FloatOption; +}; + export default function ImageNodeView(props: NodeViewProps) { const { node, updateAttributes, editor, selected } = props; const attrs = node.attrs as ImageAttrs; @@ -112,7 +115,7 @@ export default function ImageNodeView(props: NodeViewProps) { }>({ alt: attrs.alt, caption: attrs.caption, - hasCaption: Boolean(attrs.caption) ? true : false, + hasCaption: !!attrs.caption, }); // Value of the height of header + @tiptap toolbar editor. const [topSticky, setTopSticky] = useState(0); @@ -122,13 +125,15 @@ export default function ImageNodeView(props: NodeViewProps) { const transCaption = useTrans("back.wysiwyg.image.caption"); const transValidation = (attribute: string) => { return { - min: useTrans("validation.min.string", { + min: GetTranslation("validation.min.string", { params: { attribute, min: "3" }, }), - max: useTrans("validation.max.string", { + max: GetTranslation("validation.max.string", { params: { attribute, max: "255" }, }), - string: useTrans("validation.string", { params: { attribute } }), + string: GetTranslation("validation.string", { + params: { attribute }, + }), }; }; const transValidationAlt = transValidation(transAlt); @@ -182,7 +187,7 @@ export default function ImageNodeView(props: NodeViewProps) { * @param event MouseEvent * @returns */ - const onMouseDown = (event: React.MouseEvent) => { + const onMouseDown = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); @@ -243,6 +248,31 @@ export default function ImageNodeView(props: NodeViewProps) { resizeState.current = null; }; + /** + * Set new errors from object errors + * + * @param err unknown + * @return void + */ + const setNewErrors = (err: unknown): void => { + const fieldErrors: typeof errors = {}; + const fieldMapping: Record = { + alt: "alt", + caption: "caption", + }; + if (err instanceof z.ZodError) { + err.issues.forEach((error) => { + const key = error.path[0] as string | undefined; + const mappedKey = + (key && fieldMapping[key]) ?? + (error.path.length === 0 ? "form" : undefined); + if (mappedKey) fieldErrors[mappedKey] = error.message; + }); + + setErrors(fieldErrors); + } + }; + /** * Update image attributes. * @@ -272,31 +302,6 @@ export default function ImageNodeView(props: NodeViewProps) { setNewErrors(error); } }; - /** - * Set new errors from object errors - * - * @param err unknown - * @return void - */ - const setNewErrors = (err: unknown): void => { - const fieldErrors: typeof errors = {}; - const fieldMapping: Record = { - alt: "alt", - caption: "caption", - }; - if (err instanceof z.ZodError) { - err.issues.forEach((error) => { - const key = error.path[0] as string | undefined; - const mappedKey = - (key && fieldMapping[key]) ?? - (error.path.length === 0 ? "form" : undefined); - if (mappedKey) fieldErrors[mappedKey] = error.message; - }); - - setErrors(fieldErrors); - return; - } - }; /** * Close modal and reset component. @@ -338,7 +343,7 @@ export default function ImageNodeView(props: NodeViewProps) { // Update the focus on @tiptap editor. useEffect(() => { - if (!editor) return; + if (!editor) return undefined; editor.on("focus", handleFocus); editor.on("blur", handleBlur); @@ -351,7 +356,7 @@ export default function ImageNodeView(props: NodeViewProps) { // Reset events when resizing. useEffect(() => { - if (!isResizing) return; + if (!isResizing) return undefined; window.addEventListener("mousemove", onMouseMove); window.addEventListener("mouseup", onMouseUp); @@ -360,6 +365,7 @@ export default function ImageNodeView(props: NodeViewProps) { window.removeEventListener("mousemove", onMouseMove); window.removeEventListener("mouseup", onMouseUp); }; + // eslint-disable-next-line react-hooks/exhaustive-deps }, [isResizing]); // Set default value to the caption. @@ -369,6 +375,7 @@ export default function ImageNodeView(props: NodeViewProps) { caption: inputText.hasCaption ? inputText.caption : null, hasCaption: inputText.hasCaption, }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [inputText.hasCaption]); // Set height of header + @tiptap toolbar editor with resize event. @@ -433,7 +440,7 @@ export default function ImageNodeView(props: NodeViewProps) { - {useTrans("back.wysiwyg.image.position")} + {GetTranslation("back.wysiwyg.image.position")} {PLACEMENT_OPTIONS.map((value) => { const [type, dir] = value.split("-") as [ @@ -462,7 +469,7 @@ export default function ImageNodeView(props: NodeViewProps) { {value === "float-right" && ( )} - {useTrans( + {GetTranslation( `back.wysiwyg.image.${str(label).slug().value()}`, )}
diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils.tsx index 0ca5f1cd..c2bcf26e 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils.tsx @@ -47,4 +47,4 @@ export const imageTextSchema = ({ alt: altRules, caption: hasCaption ? captionRules : z.null(), }); -}; \ No newline at end of file +}; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/image.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/image.d.ts index 70dc2e99..509eccbf 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/image.d.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Image/image.d.ts @@ -1,13 +1,15 @@ -import '@tiptap/core'; +// * Packages +import "@tiptap/core"; // Set custom function attributes. -declare module '@tiptap/core' { +declare module "@tiptap/core" { interface Commands { Image: { + // eslint-disable-next-line no-unused-vars setImage: (attrs: { - src: string, + src: string; alt: string; - caption: string|null; + caption: string | null; width: string; height: string; }) => ReturnType; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/Link.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/Link.tsx index 5a7028c2..5086235a 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/Link.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/Link.tsx @@ -1,90 +1,104 @@ // * Packages -import { Plugin, PluginKey } from 'prosemirror-state'; -import { mergeAttributes, getMarkRange, CommandProps } from "@tiptap/react"; -import type { LinkOptions as TiptapLinkOptions } from '@tiptap/extension-link'; -import { Link as TiptapLink } from '@tiptap/extension-link'; -import { TextSelection } from 'prosemirror-state'; - -export interface LinkOptions extends TiptapLinkOptions {} +import { Plugin, PluginKey, TextSelection } from "prosemirror-state"; +import { mergeAttributes, getMarkRange } from "@tiptap/react"; +import type { LinkOptions as TiptapLinkOptions } from "@tiptap/extension-link"; +import { Link as TiptapLink } from "@tiptap/extension-link"; export type LinkAttrs = { text: string; blank: boolean; modelToken: string | null; - }; +}; -export const Link = TiptapLink.extend({ +export const Link = TiptapLink.extend({ addCommands() { return { - setLink: attrs => ({ state, commands }) => { - const linkAttrs = attrs as LinkAttrs; - const { from, to } = state.selection; + setLink: + (attrs) => + ({ state, commands }) => { + const linkAttrs = attrs as LinkAttrs; + const { from, to } = state.selection; - // Check if there is a selected link. - let linkFound = false; - state.doc.nodesBetween(from, to, node => { - if (node.marks) { - const found = node.marks.find(m => m.type.name === this.name); - if (found) linkFound = true; - } - }); - - if (linkFound) { - return commands.command(({ tr, state, dispatch }) => { - // Get the existing mark. - let existingMark = null; - state.doc.nodesBetween(from, to, node => { - if (node.marks) { - const found = node.marks.find(m => m.type.name === this.name); - if (found) existingMark = found; - } - }); - - if (!existingMark) return false; - - // Remove the existing text. - tr.delete(from, to); - - // Insert the new text. - tr.insertText(linkAttrs.text, from); - - // Set the mark with new attributes. - tr.addMark( - from, - from + linkAttrs.text.length, - state.schema.marks[this.name].create(linkAttrs) - ); - - // Apply the modification. - if (dispatch) dispatch(tr); - - return true; + // Check if there is a selected link. + let linkFound = false; + state.doc.nodesBetween(from, to, (node) => { + if (node.marks) { + const found = node.marks.find( + (m) => m.type.name === this.name, + ); + if (found) linkFound = true; + } }); - } - // Otherwise, create a new link like before. - return commands.insertContent({ - type: "text", - text: linkAttrs.text, - marks: [{ type: this.name, attrs: linkAttrs }], - }); - }, - unsetLink: () => ({ state, dispatch, tr, commands }) => { - const { $from } = state.selection; - const markType = state.schema.marks[this.name]; - - // Check there is a link mark. - const markRange = getMarkRange($from, markType); - if (!markRange) return false; - - // Remove the mark from the selection. - if (dispatch) { - tr.removeMark(markRange.from, markRange.to, markType); - dispatch(tr); - } - - return true; - }, + if (linkFound) { + return commands.command( + ({ tr, state: editorState, dispatch }) => { + // Get the existing mark. + let existingMark = null; + editorState.doc.nodesBetween( + from, + to, + (node) => { + if (node.marks) { + const found = node.marks.find( + (m) => + m.type.name === this.name, + ); + if (found) existingMark = found; + } + }, + ); + + if (!existingMark) return false; + + // Remove the existing text. + tr.delete(from, to); + + // Insert the new text. + tr.insertText(linkAttrs.text, from); + + // Set the mark with new attributes. + tr.addMark( + from, + from + linkAttrs.text.length, + state.schema.marks[this.name].create( + linkAttrs, + ), + ); + + // Apply the modification. + if (dispatch) dispatch(tr); + + return true; + }, + ); + } + + // Otherwise, create a new link like before. + return commands.insertContent({ + type: "text", + text: linkAttrs.text, + marks: [{ type: this.name, attrs: linkAttrs }], + }); + }, + unsetLink: + () => + ({ state, dispatch, tr }) => { + const { $from } = state.selection; + const markType = state.schema.marks[this.name]; + + // Check there is a link mark. + const markRange = getMarkRange($from, markType); + if (!markRange) return false; + + // Remove the mark from the selection. + if (dispatch) { + tr.removeMark(markRange.from, markRange.to, markType); + dispatch(tr); + } + + return true; + }, }; }, addAttributes() { @@ -94,70 +108,90 @@ export const Link = TiptapLink.extend({ }, blank: { default: false, - parseHTML: element => element.getAttribute('target') === '_blank', - renderHTML: attrs => attrs.blank ? { target: '_blank', rel: 'noopener noreferrer' } : {}, + parseHTML: (element) => + element.getAttribute("target") === "_blank", + renderHTML: (attrs) => + attrs.blank + ? { target: "_blank", rel: "noopener noreferrer" } + : {}, }, modelToken: { default: null, - parseHTML: el => el.getAttribute('data-model') ?? null, - renderHTML: attrs => attrs.modelToken ? {'data-model': attrs.modelToken } : {}, + parseHTML: (el) => el.getAttribute("data-model") ?? null, + renderHTML: (attrs) => + attrs.modelToken ? { "data-model": attrs.modelToken } : {}, }, }; }, parseHTML() { return [ { - tag: 'a[href]', - getAttrs: el => { - if (el.getAttribute('data-type') === 'button') return false; - if (/(javascript:)/i.test(el.getAttribute('href') ?? '')) return false; + tag: "a[href]", + getAttrs: (el) => { + if (el.getAttribute("data-type") === "button") return false; + if (/(javascript:)/i.test(el.getAttribute("href") ?? "")) + return false; return {}; }, }, ]; }, renderHTML({ HTMLAttributes }) { - return ['a', mergeAttributes({ - 'data-model': HTMLAttributes.modelToken, - }, HTMLAttributes), 0]; + return [ + "a", + mergeAttributes( + { + "data-model": HTMLAttributes.modelToken, + }, + HTMLAttributes, + ), + 0, + ]; }, addProseMirrorPlugins() { return [ new Plugin({ - key: new PluginKey(this.name + "-open-editor"), + key: new PluginKey(`${this.name}-open-editor`), props: { handleClick: (view, pos, event) => { const target = event.target as HTMLElement | null; if (!target) return false; - + const link = target.closest("a"); if (!link) return false; - + // Find the exact position of the gat . const { state } = view; const $pos = state.doc.resolve(pos); - + // Extend the selection to the entire mark. - const markRange = getMarkRange($pos, state.schema.marks.Link); + const markRange = getMarkRange( + $pos, + state.schema.marks.Link, + ); if (markRange) { view.dispatch( state.tr.setSelection( - TextSelection.create(state.doc, markRange.from, markRange.to) - ) + TextSelection.create( + state.doc, + markRange.from, + markRange.to, + ), + ), ); } - + // Open the modale. this.editor.emit("open-link-editor", { href: link.getAttribute("href") ?? "", blank: link.getAttribute("target") === "_blank", text: link.textContent ?? "", - modelToken: link.getAttribute('data-model') ?? null, + modelToken: link.getAttribute("data-model") ?? null, }); - + event.preventDefault(); return true; - } + }, }, }), ]; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton.tsx index 3bd092c0..483710ad 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton.tsx @@ -1,6 +1,6 @@ // * Packages import { useEffect, useState } from "react"; -import axios from "axios"; +import axios, { isAxiosError } from "axios"; import { route } from "ziggy-js"; import { ExternalLinkIcon, LinkIcon, TrashIcon } from "lucide-react"; import { Editor } from "@tiptap/react"; @@ -14,6 +14,7 @@ import { DialogHeader, DialogTitle, DialogTrigger, + DialogFooter, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; // * Other @@ -22,16 +23,18 @@ import EnumSelect from "@/back/Components/Inputs/EnumSelect"; import SimpleString from "@/back/Components/Inputs/SimpleString"; import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch"; import GoToFrontView from "@/back/Components/GoToFrontView"; +import { ModelSelect } from "@/back/Components/Inputs/ModelSelect"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; import { AppEnv, LaravelEnum } from "@/back/types/global"; -import { cn } from "@/lib/utils"; -import { ModelSelect } from "../../../ModelSelect"; +import { cn, GetTranslation } from "@/lib/utils"; // Custom type with field entry. type AddFieldToRecord> = { [K in keyof T]: { - [P in keyof T[K] | 'field']: P extends 'field' ? string : T[K][P & keyof T[K]]; + [P in keyof T[K] | "field"]: P extends "field" + ? string + : T[K][P & keyof T[K]]; }; }; @@ -55,24 +58,27 @@ type RetrieveFromTokenResponse = { }; // All link types. -enum LinkType { - external = 1, - internal = 2, -} +const LinkType = { + external: 1, + internal: 2, +} as const; + +type LinkTypeValue = (typeof LinkType)[keyof typeof LinkType]; // Component props. type LinkProps = { /** Wysiwyg editor instance. */ - editor: Editor, + editor: Editor; /** Disable trigger button. */ disabled: boolean; -} +}; -export default function LinkButton({ editor, disabled } : LinkProps) { +export default function LinkButton({ editor, disabled }: LinkProps) { // Current domain of the projet. const { url } = usePage().props.appEnv as AppEnv; // All models from global enum. - const enumModelsList = usePage().props.enumModelsList as LaravelEnumWithField; + const enumModelsList = usePage().props + .enumModelsList as LaravelEnumWithField; // State of the plugin modal. const [open, setOpen] = useState(false); @@ -84,13 +90,19 @@ export default function LinkButton({ editor, disabled } : LinkProps) { const [modelToken, setModelToken] = useState(null); // Type of selected link. - const [selectedType, setSelectedType] = useState(LinkType.external); + const [selectedType, setSelectedType] = useState( + LinkType.external, + ); // Value of the selected enum. - const [selectedEnumValue, setSelectedEnumValue] = useState(null); + const [selectedEnumValue, setSelectedEnumValue] = useState( + null, + ); // Id of the selected model. const [selectedModelId, setSelectedModelId] = useState(null); /** Url to access the selected model. */ - const [selectedEntryUrl, setSelectedEntryUrl] = useState(null); + const [selectedEntryUrl, setSelectedEntryUrl] = useState( + null, + ); // Value of the input url link. const [inputUrl, setInputUrl] = useState(""); @@ -105,55 +117,69 @@ export default function LinkButton({ editor, disabled } : LinkProps) { const [errors, setErrors] = useState>({}); // Enum selected from specific value. - const selectedEnum = Object.values(enumModelsList ?? []).find((def) => def.value === selectedEnumValue); + const selectedEnum = Object.values(enumModelsList ?? []).find( + (def) => def.value === selectedEnumValue, + ); // Duration of modal closing animation. const animationTime = 200; // Utility for generating validation messages. - const createMinRule = (attribute: string, min: number) => useTrans('validation.min.string', { params: { attribute, min: min.toString() } }); - const createMaxRule = (attribute: string, max: number) => useTrans('validation.max.string', { params: { attribute, max: max.toString() } }); + const createMinRule = (attribute: string, min: number) => + GetTranslation("validation.min.string", { + params: { attribute, min: min.toString() }, + }); + const createMaxRule = (attribute: string, max: number) => + GetTranslation("validation.max.string", { + params: { attribute, max: max.toString() }, + }); // Translations. - const textAttribute = useTrans('back.wysiwyg.link.text'); - const urlAttribute = useTrans('back.wysiwyg.link.url'); - const transTooltip = str(useTrans("back.wysiwyg.link.tooltip")).ucFirst().value(); - + const textAttribute = useTrans("back.wysiwyg.link.text"); + const urlAttribute = useTrans("back.wysiwyg.link.url"); + const transTooltip = str(useTrans("back.wysiwyg.link.tooltip")) + .ucFirst() + .value(); + // Zod internal link schema. const internalLinkSchema = z.object({ - inputText: z.string().min(3, createMinRule(textAttribute, 3)).max(255, createMaxRule(textAttribute, 255)) + inputText: z + .string() + .min(3, createMinRule(textAttribute, 3)) + .max(255, createMaxRule(textAttribute, 255)), }); // Zod external link schema. const externalLinkSchema = z.object({ - inputText: z.string().min(3, createMinRule(textAttribute, 3)).max(255, createMaxRule(textAttribute, 255)), - inputUrl: z.string().min(3, createMinRule(urlAttribute, 3)).max(255, createMaxRule(urlAttribute, 255)) - // Assert it's not an internal url. - .refine((val) => { - try { - const parsed = new URL(val); - return parsed.hostname !== new URL(url).hostname; - } catch { - return false; - } - }, { - message: useTrans('back.wysiwyg.link.validation.use_internal') - }) - // Assert it's a valid url. - .refine((val) => { - try { - new URL(val); - return true; - } catch { - return false; - } - }, { - message: useTrans('back.wysiwyg.link.validation.url') - }) - // Assert there is domain and tld. - .refine((val) => /^(?:https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,}$/i.test(val), { - message: useTrans('back.wysiwyg.link.validation.url') - }), + inputText: z + .string() + .min(3, createMinRule(textAttribute, 3)) + .max(255, createMaxRule(textAttribute, 255)), + + inputUrl: z + .string() + .min(3, createMinRule(urlAttribute, 3)) + .max(255, createMaxRule(urlAttribute, 255)) + .pipe( + z.url({ + protocol: /^https?$/, + hostname: z.regexes.domain, + message: useTrans("back.wysiwyg.link.validation.url"), + }), + ) + .refine( + (val) => { + const parsedUrl = new URL(val); + const currentHostname = new URL(url).hostname; + + return parsedUrl.hostname !== currentHostname; + }, + { + message: useTrans( + "back.wysiwyg.link.validation.use_internal", + ), + }, + ), }); /** @@ -163,9 +189,15 @@ export default function LinkButton({ editor, disabled } : LinkProps) { * @param options object * @return */ - const fetchOptions = async (routeName: string, options: Object = {}): Promise => { + const fetchOptions = async ( + routeName: string, + options: object = {}, + ): Promise => { // Get the csrf token value. - const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; + const csrfToken = + document + .querySelector('meta[name="csrf-token"]') + ?.getAttribute("content") || ""; // Base ajax call. const response = await axios.post( @@ -179,11 +211,29 @@ export default function LinkButton({ editor, disabled } : LinkProps) { "X-Inertia": "false", "X-CSRF-TOKEN": csrfToken, }, - } + }, ); return response.data; }; + /** + * Reset all states and values in the component. + * + * @return void + */ + const resetComponent = () => { + setSelectedType(LinkType.external); + setSelectedEnumValue(null); + setSelectedModelId(null); + setSelectedEntryUrl(null); + setInputUrl(""); + setInputText(""); + setInputBlank(false); + setEditingLink(false); + setErrors({}); + setLoading(false); + }; + /** * Add new link. * @@ -194,7 +244,11 @@ export default function LinkButton({ editor, disabled } : LinkProps) { try { if (selectedType === LinkType.internal) { - const parsed = internalLinkSchema.parse({ inputText, selectedEnumValue, selectedModelId }); + const parsed = internalLinkSchema.parse({ + inputText, + selectedEnumValue, + selectedModelId, + }); editor.commands.setLink({ href: selectedEntryUrl ?? url, text: parsed.inputText, @@ -202,7 +256,10 @@ export default function LinkButton({ editor, disabled } : LinkProps) { modelToken: modelToken ?? null, }); } else if (selectedType === LinkType.external) { - const parsed = externalLinkSchema.parse({ inputText, inputUrl }); + const parsed = externalLinkSchema.parse({ + inputText, + inputUrl, + }); editor.commands.setLink({ href: parsed.inputUrl, text: parsed.inputText, @@ -245,25 +302,7 @@ export default function LinkButton({ editor, disabled } : LinkProps) { editor.commands.unsetLink(); setOpen(false); setTimeout(() => resetComponent(), animationTime); - } - - /** - * Reset all states and values in the component. - * - * @return void - */ - const resetComponent = () => { - setSelectedType(LinkType.external); - setSelectedEnumValue(null); - setSelectedModelId(null); - setSelectedEntryUrl(null); - setInputUrl(""); - setInputText(""); - setInputBlank(false); - setEditingLink(false); - setErrors({}); - setLoading(false); - } + }; /** * Update selected enum and update states. @@ -274,9 +313,9 @@ export default function LinkButton({ editor, disabled } : LinkProps) { const handleSelectEnum = (value: number | null): void => { setSelectedModelId(null); setSelectedEntryUrl(null); - setErrors(prev => ({ ...prev, 'modelName': '' })); + setErrors((prev) => ({ ...prev, modelName: "" })); setSelectedEnumValue(value); - } + }; /** * Update selected entry and update states. @@ -286,24 +325,28 @@ export default function LinkButton({ editor, disabled } : LinkProps) { */ const handleSelectEntry = async (value: number | null): Promise => { setLoading(true); - setErrors(prev => ({ ...prev, 'selectedEntry': '' })); + setErrors((prev) => ({ ...prev, selectedEntry: "" })); try { // Get the url to access a specific model. - const data = await fetchOptions("back.wysiwyg.model-access", { + const data = (await fetchOptions("back.wysiwyg.model-access", { selectedEntry: value, modelName: selectedEnum?.name, - }) as ModelAccessResponse; - console.log(data) + })) as ModelAccessResponse; setSelectedEntryUrl(data.url); setModelToken(data.token); - } catch (err: any) { + } catch (err: unknown) { console.error(err); - setErrors(prev => ({ ...prev, ...err.response?.data?.errors})) + if (isAxiosError(err) && err.response?.data?.errors) { + setErrors((prev) => ({ + ...prev, + ...err.response?.data.errors, + })); + } } finally { setSelectedModelId(value); setLoading(false); } - } + }; /** * Update url value from string input. @@ -311,9 +354,9 @@ export default function LinkButton({ editor, disabled } : LinkProps) { * @return void */ const handleUpdateUrl = (value: string): void => { - setErrors(prev => ({ ...prev, 'link-url': '' })); + setErrors((prev) => ({ ...prev, "link-url": "" })); setInputUrl(value); - } + }; /** * Update text value from string input. @@ -321,9 +364,9 @@ export default function LinkButton({ editor, disabled } : LinkProps) { * @return void */ const handleUpdateText = (value: string): void => { - setErrors(prev => ({ ...prev, 'link-text': '' })); + setErrors((prev) => ({ ...prev, "link-text": "" })); setInputText(value); - } + }; /** * Update blank value from switch input. @@ -331,9 +374,9 @@ export default function LinkButton({ editor, disabled } : LinkProps) { * @return void */ const handleUpdateBlank = (value: boolean): void => { - setErrors(prev => ({ ...prev, 'link-blank': '' })); + setErrors((prev) => ({ ...prev, "link-blank": "" })); setInputBlank(value); - } + }; /** * Close modal and reset component. @@ -343,7 +386,7 @@ export default function LinkButton({ editor, disabled } : LinkProps) { const handleCancelLink = (): void => { setOpen(false); setTimeout(() => resetComponent(), animationTime); - } + }; /** * Retrieve data from token and update states. @@ -357,13 +400,13 @@ export default function LinkButton({ editor, disabled } : LinkProps) { const handler = async ({ href, text, - modelToken, + modelToken, // eslint-disable-line no-shadow blank, }: { - href: string, - text: string, - modelToken: string | null, - blank: boolean, + href: string; + text: string; + modelToken: string | null; + blank: boolean; }): Promise => { setOpen(true); setLoading(true); @@ -372,14 +415,22 @@ export default function LinkButton({ editor, disabled } : LinkProps) { setSelectedType(LinkType.internal); try { // Retrieve data from decrypted token. - const data = await fetchOptions("back.wysiwyg.retrieve-data-from-token", { - token: modelToken, - }) as RetrieveFromTokenResponse; + const data = (await fetchOptions( + "back.wysiwyg.retrieve-data-from-token", + { + token: modelToken, + }, + )) as RetrieveFromTokenResponse; // Retrieve selected enum. - const newSelectedEnum = Object.values(enumModelsList ?? []).find((def) => def.name === data.modelName); + const newSelectedEnum = Object.values( + enumModelsList ?? [], + ).find((def) => def.name === data.modelName); if (!newSelectedEnum) { - setErrors(prev => ({ ...prev, 'selectedEntry': 'Model inconnu' })); + setErrors((prev) => ({ + ...prev, + selectedEntry: "Model inconnu", + })); return; } @@ -387,9 +438,14 @@ export default function LinkButton({ editor, disabled } : LinkProps) { setSelectedModelId(data.modelId); setSelectedEntryUrl(href); setModelToken(modelToken); - } catch (err: any) { + } catch (err: unknown) { console.error(err); - setErrors(prev => ({ ...prev, ...err.response?.data?.errors})) + if (isAxiosError(err) && err.response?.data?.errors) { + setErrors((prev) => ({ + ...prev, + ...err.response?.data.errors, + })); + } } } else { setSelectedType(LinkType.external); @@ -397,17 +453,26 @@ export default function LinkButton({ editor, disabled } : LinkProps) { } setInputText(text); setInputBlank(blank); - setResetState(prev => prev + 1) + setResetState((prev) => prev + 1); setLoading(false); - } + }; // Catch wysiwyg event when clicking on link. useEffect(() => { editor.on("open-link-editor", handler); return () => { editor.off("open-link-editor", handler); }; + // eslint-disable-next-line react-hooks/exhaustive-deps }, [editor]); + let path = ""; + + if (selectedEntryUrl) { + path = selectedEntryUrl.startsWith("/") + ? selectedEntryUrl.slice(1) + : selectedEntryUrl; + } + return ( - - - {useTrans('back.wysiwyg.link.title')} - {useTrans('back.wysiwyg.link.subtitle')} + + + + {useTrans("back.wysiwyg.link.title")} + + + {useTrans("back.wysiwyg.link.subtitle")} + -
+
@@ -469,49 +538,67 @@ export default function LinkButton({ editor, disabled } : LinkProps) { { }} - onSelectValue={(value) => handleSelectEnum(value)} + setData={() => {}} + onSelectValue={(value) => + handleSelectEnum(value) + } parentErrors={errors} /> {/* Selected entry. */} - handleSelectEntry(Array.isArray(value) ? value[0] ?? null : value) + handleSelectEntry( + Array.isArray(value) + ? (value[0] ?? null) + : value, + ) } parentErrors={errors} /> {/* Url to go to the selected entry. */} {selectedEntryUrl ? ( ) : ( - {useTrans('back.wysiwyg.link.link')} + + {GetTranslation( + "back.wysiwyg.link.link", + )} + )} ) : ( @@ -519,25 +606,33 @@ export default function LinkButton({ editor, disabled } : LinkProps) { {/* Url input. */} handleUpdateUrl(value)} + setData={(_, value) => + handleUpdateUrl(value) + } pattern="https?://.+" placeholder="ex: https://example.com" parentErrors={errors} /> {/* Url to go to the url. */} } - tooltipContent={useTrans('back.wysiwyg.link.access_url')} + content={ + + } + tooltipContent={GetTranslation( + "back.wysiwyg.link.access_url", + )} className="cursor-pointer" variant="secondary" type="button" size="default" link={inputUrl} - externalLink={true} + externalLink disabled={loading || inputUrl.length <= 8} />
@@ -545,7 +640,7 @@ export default function LinkButton({ editor, disabled } : LinkProps) { {/* String input. */} handleUpdateText(value)} @@ -553,7 +648,7 @@ export default function LinkButton({ editor, disabled } : LinkProps) { /> {/* Boolean input. */}
-
+ {/* Cancel button. */} {/* Save button. */} } - tooltipContent={useTrans('back.wysiwyg.link.tooltip_delete')} + tooltipContent={GetTranslation( + "back.wysiwyg.link.tooltip_delete", + )} className="cursor-pointer" - variant='destructive' + variant="destructive" type="button" disabled={loading || !editingLink} onClick={handleDeleteLink} /> -
+
); diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/link.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/link.d.ts index 6184b48b..20e4e4c5 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/link.d.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/link.d.ts @@ -1,13 +1,15 @@ -import '@tiptap/core'; +// * Packages +import "@tiptap/core"; -declare module '@tiptap/core' { +declare module "@tiptap/core" { interface Commands { Link: { + // eslint-disable-next-line no-unused-vars setLink: (attrs: { - href: string, - text: string, - blank: boolean, - modelToken: string|null; + href: string; + text: string; + blank: boolean; + modelToken: string | null; }) => ReturnType; unsetLink: () => ReturnType; }; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/tiptap-events.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/tiptap-events.d.ts index 055abd99..40c77262 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/tiptap-events.d.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Link/tiptap-events.d.ts @@ -1,12 +1,13 @@ -import '@tiptap/core'; +// * Packages +import "@tiptap/core"; -declare module '@tiptap/core' { - interface EditorEvents { - 'open-link-editor': { - href: string; - text: string; - blank: boolean; - modelToken: string | null; - }; - } +declare module "@tiptap/core" { + interface EditorEvents { + "open-link-editor": { + href: string; + text: string; + blank: boolean; + modelToken: string | null; + }; + } } diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton.tsx index 0a758d1b..4f6576d3 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton.tsx @@ -10,6 +10,7 @@ import { DialogTitle, DialogDescription, DialogTrigger, + DialogFooter, } from "@/components/ui/dialog"; import { Checkbox } from "@/components/ui/checkbox"; import { Label } from "@/components/ui/label"; @@ -28,30 +29,6 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) { // Duration of modal closing animation. const animationTime = 200; - /** - * Search and replace specific text. - * - * @return void - */ - const handleReplaceAll = (): void => { - if (!editor || !searchText) return; - - // Get all editor content. - const html = editor.getHTML(); - - // Set dynamic regex depending on match case value. - const flags = matchCase ? "g" : "gi"; - const regex = new RegExp(searchText, flags); - - // Replace the text. - const newHtml = html.replace(regex, replaceText); - - // Update editor content. - editor.commands.setContent(newHtml); - - closeModal(); - }; - /** * Reset the component. * @@ -74,11 +51,32 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) { setTimeout(() => resetComponent(), animationTime); }; + /** + * Search and replace specific text. + * + * @return void + */ + const handleReplaceAll = (): void => { + if (!editor || !searchText) return; + + // Get all editor content. + const html = editor.getHTML(); + + // Set dynamic regex depending on match case value. + const flags = matchCase ? "g" : "gi"; + const regex = new RegExp(searchText, flags); + + // Replace the text. + const newHtml = html.replace(regex, replaceText); + + // Update editor content. + editor.commands.setContent(newHtml); + + closeModal(); + }; + return ( - closeModal(status)} - > + closeModal(status)}> } @@ -89,48 +87,52 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) { size="icon" /> - - - {useTrans("back.wysiwyg.replace.title")} + + + + {useTrans("back.wysiwyg.replace.title")} + {useTrans("back.wysiwyg.replace.subtitle")} - {/* Inputs text */} - setSearchText(value)} - /> - setReplaceText(value)} - /> -
- setMatchCase(Boolean(val))} +
+ {/* Inputs text */} + setSearchText(value)} /> - + setReplaceText(value)} + /> +
+ + setMatchCase(Boolean(val)) + } + /> + +
{/* Action buttons */} -
+ -
+
); diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary.tsx index b737a342..e4fed0d5 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary.tsx @@ -2,7 +2,7 @@ import { Extension } from "@tiptap/core"; import { Plugin } from "prosemirror-state"; -export const ShortcutBoundary = Extension.create({ +const ShortcutBoundary = Extension.create({ addProseMirrorPlugins() { return [ new Plugin({ @@ -22,3 +22,5 @@ export const ShortcutBoundary = Extension.create({ ]; }, }); + +export default ShortcutBoundary; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton.tsx index d19fa1d4..2e8b72ba 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton.tsx @@ -10,6 +10,7 @@ import { DialogTitle, DialogDescription, DialogTrigger, + DialogFooter, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Checkbox } from "@/components/ui/checkbox"; @@ -23,9 +24,9 @@ const BASE = 5; const MAX = 12; type TableProps = { - editor: Editor, - disabled: boolean, -} + editor: Editor; + disabled: boolean; +}; export default function TableButton({ editor, disabled }: TableProps) { const [rows, setRows] = useState(3); @@ -53,18 +54,18 @@ export default function TableButton({ editor, disabled }: TableProps) { ); const insert = ( - rows: number | undefined = undefined, - cols: number | undefined = undefined, + expectedRows: number | undefined = undefined, + expectedCols: number | undefined = undefined, ): void => { if (!editor.can().insertTable()) return; - // Insert the current table in the editor. + // Insert the expected table in the editor. editor .chain() .focus() .insertTable({ - rows: rows, - cols: cols, + rows: expectedRows, + cols: expectedCols, withHeaderRow: header, }) .run(); @@ -85,16 +86,6 @@ export default function TableButton({ editor, disabled }: TableProps) { setHeader(true); }; - /** - * Insert tableClose modal and reset component. - * - * @return void - */ - const handleInsertTable = (): void => { - insert(); - closeModal(); - }; - /** * Close modal and reset component. * @@ -105,6 +96,16 @@ export default function TableButton({ editor, disabled }: TableProps) { setTimeout(() => resetComponent(), animationTime); }; + /** + * Insert tableClose modal and reset component. + * + * @return void + */ + const handleInsertTable = (): void => { + insert(); + closeModal(); + }; + // Set size of the current table on hover. useEffect(() => { setHover({ row: rows, column: cols }); @@ -112,7 +113,7 @@ export default function TableButton({ editor, disabled }: TableProps) { // Press the key event to use the arrow keys to set the table size. useEffect(() => { - if (!open) return; + if (!open) return undefined; const onKeyDown = (event: KeyboardEvent) => { const active = document.activeElement as HTMLInputElement; @@ -163,13 +164,16 @@ export default function TableButton({ editor, disabled }: TableProps) { event.preventDefault(); setOpen(false); break; + default: + break; } }; // Redefine the keydown event due to table resize. window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [open, insert]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]); return ( } - tooltipContent={useTrans( - "back.wysiwyg.table.tooltip", - )} + tooltipContent={useTrans("back.wysiwyg.table.tooltip")} disabled={disabled || !editor.can().insertTable()} type="button" variant="ghost" size="icon" /> - - + + {useTrans("back.wysiwyg.table.title")} @@ -201,96 +203,106 @@ export default function TableButton({ editor, disabled }: TableProps) { {/* Inputs */} -
-
- - - setRows(Number(event.target.value) || 1) - } - /> -
-
- - - setCols(Number(event.target.value) || 1) - } - /> -
-
- - setHeader(Boolean(event)) - } - /> - -
-
- {/* Keys notice */} -

- - {useTrans("back.wysiwyg.table.use_arrow_keys")} - - - {useTrans("back.wysiwyg.table.enter_to_insert")} - -

- {/* Preview grid */} -
- {Array.from({ length: gridSize * gridSize }).map((_, i) => { - const row = Math.floor(i / gridSize) + 1; - const column = (i % gridSize) + 1; - const active = - hover && row <= hover.row && column <= hover.column; - return ( -
{ - setHover({ row, column }); - setRows(row); - setCols(column); - }} - onClick={() => insert(row, column)} - className={[ - "aspect-square border cursor-pointer", - active - ? "bg-primary/30 border-primary" - : "bg-muted", - ].join(" ")} +
+
+
+ + + setRows(Number(event.target.value) || 1) + } /> - ); - })} +
+
+ + + setCols(Number(event.target.value) || 1) + } + /> +
+
+ + setHeader(Boolean(event)) + } + /> + +
+
+ {/* Keys notice */} +

+ + {useTrans("back.wysiwyg.table.use_arrow_keys")} + + + {useTrans("back.wysiwyg.table.enter_to_insert")} + +

+ {/* Preview grid */} +
+ {Array.from({ length: gridSize * gridSize }).map( + (_, i) => { + const row = Math.floor(i / gridSize) + 1; + const column = (i % gridSize) + 1; + + const active = + hover && + row <= hover.row && + column <= hover.column; + + return ( +
{/* Action buttons */} -
+ -
+
); diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx index d1b84570..79e0af09 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx @@ -17,147 +17,166 @@ import TextAlign from "@tiptap/extension-text-align"; // * Components shadcn import { Label } from "@/components/ui/label"; // * Other -import { ShortcutBoundary } from "@/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary"; +import ShortcutBoundary from "@/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary"; import { Link } from "@/back/Components/Inputs/Wysiwyg/Extensions/Link/Link"; -import { Image } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/Image"; +import Image from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/Image"; import InputError from "@/back/Components/InputError"; import WordCounter from "@/back/Components/WordCounter"; import Toolbar from "@/back/Components/Inputs/Wysiwyg/Toolbar"; -import useTrans from "@/hooks/use-translations"; -import { cn } from "@/lib/utils"; +import { cn, GetTranslation } from "@/lib/utils"; type SimpleWysiwygProps = { - className?: string; - name: string; - model: string; - label: string; - value?: string; - id?: string; - placeholder?: string; - wordCounter?: boolean; - required?: boolean; - disabled?: boolean; - parentErrors?: Record | null; - setData: (name: string, value: string) => void; + className?: string; + name: string; + model: string; + label: string; + value?: string; + id?: string; + placeholder?: string; + wordCounter?: boolean; + required?: boolean; + disabled?: boolean; + parentErrors?: Record | null; + // eslint-disable-next-line no-unused-vars + setData: (name: string, value: string) => void; }; export default function SimpleWysiwyg({ - className, - value = undefined, - model, - name, - label, - id = name as string, - placeholder = "back.enter_text_here", - wordCounter = true, - required = true, - disabled = false, - parentErrors = null, - setData, + className, + value = undefined, + model, + name, + label, + id = name as string, + placeholder = "back.enter_text_here", + wordCounter = true, + required = true, + disabled = false, + parentErrors = null, + setData, }: SimpleWysiwygProps) { - const { errors } = usePage().props; - const localErrors = parentErrors ?? errors; + const { errors } = usePage().props; + const localErrors = parentErrors ?? errors; - const [editor, setEditor] = useState(null); - const [content, setContent] = useState(value); + const [editor, setEditor] = useState(null); + const [content, setContent] = useState(value); - /** - * Remove html tags from content string. - * - * @param html string - * @return string|null - */ - const stripHtmlTags = (html: string): string|null => { - const temp = document.createElement("div"); - temp.innerHTML = html; - const text = temp.textContent || temp.innerText || ""; - return text.trim() === "" ? null : text; - }; + /** + * Remove html tags from content string. + * + * @param html string + * @return string|null + */ + const stripHtmlTags = (html: string): string | null => { + const temp = document.createElement("div"); + temp.innerHTML = html; + const text = temp.textContent || temp.innerText || ""; + return text.trim() === "" ? null : text; + }; - /** - * Update values when content is changing. - * - * @param editorContent string - * @return void - */ - const onChangeContent = (editorContent: string): void => { - const val = stripHtmlTags(editorContent) ? editorContent : ""; - setContent(val); - setData(name, val); - }; + /** + * Update values when content is changing. + * + * @param editorContent string + * @return void + */ + const onChangeContent = (editorContent: string): void => { + const val = stripHtmlTags(editorContent) ? editorContent : ""; + setContent(val); + setData(name, val); + }; - // Tiptap extensions. - const extensions = useMemo(() => [ - // Starterkit contains: heading, bold, italic, strike, underline, ordered list, item list, blockquote. - StarterKit.configure({ - link: false, // Custom link extension. - }), - // Specific extensions. - ShortcutBoundary, - TaskList, - TaskItem.configure({ - nested: true, - }), - Table.configure({ - resizable: true, - }), - TableRow, - TableHeader, - TableCell, - Placeholder.configure({ - placeholder: useTrans(placeholder), - }), - TextAlign.configure({ - types: ["heading", "paragraph"], - }), - Subscript, - Superscript, - InvisibleCharacters.configure({ - visible: false, - }), - Image, - Link, - ], []); + // Tiptap extensions. + const extensions = useMemo( + () => [ + // Starterkit contains: heading, bold, italic, strike, underline, ordered list, item list, blockquote. + StarterKit.configure({ + link: false, // Custom link extension. + }), + // Specific extensions. + ShortcutBoundary, + TaskList, + TaskItem.configure({ + nested: true, + }), + Table.configure({ + resizable: true, + }), + TableRow, + TableHeader, + TableCell, + Placeholder.configure({ + placeholder: GetTranslation(placeholder), + }), + TextAlign.configure({ + types: ["heading", "paragraph"], + }), + Subscript, + Superscript, + InvisibleCharacters.configure({ + visible: false, + }), + Image, + Link, + ], + // eslint-disable-next-line react-hooks/exhaustive-deps + [], + ); - // Init editor only once. - useEffect(() => { - const e = new Editor({ - content: value || undefined, - extensions, - editable: !disabled, - editorProps: { attributes: { id, required: String(required), model } }, - onUpdate: ({ editor }) => onChangeContent(editor.getHTML()), - }); - setEditor(e); + // Init editor only once. + useEffect(() => { + const e = new Editor({ + content: value || undefined, + extensions, + editable: !disabled, + editorProps: { + attributes: { id, required: String(required), model }, + }, + onUpdate: ({ editor: currentEditor }) => + onChangeContent(currentEditor.getHTML()), + }); + setEditor(e); - return () => e.destroy(); - }, []); + return () => e.destroy(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); - // Sync content if parent change. - useEffect(() => { - if (!editor) return; - - if (!value) { - editor.commands.clearContent(true); - return; - } + // Sync content if parent change. + useEffect(() => { + if (!editor) return; - if (editor.getHTML() !== value) { - editor.commands.setContent(value); - } - }, [value, editor]); - - if (!editor) return null; + if (!value) { + editor.commands.clearContent(true); + return; + } - return ( -
- - {wordCounter && } -
- - -
- -
- ); + if (editor.getHTML() !== value) { + editor.commands.setContent(value); + } + }, [value, editor]); + + if (!editor) return null; + + return ( +
+ + {wordCounter && ( + + )} +
+ + +
+ +
+ ); } diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Toolbar.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Toolbar.tsx index 9c2aa034..adfff8b0 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Toolbar.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Toolbar.tsx @@ -45,9 +45,8 @@ import LinkButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkBut import TableButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton"; import FindReplaceButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import { cn } from "@/lib/utils"; +import { cn, GetTranslation } from "@/lib/utils"; type AllowedHeadings = 1 | 2 | 3 | 4 | 5 | 6; @@ -109,7 +108,7 @@ export default function Toolbar({ editor }: ToolbarProps) { // Force re-render editor on select to update activated extensions. useEffect(() => { - if (!editor) return; + if (!editor) return undefined; const update = () => forceUpdate((value) => value + 1); @@ -127,14 +126,16 @@ export default function Toolbar({ editor }: ToolbarProps) { // Set header height with resize event. useEffect(() => { - const handleResize = () => { - setHeaderHeight(document.querySelector("header")?.clientHeight ?? 0); - }; - - window.addEventListener('resize', handleResize); - handleResize(); - - return () => window.removeEventListener('resize', handleResize); + const handleResize = () => { + setHeaderHeight( + document.querySelector("header")?.clientHeight ?? 0, + ); + }; + + window.addEventListener("resize", handleResize); + handleResize(); + + return () => window.removeEventListener("resize", handleResize); }, []); return ( @@ -146,7 +147,7 @@ export default function Toolbar({ editor }: ToolbarProps) { > } - tooltipContent={str(useTrans("back.wysiwyg.undo")) + tooltipContent={str(GetTranslation("back.wysiwyg.undo")) .ucFirst() .value()} onClick={(event) => { @@ -160,7 +161,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.redo")) + tooltipContent={str(GetTranslation("back.wysiwyg.redo")) .ucFirst() .value()} onClick={(event) => { @@ -175,7 +176,7 @@ export default function Toolbar({ editor }: ToolbarProps) { } - tooltipContent={str(useTrans("back.wysiwyg.bold")) + tooltipContent={str(GetTranslation("back.wysiwyg.bold")) .ucFirst() .value()} onClick={(event) => { @@ -190,7 +191,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.italic")) + tooltipContent={str(GetTranslation("back.wysiwyg.italic")) .ucFirst() .value()} onClick={(event) => { @@ -205,7 +206,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.strike")) + tooltipContent={str(GetTranslation("back.wysiwyg.strike")) .ucFirst() .value()} onClick={(event) => { @@ -220,7 +221,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.underline")) + tooltipContent={str(GetTranslation("back.wysiwyg.underline")) .ucFirst() .value()} onClick={(event) => { @@ -235,7 +236,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.blockquote")) + tooltipContent={str(GetTranslation("back.wysiwyg.blockquote")) .ucFirst() .value()} onClick={(event) => { @@ -275,18 +276,18 @@ export default function Toolbar({ editor }: ToolbarProps) { - {useTrans("back.wysiwyg.heading")} + {GetTranslation("back.wysiwyg.heading")}
{/* Define default paragraph value to reset heading */} - {useTrans("back.wysiwyg.heading_paragraph")} + {GetTranslation("back.wysiwyg.heading_paragraph")} {/* List of headings */} {headingLevels.map((level) => ( - {useTrans("back.wysiwyg.heading_x", { + {GetTranslation("back.wysiwyg.heading_x", { params: { hx: String(level) }, })} @@ -296,7 +297,7 @@ export default function Toolbar({ editor }: ToolbarProps) { } - tooltipContent={str(useTrans("back.wysiwyg.bullet_list")) + tooltipContent={str(GetTranslation("back.wysiwyg.bullet_list")) .ucFirst() .value()} onClick={(event) => { @@ -311,7 +312,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.ordered_list")) + tooltipContent={str(GetTranslation("back.wysiwyg.ordered_list")) .ucFirst() .value()} onClick={(event) => { @@ -326,7 +327,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.task_list")) + tooltipContent={str(GetTranslation("back.wysiwyg.task_list")) .ucFirst() .value()} onClick={(event) => { @@ -364,7 +365,7 @@ export default function Toolbar({ editor }: ToolbarProps) { - {useTrans("back.wysiwyg.align")} + {GetTranslation("back.wysiwyg.align")} @@ -374,8 +375,10 @@ export default function Toolbar({ editor }: ToolbarProps) { value={align.value.toString()} >
- {} - {useTrans(`back.wysiwyg.align_${align.value}`)} + + {GetTranslation( + `back.wysiwyg.align_${align.value}`, + )}
))} @@ -384,7 +387,7 @@ export default function Toolbar({ editor }: ToolbarProps) { } - tooltipContent={str(useTrans("back.wysiwyg.subscript")) + tooltipContent={str(GetTranslation("back.wysiwyg.subscript")) .ucFirst() .value()} onClick={(event) => { @@ -399,7 +402,7 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.superscript")) + tooltipContent={str(GetTranslation("back.wysiwyg.superscript")) .ucFirst() .value()} onClick={(event) => { @@ -415,7 +418,9 @@ export default function Toolbar({ editor }: ToolbarProps) { } - tooltipContent={str(useTrans("back.wysiwyg.horizontal_rule")) + tooltipContent={str( + GetTranslation("back.wysiwyg.horizontal_rule"), + ) .ucFirst() .value()} onClick={(event) => { @@ -434,7 +439,7 @@ export default function Toolbar({ editor }: ToolbarProps) { } tooltipContent={str( - useTrans("back.wysiwyg.invisible_characters"), + GetTranslation("back.wysiwyg.invisible_characters"), ) .ucFirst() .value()} @@ -454,7 +459,7 @@ export default function Toolbar({ editor }: ToolbarProps) { } - tooltipContent={str(useTrans("back.wysiwyg.select_all")) + tooltipContent={str(GetTranslation("back.wysiwyg.select_all")) .ucFirst() .value()} onClick={(event) => { @@ -467,7 +472,9 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.clear_selection")) + tooltipContent={str( + GetTranslation("back.wysiwyg.clear_selection"), + ) .ucFirst() .value()} onClick={(event) => { @@ -482,7 +489,7 @@ export default function Toolbar({ editor }: ToolbarProps) { .run(); }} disabled={ - editor.getText().trim() === "" && + editor.getText().trim() === "" || editor.state.selection.empty } type="button" @@ -491,7 +498,9 @@ export default function Toolbar({ editor }: ToolbarProps) { /> } - tooltipContent={str(useTrans("back.wysiwyg.delete_selection")) + tooltipContent={str( + GetTranslation("back.wysiwyg.delete_selection"), + ) .ucFirst() .value()} onClick={(event) => { @@ -499,7 +508,7 @@ export default function Toolbar({ editor }: ToolbarProps) { editor.chain().focus().deleteSelection().run(); }} disabled={ - editor.getText().trim() === "" && + editor.getText().trim() === "" || editor.state.selection.empty } type="button" diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/tiptap.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/tiptap.d.ts index 31c30d3d..2af11267 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/tiptap.d.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/tiptap.d.ts @@ -1,9 +1,10 @@ -import '@tiptap/core' +// * Packages +import "@tiptap/core"; -declare module '@tiptap/core' { - interface Storage { - invisibleCharacters?: { - visibility: () => boolean +declare module "@tiptap/core" { + interface Storage { + invisibleCharacters?: { + visibility: () => boolean; + }; } - } } diff --git a/resources/ts/back/Components/Layout/AppSettings.tsx b/resources/ts/back/Components/Layout/AppSettings.tsx index 9fe27e77..b310ca6c 100644 --- a/resources/ts/back/Components/Layout/AppSettings.tsx +++ b/resources/ts/back/Components/Layout/AppSettings.tsx @@ -16,15 +16,13 @@ import { import { AppEnv, Theme } from "@/back/types/global"; import { useTheme } from "@/back/providers/ThemeProvider"; import useTrans from "@/hooks/use-translations"; -import { cn } from "@/lib/utils"; +import { cn, GetTranslation } from "@/lib/utils"; type AppSettingsProps = { className?: string; }; -export default function AppSettings({ - className = "", -}: AppSettingsProps) { +export default function AppSettings({ className = "" }: AppSettingsProps) { const { locale, locales } = usePage().props.appEnv as AppEnv; const { setTheme, theme } = useTheme(); const { post, setData } = useForm({ @@ -34,9 +32,7 @@ export default function AppSettings({ e.preventDefault(); post(route(`back.lang.set`)); }; - const GetTranslation = (name: string) => { - return useTrans(name); - }; + const mods = [ { name: useTrans("back.light"), @@ -71,7 +67,9 @@ export default function AppSettings({ flag: "de", }, ]; - const allowedLocales = languages.filter(language => locales.includes(language.locale)); + const allowedLocales = languages.filter((language) => + locales.includes(language.locale), + ); return (
@@ -79,13 +77,13 @@ export default function AppSettings({

- {useTrans("back.mods")} + {GetTranslation("back.mods")}

{mods.map((mod) => { @@ -115,7 +113,7 @@ export default function AppSettings({ <>

- {useTrans("back.languages")} + {GetTranslation("back.languages")}

diff --git a/resources/ts/back/Components/Layout/AppSidebar.tsx b/resources/ts/back/Components/Layout/AppSidebar.tsx index bfd1bac0..817f3033 100644 --- a/resources/ts/back/Components/Layout/AppSidebar.tsx +++ b/resources/ts/back/Components/Layout/AppSidebar.tsx @@ -61,37 +61,63 @@ import { AppEnv, AuthProp, LaravelEnum } from "@/back/types/global"; type NavListProps = Array<{ /** Title of the group. */ - title: string, + title: string; /** Condition to set the visibility of the group. */ - show: boolean, + show: boolean; /** Links presents in the group. */ links: Array<{ /** Title of the button. */ - title: string, + title: string; /** Main model of the button (used for route checking). */ - model?: string, + model?: string; /** External link of the button (if it's a not CRUD, just a simple link). */ - link?: string, + link?: string; /** Define some conditions for active or not the button (in addition to the route model checking if defined). */ - activeCondition?: boolean[], + activeCondition?: boolean[]; /** Condition to set the visibility of the button. */ - show: boolean, + show: boolean; /** Lucide icon of the button. */ - icon: ElementType, + icon: ElementType; /** Define some actions in side popover (like create/trash). */ - actions?: (model: string) => ReactNode, - }> -}> + // eslint-disable-next-line no-unused-vars + actions?: (model: string) => ReactNode; + }>; +}>; type CustomDropdownMenuItemProps = { /** Link of the action. */ - route: string; + targetRoute: string; /** Lucide icon of the action. */ - icon?: ElementType; + icon: ElementType; /** Translation of the action. */ - trans?: string; + trans: string; }; +/** + * Sidenav action button. + * + * @param string targetRoute + * @param ElementType icon + * @param string trans + * @return ReactNode + */ +function CustomDropdownMenuItem({ + targetRoute, + icon: Icon, + trans, +}: CustomDropdownMenuItemProps): ReactNode { + return ( + + + + ); +} + export default function AppSidebar() { const { appEnv, auth, enumUserRole } = usePage().props as unknown as { appEnv: AppEnv; @@ -102,205 +128,359 @@ export default function AppSidebar() { const { state } = useSidebar(); const prevStateRef = useRef(state); const isCollapsed = state === "collapsed"; + + // Translations. + const transDefaultSideAction = str( + useTrans(`crud.actions.${Views.CREATION.label}`), + ) + .ucFirst() + .value(); + const transPages = useTrans("back.pages"); + const transDashboard = useTrans("back.dashboard"); + const transWebsite = useTrans("back.your_website"); + const transDynamicPages = useTrans("models.classes.dynamic-page", { + choice: 2, + }); + const transModules = useTrans("back.modules"); + const transNews = useTrans("models.classes.news", { choice: 2 }); + const transNewsCategories = useTrans("models.classes.news-category", { + choice: 2, + }); + const transNewsTags = useTrans("models.classes.news-tag", { choice: 2 }); + const transContactCount = useTrans("models.classes.contact-count"); + const transDocuments = useTrans("models.classes.document", { choice: 2 }); + const transDocumentCategories = useTrans( + "models.classes.document-category", + { choice: 2 }, + ); + const transDocumentTags = useTrans("models.classes.document-tag", { + choice: 2, + }); + const transCompanies = useTrans("models.classes.company", { choice: 2 }); + const transCompanyActivities = useTrans("models.classes.company-activity", { + choice: 2, + }); + const transCompanySectors = useTrans("models.classes.company-sector", { + choice: 2, + }); + const transAdmin = useTrans("enums.user-role.admin"); + const transUsers = useTrans("models.classes.user"); + const transActivityLogs = useTrans("models.classes.activity-log"); + const transPageConfigs = useTrans("models.classes.page-config", { + choice: 2, + }); + const transArchives = str(useTrans("back.archives")).ucFirst().value(); + const transTelescope = useTrans("back.telescope"); + + /** + * Get sidenav actions. + * + * @param ReactNode items + * @param string model + * @return + */ + const filterActions = ({ + items, + model, + }: { + items?: ReactNode[]; + model?: string; + }): ReactNode => { + let computedItems = items; + // Set create action by default. + if (!computedItems && model) { + computedItems = [ + authPolicies[model].create && ( + + ), + ]; + } + const visibleItems = computedItems + ? computedItems.filter(Boolean) + : null; + return visibleItems && visibleItems.length > 0 ? visibleItems : null; + }; + const navList: NavListProps = [ { - title: useTrans("back.pages"), + title: transPages, show: true, links: [ { - title: useTrans("back.dashboard"), + title: transDashboard, model: "dashboard", show: true, icon: HomeIcon, }, { - title: useTrans("back.your_website"), + title: transWebsite, link: "/", show: true, icon: SquareArrowOutUpRightIcon, }, { - title: str(useTrans("models.classes.dynamic-page", { choice: 2 })).ucFirst().value(), + title: str(transDynamicPages).ucFirst().value(), model: "dynamic-pages", show: authPolicies.dynamicPages.viewAny, icon: StickyNoteIcon, - actions: (model: string) => filterActions({ - items: [ - authPolicies.dynamicPages.create && ( - - ), - authPolicies.dynamicPages.viewTrash && ( - - ), - ] - }) + actions: (model: string) => + filterActions({ + items: [ + authPolicies.dynamicPages.create && ( + + ), + authPolicies.dynamicPages.viewTrash && ( + + ), + ], + }), }, ], }, { - title: useTrans("back.modules"), - show: authPolicies.news.viewAny || auth.policies.contact_counts.viewAny, + title: transModules, + show: + authPolicies.news.viewAny || + auth.policies.contact_counts.viewAny, links: [ { - title: str(useTrans("models.classes.news", { choice: 2 })).ucFirst().value(), + title: str(transNews).ucFirst().value(), model: "news", - activeCondition: [route().current("back.news-categories.*"), route().current('back.news-tags.*')], + activeCondition: [ + route().current("back.news-categories.*"), + route().current("back.news-tags.*"), + ], icon: NewspaperIcon, show: auth.policies.news.viewAny, - actions: (model: string) => filterActions({ - items: [ - authPolicies.news.create && ( - - ), - authPolicies.news.viewTrash && ( - - ), - authPolicies.newsCategories.viewAny && ( - - ), - authPolicies.newsTags.viewAny && ( - - ), - ] - }) + actions: (model: string) => + filterActions({ + items: [ + authPolicies.news.create && ( + + ), + authPolicies.news.viewTrash && ( + + ), + authPolicies.newsCategories.viewAny && ( + + ), + authPolicies.newsTags.viewAny && ( + + ), + ], + }), }, { - title: str(useTrans("models.classes.contact-count")).ucFirst().value(), + title: str(transContactCount).ucFirst().value(), model: "contact-counts", icon: ContactIcon, show: auth.policies.contact_counts.viewAny, }, { - title: str(useTrans("models.classes.document", { choice: 2 })).ucFirst().value(), + title: str(transDocuments).ucFirst().value(), model: "documents", - activeCondition: [route().current("back.document-categories.*"), route().current('back.document-tags.*')], + activeCondition: [ + route().current("back.document-categories.*"), + route().current("back.document-tags.*"), + ], icon: FileInputIcon, show: auth.policies.documents.viewAny, - actions: (model: string) => filterActions({ - items: [ - authPolicies.documents.create && ( - - ), - authPolicies.documentCategories.create && ( - - ), - authPolicies.documentTags.create && ( - - ) - ] - }) + actions: (model: string) => + filterActions({ + items: [ + authPolicies.documents.create && ( + + ), + authPolicies.documentCategories.create && ( + + ), + authPolicies.documentTags.create && ( + + ), + ], + }), }, { - title: str(useTrans("models.classes.company", { choice: 2 })).ucFirst().plural().value(), + title: str(transCompanies).ucFirst().plural().value(), model: "companies", - activeCondition: [route().current("back.company-activities.*"), route().current('back.company-sectors.*')], + activeCondition: [ + route().current("back.company-activities.*"), + route().current("back.company-sectors.*"), + ], icon: Building2Icon, show: auth.policies.companies.viewAny, - actions: (model: string) => filterActions({ - items: [ - authPolicies.companies.create && ( - - ), - authPolicies.companies.viewTrash && ( - - ), - authPolicies.companyActivities.viewAny && ( - - ), - authPolicies.companySectors.viewAny && ( - - ), - ] - }) + actions: (model: string) => + filterActions({ + items: [ + authPolicies.companies.create && ( + + ), + authPolicies.companies.viewTrash && ( + + ), + authPolicies.companyActivities.viewAny && ( + + ), + authPolicies.companySectors.viewAny && ( + + ), + ], + }), }, ], }, { - title: str(useTrans("enums.user-role.admin")).plural().value(), + title: str(transAdmin).plural().value(), show: auth.user.role === enumUserRole.conceptor.value, links: [ { - title: str(useTrans("models.classes.user")).ucFirst().plural().value(), + title: str(transUsers).ucFirst().plural().value(), model: "users", icon: UsersIcon, show: authPolicies.users.viewAny, actions: (model: string) => filterActions({ model }), }, { - title: str(useTrans("models.classes.activity-log")).ucFirst().plural().value(), + title: str(transActivityLogs).ucFirst().plural().value(), model: "activity-logs", icon: HistoryIcon, show: authPolicies.activityLogs.viewAny, }, { - title: str(useTrans("models.classes.page-config", { choice: 2 })).ucFirst().value(), + title: str(transPageConfigs).ucFirst().value(), model: "page-configs", show: authPolicies.pageConfigs.viewAny, icon: CogIcon, - actions: (model: string) => filterActions({ - items: [ - authPolicies.pageConfigs.create && ( - - ), - authPolicies.pageConfigs.viewTrash && ( - - ), - ] - }) + actions: (model: string) => + filterActions({ + items: [ + authPolicies.pageConfigs.create && ( + + ), + authPolicies.pageConfigs.viewTrash && ( + + ), + ], + }), }, { - title: useTrans("back.telescope"), - link: route().has("telescope") ? route("telescope") : undefined, + title: transTelescope, + link: route().has("telescope") + ? route("telescope") + : undefined, icon: TelescopeIcon, show: appEnv.mode === "local" && route().has("telescope"), }, @@ -308,32 +488,6 @@ export default function AppSidebar() { }, ]; - const filterActions = ({ items, model }: { items?: ReactNode[], model?: string }) => { - // Set create action by default. - if (!items && model) { - items = [authPolicies[model].create && ]; - } - const visibleItems = items ? items.filter(Boolean) : null; - return visibleItems && visibleItems.length > 0 ? <>{visibleItems} : null; - }; - - const CustomDropdownMenuItem = ({ - route, - icon: Icon = Views.CREATION.icon, - trans = str(useTrans(`crud.actions.${Views.CREATION.label}`)).ucFirst().value(), - }: CustomDropdownMenuItemProps) => { - return ( - - - - ); - }; - useEffect(() => { if (prevStateRef.current !== state) { const elmts = document.querySelectorAll(".sidebar-transition"); @@ -350,102 +504,141 @@ export default function AppSidebar() { return ( - + - + {navList.map( - (navGroup) => navGroup.show && ( - - - {!isCollapsed && ( - - - {navGroup.title} - - - - )} - - - - {navGroup.links.map((navLink) => { - if (navLink.show) { - const isActive = route().current(`back.${navLink.model}.*`) || navLink.activeCondition?.some(Boolean); - const sidebarButton = ( - - {navLink.link ? ( - - - {navLink.title} - - ) : ( - - - {navLink.title} - - )} - - ); - return - {isCollapsed ? ( - - - {sidebarButton} - - -

{navLink.title}

-
-
- ) : ( - sidebarButton - )} - {navLink.model && navLink.actions?.(navLink.model) && ( - - - + navGroup.show && ( + + + {!isCollapsed && ( + + + {navGroup.title} + + + + )} + + + + {navGroup.links + .filter( + (navLink) => + navLink.show, + ) + .map((navLink) => { + const isActive = + route().current( + `back.${navLink.model}.*`, + ) || + navLink.activeCondition?.some( + Boolean, + ); + const sidebarButton = ( + + {navLink.link ? ( + - - - - - {navLink.actions(navLink.model)} - - - )} -
- } - })} - - - - - - ), + + { + navLink.title + } + + ) : ( + + + { + navLink.title + } + + )} + + ); + return ( + + {isCollapsed ? ( + + + { + sidebarButton + } + + +

+ { + navLink.title + } +

+
+
+ ) : ( + sidebarButton + )} + {navLink.model && + navLink.actions?.( + navLink.model, + ) && ( + + + + + + + + {navLink.actions( + navLink.model, + )} + + + )} +
+ ); + })} + + + + + + ), )} diff --git a/resources/ts/back/Components/ModelActions.tsx b/resources/ts/back/Components/ModelActions.tsx index cd59a88f..319cba59 100644 --- a/resources/ts/back/Components/ModelActions.tsx +++ b/resources/ts/back/Components/ModelActions.tsx @@ -1,12 +1,18 @@ // * Packages import { Link, useForm } from "@inertiajs/react"; import { route } from "ziggy-js"; -import { FormEvent, useState } from "react"; +import { FormEvent, ReactNode, useState } from "react"; import { MoreHorizontalIcon } from "lucide-react"; +import type { VisitOptions } from "@inertiajs/core"; // * Components shadcn import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; -import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu"; +import { + DropdownMenuSeparator, + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; import { Dialog, DialogClose, @@ -17,23 +23,286 @@ import { DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; // * Other import { useFormatedDate } from "@/hooks/use-formated-value"; import { useToast } from "@/hooks/use-toast"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import { Model, Views as ViewsType } from "@/back/types/global"; +import { DefaultModel, Views as ViewsType } from "@/back/types/global"; import { Views } from "@/lib/utils"; +import { ToastActionElement, ToastProps } from "@/components/ui/toast"; + +interface Translations { + successfulArchivation: string; + successfulArchivationDetails: string; + canceledArchivation: string; + canceledArchivationDetails: string; + successfulRestoration: string; + successfulRestorationDetails: string; + canceledRestoration: string; + canceledRestorationDetails: string; + successfulDeletion: string; + successfulDeletionDetails: string; + canceledDeletion: string; + canceledDeletionDetails: string; +} + +type ToasterToast = ToastProps & { + id: string; + title?: ReactNode; + description?: ReactNode; + action?: ToastActionElement; +}; + +/** + * Button for GET action. + * @param action ViewsType[number] + * @param modelRoute string + * @param model DefaultModel + * @returns Element + */ +function GetAction({ + action, + modelRoute, + model, +}: { + action: ViewsType[number]; + modelRoute: string; + model: DefaultModel; +}) { + return ( + + ); +} + +/** + * Action call on model. + * @param event FormEvent + * @param action ViewsType[number] + * @param modelRoute string + * @param model DefaultModel + * @param setOpen (value: boolean) => void + * @param translations Translations + * @param toast + */ +const actionOnModel = ( + /* eslint-disable no-unused-vars */ + event: FormEvent, + action: ViewsType[number], + modelRoute: string, + model: DefaultModel, + setOpen: (value: boolean) => void, + translations: Translations, + toast: ({ ...props }: Omit) => { + id: string; + dismiss: () => void; + update: (propsChild: ToasterToast) => void; + }, + destroy: (url: string, options?: VisitOptions) => void, + patch: (url: string, options?: VisitOptions) => void, + /* eslint-enable no-unused-vars */ +) => { + event.preventDefault(); + + const routeAction = route(`back.${modelRoute}.${action.value}`, model.id); + + // All post actions mapping. + const actionMap: Record< + ViewsType[number]["label"], + { + method: typeof destroy | typeof patch; + success: { title: string; description: string }; + error: { title: string; description: string }; + } + > = { + [Views.ARCHIVATION.label]: { + method: destroy, + success: { + title: translations.successfulArchivation, + description: translations.successfulArchivationDetails, + }, + error: { + title: translations.canceledArchivation, + description: translations.canceledArchivationDetails, + }, + }, + [Views.RESTORATION.label]: { + method: patch, + success: { + title: translations.successfulRestoration, + description: translations.successfulRestorationDetails, + }, + error: { + title: translations.canceledRestoration, + description: translations.canceledRestorationDetails, + }, + }, + [Views.DELETION.label || Views.FORCEDELETION.label]: { + method: destroy, + success: { + title: translations.successfulDeletion, + description: translations.successfulDeletionDetails, + }, + error: { + title: translations.canceledDeletion, + description: translations.canceledDeletionDetails, + }, + }, + }; + + // Check if route exist. + const config = actionMap[action.label]; + if (!config) { + throw new Error(`Unknown action: ${action.label}`); + } + + // Close the dropdown. + setOpen(false); + + // Execute the call. + config.method(routeAction, { + preserveScroll: true, + onSuccess: () => toast(config.success), + onError: () => toast({ variant: "destructive", ...config.error }), + }); +}; + +/** + * Button for POST action. + * @param action ViewsType[number] + * @param modelRoute string + * @param model DefaultModel + * @param setOpen (value: boolean) => void + * @returns Element + */ +function PostAction({ + action, + modelRoute, + model, + setOpen, +}: { + action: ViewsType[number]; + modelRoute: string; + model: DefaultModel; + // eslint-disable-next-line no-unused-vars + setOpen: (value: boolean) => void; +}) { + const { delete: destroy, patch } = useForm(); + + const isRestoreAction = action.label === Views.RESTORATION.label; + const isArchiveAction = action.label === Views.ARCHIVATION.label; + const btnVariantType = isRestoreAction ? "ghost" : "destructive"; + let translationKeyBtnConfirm: string; + const { toast } = useToast(); + if (isRestoreAction) { + translationKeyBtnConfirm = "back.yes_restore"; + } else if (isArchiveAction) { + translationKeyBtnConfirm = "back.yes_archive"; + } else { + translationKeyBtnConfirm = "back.yes_delete"; + } + + const btnConfirm = useTrans(translationKeyBtnConfirm); + + let translationKeyBtnDesc = "back.lost_data"; + + if (isRestoreAction) { + translationKeyBtnDesc = "back.restore_data"; + } else if (isArchiveAction) { + translationKeyBtnDesc = "back.trash_data"; + } + + const btnDesc = useTrans(translationKeyBtnDesc); + + // Translations for actionOnModel. + const translations: Translations = { + successfulArchivation: useTrans("crud.messages.successful_archivation"), + successfulArchivationDetails: useTrans( + "crud.messages.successful_archivation_details", + ), + canceledArchivation: useTrans("crud.messages.canceled_archivation"), + canceledArchivationDetails: useTrans( + "crud.messages.canceled_archivation_details", + ), + successfulRestoration: useTrans("crud.messages.successful_restoration"), + successfulRestorationDetails: useTrans( + "crud.messages.successful_restoration_details", + ), + canceledRestoration: useTrans("crud.messages.canceled_restoration"), + canceledRestorationDetails: useTrans( + "crud.messages.canceled_restoration_details", + ), + successfulDeletion: useTrans("crud.messages.successful_deletion"), + successfulDeletionDetails: useTrans( + "crud.messages.successful_deletion_details", + ), + canceledDeletion: useTrans("crud.messages.canceled_deletion"), + canceledDeletionDetails: useTrans( + "crud.messages.canceled_deletion_details", + ), + }; + + return ( + + + + + + + {useTrans("back.are_you_sure")} + {btnDesc} + + + + + + + actionOnModel( + event, + action, + modelRoute, + model, + setOpen, + translations, + toast, + destroy, + patch, + ) + } + className="w-fit mb-2 sm:mb-0" + > + + + + + + ); +} interface ModelActionsProps { actions?: ViewsType; modelRoute: string; - model: Model; + model: DefaultModel; modelUpdatedAt?: string; inDialog?: boolean; message?: string; @@ -50,197 +319,62 @@ export default function ModelActions({ const [open, setOpen] = useState(false); const messageTrans = useTrans(message); const formattedDate = useFormatedDate(modelUpdatedAt); - const allowedActions = actions.filter((action) => model.policies[action.policy as keyof typeof model.policies]) - const { delete: destroy, patch } = useForm(); - const { toast } = useToast(); - - // Translations. - const successfulArchivation = useTrans('crud.messages.successful_archivation'); - const successfulArchivationDetails = useTrans("crud.messages.successful_archivation_details"); - const canceledArchivation = useTrans('crud.messages.canceled_archivation'); - const canceledArchivationDetails = useTrans("crud.messages.canceled_archivation_details"); - - const successfulRestoration = useTrans('crud.messages.successful_restoration'); - const successfulRestorationDetails = useTrans("crud.messages.successful_restoration_details"); - const canceledRestoration = useTrans('crud.messages.canceled_restoration'); - const canceledRestorationDetails = useTrans("crud.messages.canceled_restoration_details"); - - const successfulDeletion = useTrans('crud.messages.successful_deletion'); - const successfulDeletionDetails = useTrans("crud.messages.successful_deletion_details"); - const canceledDeletion = useTrans('crud.messages.canceled_deletion'); - const canceledDeletionDetails = useTrans("crud.messages.canceled_deletion_details"); - - /** - * Action call on model. - * @param event FormEvent - * @param action ViewsType[number] - */ - const actionOnModel = (event: FormEvent, action: ViewsType[number]) => { - event.preventDefault(); - - const routeAction = route(`back.${modelRoute}.${action.value}`, model.id); - - // All post actions mapping. - const actionMap: Record = { - [Views.ARCHIVATION.label]: { - method: destroy, - success: { - title: successfulArchivation, - description: successfulArchivationDetails, - }, - error: { - title: canceledArchivation, - description: canceledArchivationDetails, - }, - }, - [Views.RESTORATION.label]: { - method: patch, - success: { - title: successfulRestoration, - description: successfulRestorationDetails, - }, - error: { - title: canceledRestoration, - description: canceledRestorationDetails, - }, - }, - [Views.DELETION.label || Views.FORCEDELETION.label]: { - method: destroy, - success: { - title: successfulDeletion, - description: successfulDeletionDetails, - }, - error: { - title: canceledDeletion, - description: canceledDeletionDetails, - }, - }, - }; - - // Check if route exist. - const config = actionMap[action.label]; - if (!config) { - throw new Error(`Unknown action: ${action.label}`); - } - - // Close the dropdown. - setOpen(false); - - // Execute the call. - config.method(routeAction, { - preserveScroll: true, - onSuccess: () => toast(config.success), - onError: () => toast({ variant: "destructive", ...config.error }), - }); - }; + const allowedActions = actions.filter( + (action) => + model.policies[action.policy as keyof typeof model.policies], + ); /** * Get all action buttons. * @returns Element[] */ const AllBtnActions = () => { - return allowedActions.map((action, index) => ( -
- { - action.value === Views.ARCHIVATION.value - || action.value === Views.RESTORATION.value - || action.value === Views.DELETION.value - || action.value === Views.FORCEDELETION.value - ? inDialog && index != 0 ? ( - <> - - - - ) : - : - } -
- )) - } + const postActionValues = new Set([ + Views.ARCHIVATION.value, + Views.RESTORATION.value, + Views.DELETION.value, + Views.FORCEDELETION.value, + ]); - /** - * Button for POST action. - * @param action ViewsType[number] - * @returns Element - */ - const PostAction = ({ action }: { action: ViewsType[number] }) => { - const isRestoreAction = action.label === Views.RESTORATION.label; - const isArchiveAction = action.label === Views.ARCHIVATION.label; - const btnVariantType = isRestoreAction ? "ghost" : "destructive"; - const btnConfirm = useTrans(isRestoreAction ? "back.yes_restore" : isArchiveAction ? "back.yes_archive" : "back.yes_delete"); - const btnDesc = useTrans(isRestoreAction ? "back.restore_data" : isArchiveAction ? "back.trash_data" : "back.lost_data"); - return ( - - - - - - - - {useTrans("back.are_you_sure")} - - - {btnDesc} - - - - - - -
actionOnModel(event, action)} - className="w-fit mb-2 sm:mb-0" - > - -
-
-
-
- ) - } + return allowedActions.map((action) => { + const isPostAction = postActionValues.has(action.value); + const showSeparator = + inDialog && + isPostAction && + action.value !== allowedActions[0].value; - /** - * Button for GET action. - * @param action ViewsType[number] - * @returns Element - */ - const GetAction = ({ action }: { action: ViewsType[number] }) => ( - - ) + const content = isPostAction ? ( + <> + {showSeparator && } + + + ) : ( + + ); + + return ( +
+ {content} +
+ ); + }); + }; return ( -
+
{!inDialog && modelUpdatedAt.length > 0 && (

{messageTrans}

@@ -250,23 +384,21 @@ export default function ModelActions({
)} {Boolean(allowedActions.length) && ( -
+
{inDialog ? ( - - + diff --git a/resources/ts/back/Components/News/AssociatedNewsList.tsx b/resources/ts/back/Components/News/AssociatedNewsList.tsx index c5bf4c56..e433e070 100644 --- a/resources/ts/back/Components/News/AssociatedNewsList.tsx +++ b/resources/ts/back/Components/News/AssociatedNewsList.tsx @@ -1,49 +1,57 @@ // * Packages import { Row } from "@tanstack/react-table"; -import { usePage } from "@inertiajs/react"; import { NewspaperIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other -import DataTable from "@/back/Components/Table/DataTable" +import DataTable from "@/back/Components/Table/DataTable"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import { AppEnv, NewsModel, Resource } from "@/back/types/global"; +import { Resource } from "@/back/types/global"; +import { NewsModel } from "@/back/types/others"; import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; -import useTrans from "@/hooks/use-translations" -import str from "@/hooks/use-string" +import useTrans, { UseTransOptions } from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; interface Props { news: Resource; } -const AssociatedNewsList = (props: Props) => { - const { news } = props; - const { appEnv } = usePage().props as unknown as { - appEnv: AppEnv; - }; - const columns = [ +const getColumns = () => { + const GetTranslation = (name: string, options?: UseTransOptions) => { + return useTrans(name, options); + }; + const GetFormatedDate = ( + date: string, + timezone?: string, + time?: boolean, + ) => { + return useFormatedDate(date, timezone, time); + }; + return [ { accessorKey: "title", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("title")); - }, + cell: ({ row }: { row: Row }) => ( + + ), }, { accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( { ), cell: ({ row }: { row: Row }) => { return ( - + ); }, }, @@ -59,7 +67,9 @@ const AssociatedNewsList = (props: Props) => { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( { ), cell: ({ row }: { row: Row }) => ( - {useFormatedDate(row.getValue("updated_at"))} + {GetFormatedDate(row.getValue("updated_at"))} ), }, ]; +}; +function AssociatedNewsList(props: Props) { + const { news } = props; + + const columns = getColumns(); return ( <> @@ -92,12 +107,12 @@ const AssociatedNewsList = (props: Props) => { ); -}; +} export default AssociatedNewsList; diff --git a/resources/ts/back/Components/News/NewsStatusBadge.tsx b/resources/ts/back/Components/News/NewsStatusBadge.tsx index 4a48cc75..aab3f0a2 100644 --- a/resources/ts/back/Components/News/NewsStatusBadge.tsx +++ b/resources/ts/back/Components/News/NewsStatusBadge.tsx @@ -10,9 +10,7 @@ type NewsStatusBadgeProps = { value: number; }; -export default function NewsStatusBadge({ - value, -}: NewsStatusBadgeProps) { +export default function NewsStatusBadge({ value }: NewsStatusBadgeProps) { const { enumNewsStatus } = usePage().props as unknown as { enumNewsStatus: LaravelEnum; }; diff --git a/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx b/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx index 42b7afc8..5da118e3 100644 --- a/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx +++ b/resources/ts/back/Components/PageConfigs/AddNewFieldBtn.tsx @@ -1,56 +1,59 @@ // * Packages -import { PlusIcon } from "lucide-react" +import { PlusIcon } from "lucide-react"; import { VariantProps } from "class-variance-authority"; // * Components shadcn -import { Button, buttonVariants } from "@/components/ui/button" +import { Button, buttonVariants } from "@/components/ui/button"; // * Other -import useTrans from "@/hooks/use-translations" -import { ConfigInternalField, DynamicInternalField } from "@/back/types/global"; +import useTrans from "@/hooks/use-translations"; +import { + ConfigInternalField, + DynamicInternalField, +} from "@/back/types/dynamic-pages"; type AddNewFieldBtnProps = { - array: ConfigInternalField[] | DynamicInternalField[] | undefined, - variant?: VariantProps["variant"], - limitMax?: number | undefined; - onClick: () => void, -} + array: ConfigInternalField[] | DynamicInternalField[] | undefined; + variant?: VariantProps["variant"]; + limitMax?: number | undefined; + onClick: () => void; +}; // Get a button with some informations. export default function AddNewFieldBtn({ - array = [], - variant = "default", - limitMax, - onClick, + array = [], + variant = "default", + limitMax, + onClick, }: AddNewFieldBtnProps) { - // Translations. - const transNoMoreChildren = useTrans('back.no_more_children') - const transNewField = useTrans("back.new_field"); - const transEmptyWarning = useTrans("back.empty_warning"); - const transEntriesCount = useTrans("back.entries_count", { - params: { - length: String(array?.length ?? 0), - }, - choice: (array?.length ?? 0) > 1 ? 2 : 1 - }); + // Translations. + const transNoMoreChildren = useTrans("back.no_more_children"); + const transNewField = useTrans("back.new_field"); + const transEmptyWarning = useTrans("back.empty_warning"); + const transEntriesCount = useTrans("back.entries_count", { + params: { + length: String(array?.length ?? 0), + }, + choice: (array?.length ?? 0) > 1 ? 2 : 1, + }); - return ( -
- {/* Check if the limit is achieved */} - {limitMax && array.length >= limitMax ? ( -

{transNoMoreChildren}

- ) : ( - - )} - {/* Indicate the current number of elements. */} -

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

-
- ) + return ( +
+ {/* Check if the limit is achieved */} + {limitMax && array.length >= limitMax ? ( +

+ {transNoMoreChildren} +

+ ) : ( + + )} + {/* Indicate the current number of elements. */} +

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

+
+ ); } diff --git a/resources/ts/back/Components/PageConfigs/ConfigDetails.tsx b/resources/ts/back/Components/PageConfigs/ConfigDetails.tsx index a1b8b67c..8475504e 100644 --- a/resources/ts/back/Components/PageConfigs/ConfigDetails.tsx +++ b/resources/ts/back/Components/PageConfigs/ConfigDetails.tsx @@ -11,7 +11,7 @@ import { // * Other import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { ConfigField, DynamicFieldTypes } from "@/back/types/global"; +import { ConfigField, DynamicFieldTypes } from "@/back/types/dynamic-pages"; import { cn } from "@/lib/utils"; type ConfigDetailsProps = { @@ -19,23 +19,35 @@ type ConfigDetailsProps = { }; export default function ConfigDetails({ config }: ConfigDetailsProps) { - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; const getEnumDynamicFieldType = (value: number) => { - return Object.values(enumDynamicFieldTypes).find((def) => def.value === value); + return Object.values(enumDynamicFieldTypes).find( + (def) => def.value === value, + ); }; const transType = str(useTrans("validation.custom.type")).ucFirst().value(); - const transLabel = str(useTrans("validation.custom.label")).ucFirst().value(); - const transValidation = str(useTrans("validation.custom.validation")).ucFirst().value(); + const transLabel = str(useTrans("validation.custom.label")) + .ucFirst() + .value(); + const transValidation = str(useTrans("validation.custom.validation")) + .ucFirst() + .value(); - const RenderRows = (fields: ConfigField[], hasBorders: boolean = false): ReactNode => + const RenderRows = ( + fields: ConfigField[], + hasBorders: boolean = false, + ): ReactNode => fields.map((field, index) => { const hasChildren = !!field.children?.length; const accordionKey = `${field.key}-${index}`; - const rowContent = (hasChildren: boolean = false) => ( + const rowContent = (targetHasChildren: boolean = false) => (
-

{getEnumDynamicFieldType(field.type)?.label}

+

+ {getEnumDynamicFieldType(field.type)?.label} +

{field.label} {`(${field.key})`} @@ -43,14 +55,24 @@ export default function ConfigDetails({ config }: ConfigDetailsProps) {

{field.validation || "—"}
- {!hasChildren &&
} + {!targetHasChildren &&
}
); return ( - + {hasChildren ? ( - + {rowContent(hasChildren)} ) : ( @@ -58,7 +80,7 @@ export default function ConfigDetails({ config }: ConfigDetailsProps) { )} {hasChildren && ( - +
{RenderRows(field.children!, false)}
@@ -75,7 +97,7 @@ export default function ConfigDetails({ config }: ConfigDetailsProps) {
{transType}
{transLabel}
{transValidation}
-
+
{/* ROWS */} diff --git a/resources/ts/back/Components/PageConfigs/DynamicFields.tsx b/resources/ts/back/Components/PageConfigs/DynamicFields.tsx index 4169c16d..5f63cf5c 100644 --- a/resources/ts/back/Components/PageConfigs/DynamicFields.tsx +++ b/resources/ts/back/Components/PageConfigs/DynamicFields.tsx @@ -20,7 +20,11 @@ import { Accordion } from "@/components/ui/accordion"; import FieldGroup from "@/back/Components/PageConfigs/FieldGroup"; import AddNewFieldBtn from "@/back/Components/PageConfigs/AddNewFieldBtn"; import InputError from "@/back/Components/InputError"; -import { ConfigField, ConfigInternalField, DynamicFieldTypes } from "@/back/types/global"; +import { + ConfigField, + ConfigInternalField, + DynamicFieldTypes, +} from "@/back/types/dynamic-pages"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; @@ -44,10 +48,12 @@ export default function DynamicFields({ }: DynamicFieldsProps) { // Errors. const { errors } = usePage().props; - const [localErrors, setLocalErrors] = useState>(errors) + const [localErrors, setLocalErrors] = + useState>(errors); // Enums. - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; // Accordion open index. const [openIndex, setOpenIndex] = useState(""); @@ -56,35 +62,38 @@ export default function DynamicFields({ const prevValueRef = useRef(JSON.stringify(value ?? [])); // Sensitive fields. - var [originalConfigKeys, setOriginalConfigKeys] = useState([]); + const [originalConfigKeys, setOriginalConfigKeys] = useState([]); const addIdsRecursively = ( fields: ConfigField[], parentKey: string = name, startId = 0, - ): ConfigInternalField[] => { + ): ConfigInternalField[] => { let currentId = startId; - const withIds = fields.map(field => { - const id = currentId++; + const withIds = fields.map((field) => { + currentId += 1; + const id = currentId; - // Add the key in sensitive array. - const currentParentKey = `${parentKey}.${field.key}`; - setOriginalConfigKeys(prev => [...prev, currentParentKey]); + // Add the key in sensitive array. + const currentParentKey = `${parentKey}.${field.key}`; + setOriginalConfigKeys((prev) => [...prev, currentParentKey]); - const children = field.children - ? addIdsRecursively(field.children, currentParentKey, currentId) - : undefined; + const children = field.children + ? addIdsRecursively(field.children, currentParentKey, currentId) + : undefined; - if (field.children?.length) { - currentId += field.children.length; - } + if (field.children?.length) { + currentId += field.children.length; + } - return children ? { ...field, id, children } : { ...field, id }; + return children ? { ...field, id, children } : { ...field, id }; }); return withIds as ConfigInternalField[]; - } - const [fields, setFields] = useState(() => addIdsRecursively(value ?? [])); + }; + const [fields, setFields] = useState(() => + addIdsRecursively(value ?? []), + ); // Sorted fields by order. const sortedFields = useMemo( @@ -129,8 +138,10 @@ export default function DynamicFields({ * @returns void */ const addField = (): void => { - const maxOrder = Math.max(0, ...fields.map((field) => field.order ?? 0)) + 1; - const maxIndex = Math.max(0, ...fields.map((field) => field.id ?? 0)) + 1; + const maxOrder = + Math.max(0, ...fields.map((field) => field.order ?? 0)) + 1; + const maxIndex = + Math.max(0, ...fields.map((field) => field.id ?? 0)) + 1; const newField: ConfigInternalField = { id: maxIndex, @@ -158,19 +169,26 @@ export default function DynamicFields({ if (field.id !== fieldId) return field; // Merge the data. - const merged = Object.assign({}, field, updatedField); + const merged = { ...field, ...updatedField }; // Only if updated field is type. if (updatedField.type !== undefined) { const matchingKey = Object.keys(enumDynamicFieldTypes).find( - (k) => enumDynamicFieldTypes[k].value === updatedField.type, + (k) => + enumDynamicFieldTypes[k].value === + updatedField.type, ); - const originalMatchingKey = Object.keys(enumDynamicFieldTypes).find( + const originalMatchingKey = Object.keys( + enumDynamicFieldTypes, + ).find( (k) => enumDynamicFieldTypes[k].value === field.type, ); - const editableKey = field.key.split(`${originalMatchingKey ?? enumDynamicFieldTypes.string.name}_`)[1] + const editableKey = field.key.split( + `${originalMatchingKey ?? enumDynamicFieldTypes.string.name}_`, + )[1]; if (matchingKey) { - merged.validation = enumDynamicFieldTypes[matchingKey].validation; + merged.validation = + enumDynamicFieldTypes[matchingKey].validation; merged.type = enumDynamicFieldTypes[matchingKey].value; merged.key = `${matchingKey}_${editableKey}`; } @@ -180,6 +198,18 @@ export default function DynamicFields({ ); }; + /** + * Remove sensitive field list. + * @param keyToRemove string + */ + const removeSensitiveField = (keyToRemove: string): void => { + setOriginalConfigKeys((prev) => + prev.filter((key) => key !== keyToRemove), + ); + // Reset all errors because of alter elements list. + setLocalErrors({}); + }; + /** * Remove a specific field. * @param fieldId string @@ -192,16 +222,6 @@ export default function DynamicFields({ setFields((prev) => prev.filter((field) => field.id !== fieldId)); }; - /** - * Remove sensitive field list. - * @param keyToRemove string - */ - const removeSensitiveField = (keyToRemove: string): void => { - setOriginalConfigKeys(prev => prev.filter((key) => key !== keyToRemove)); - // Reset all errors because of alter elements list. - setLocalErrors({}); - }; - /** * Save the new order. * @param event DragEndEvent @@ -211,8 +231,12 @@ export default function DynamicFields({ const { active, over } = event; if (!over || active.id === over.id) return; - const oldIndex = sortedFields.findIndex((f) => f.id === Number(active.id)); - const newIndex = sortedFields.findIndex((f) => f.id === Number(over.id)); + const oldIndex = sortedFields.findIndex( + (f) => f.id === Number(active.id), + ); + const newIndex = sortedFields.findIndex( + (f) => f.id === Number(over.id), + ); if (oldIndex < 0 || newIndex < 0) return; setFields((prev) => { @@ -226,15 +250,17 @@ export default function DynamicFields({ /** * Remove all local ids. - * @param fields ConfigInternalField[] + * @param currentFields ConfigInternalField[] * @returns */ - const removeIds = (fields: ConfigInternalField[]): ConfigField[] => { - return fields.map(({ id, children, ...rest }) => ({ - ...rest, - ...(children ? { children: removeIds(children) } : {}), + const removeIds = (currentFields: ConfigInternalField[]): ConfigField[] => { + // Delete the id, keep only the children if they are present, and keep the rest. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + return currentFields.map(({ id, children, ...rest }) => ({ + ...rest, + ...(children ? { children: removeIds(children) } : {}), })) as ConfigField[]; - } + }; // Export to parent only if payload differs with prevValueRef. useEffect(() => { @@ -244,11 +270,13 @@ export default function DynamicFields({ setData(name, payload); prevValueRef.current = payloadStr; } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [fields]); // Update fields when copying config from another locale. useEffect(() => { setFields(() => addIdsRecursively(value ?? [])); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedConfig]); return ( @@ -267,7 +295,9 @@ export default function DynamicFields({ onDragEnd={handleDragEnd} > String(field.id))} + items={sortedFields.map((field) => + String(field.id), + )} strategy={verticalListSortingStrategy} > {sortedFields.map((field, index) => ( @@ -300,7 +330,11 @@ export default function DynamicFields({ )} - +
); diff --git a/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx b/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx index baa09f1d..c2bdb1ac 100644 --- a/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx +++ b/resources/ts/back/Components/PageConfigs/ExportConfigJson.tsx @@ -4,53 +4,53 @@ import { FileDownIcon } from "lucide-react"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; type ExportConfigJsonProps = { - // The data in string. - data: T; - // Name of the downloaded file. - filename?: string; - // String present in the tooltip. - tooltipContent: string; - // Disable the button or not. - disabled?: boolean; + // The data in string. + data: T; + // Name of the downloaded file. + filename?: string; + // String present in the tooltip. + tooltipContent: string; + // Disable the button or not. + disabled?: boolean; }; export default function ExportConfigJson({ - data, - filename = "config.json", - tooltipContent, - disabled = false, + data, + filename = "config.json", + tooltipContent, + disabled = false, }: ExportConfigJsonProps) { - const handleExport = () => { - try { - // Transform data into json structure. - const json = JSON.stringify(data, null); + const handleExport = () => { + try { + // Transform data into json structure. + const json = JSON.stringify(data, null); - // Create blob from the json. - const blob = new Blob([json], { - type: "application/json;charset=utf-8", - }); + // Create blob from the json. + const blob = new Blob([json], { + type: "application/json;charset=utf-8", + }); - // Creates a link on the fly and opens it. - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = filename; - link.click(); - URL.revokeObjectURL(url); - } catch (error) { - console.error("Error during JSON export:", error); - } - }; + // Creates a link on the fly and opens it. + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = filename; + link.click(); + URL.revokeObjectURL(url); + } catch (error) { + console.error("Error during JSON export:", error); + } + }; - return ( - } - tooltipContent={tooltipContent} - type="button" - variant="outline" - size="icon" - disabled={disabled} - onClick={handleExport} - /> - ); + return ( + } + tooltipContent={tooltipContent} + type="button" + variant="outline" + size="icon" + disabled={disabled} + onClick={handleExport} + /> + ); } diff --git a/resources/ts/back/Components/PageConfigs/FieldGroup.tsx b/resources/ts/back/Components/PageConfigs/FieldGroup.tsx index e1755321..67ac6e85 100644 --- a/resources/ts/back/Components/PageConfigs/FieldGroup.tsx +++ b/resources/ts/back/Components/PageConfigs/FieldGroup.tsx @@ -1,27 +1,28 @@ +// * Packages import { Dispatch, SetStateAction, useState } from "react"; import { - DndContext, - closestCenter, - useSensor, - useSensors, - PointerSensor, - DragEndEvent, + DndContext, + closestCenter, + useSensor, + useSensors, + PointerSensor, + DragEndEvent, } from "@dnd-kit/core"; import { - SortableContext, - verticalListSortingStrategy, - arrayMove, - useSortable, + SortableContext, + verticalListSortingStrategy, + arrayMove, + useSortable, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { TrashIcon, GripVerticalIcon, CheckIcon, CopyIcon } from "lucide-react"; import { usePage } from "@inertiajs/react"; // * Components shadcn import { - Accordion, - AccordionContent, - AccordionItem, - AccordionTrigger, + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, } from "@/components/ui/accordion"; import { Card, CardContent } from "@/components/ui/card"; // * Other @@ -29,368 +30,514 @@ import EnumSelect from "@/back/Components/Inputs/EnumSelect"; import SimpleString from "@/back/Components/Inputs/SimpleString"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import AddNewFieldBtn from "@/back/Components/PageConfigs/AddNewFieldBtn"; -import { ConfigField, ConfigInternalField, DynamicFieldTypes } from "@/back/types/global"; +import { + ConfigField, + ConfigInternalField, + DynamicFieldTypes, +} from "@/back/types/dynamic-pages"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; import { cn } from "@/lib/utils"; +/* eslint-disable no-unused-vars */ type FieldGroupProps = { - currentId: number; - currentIndex: number; - currentFieldKey: string; - parentFieldKey: string; - currentField: ConfigInternalField; - currentRequired: boolean; - currentDisabled: boolean; - getTransInput: ( - field: "type" | "key" | "label" | "validation" | "children", - id: number - ) => string; - updateField: (id: number, updatedField: Partial) => void; - removeField: (id: number) => void; - transDelete: string; - transDragAndDrop?: string; - sensitiveField: string[]; - removeSensitiveField: (key: string) => void; - localErrors: Record; - setLocalErrors: Dispatch>>; - parentAccordionState: string; - setParentAccordionState: (key: string) => void; - limitMaxChildren: number; -} + currentId: number; + currentIndex: number; + currentFieldKey: string; + parentFieldKey: string; + currentField: ConfigInternalField; + currentRequired: boolean; + currentDisabled: boolean; + getTransInput: ( + field: "type" | "key" | "label" | "validation" | "children", + id: number, + ) => string; + updateField: (id: number, updatedField: Partial) => void; + removeField: (id: number) => void; + transDelete: string; + transDragAndDrop?: string; + sensitiveField: string[]; + removeSensitiveField: (key: string) => void; + localErrors: Record; + setLocalErrors: Dispatch>>; + parentAccordionState: string; + setParentAccordionState: (key: string) => void; + limitMaxChildren: number; +}; +/* eslint-enable no-unused-vars */ export default function FieldGroup({ - currentId, - currentIndex, - currentFieldKey, - parentFieldKey, - currentField, - currentRequired, - currentDisabled, - getTransInput, - updateField, - removeField, - transDelete, - transDragAndDrop, - sensitiveField, - removeSensitiveField, - localErrors, - setLocalErrors, - parentAccordionState, - setParentAccordionState, - limitMaxChildren, + currentId, + currentIndex, + currentFieldKey, + parentFieldKey, + currentField, + currentRequired, + currentDisabled, + getTransInput, + updateField, + removeField, + transDelete, + transDragAndDrop, + sensitiveField, + removeSensitiveField, + localErrors, + setLocalErrors, + parentAccordionState, + setParentAccordionState, + limitMaxChildren, }: FieldGroupProps) { - // Drag & drop module for user interactions (mouse, touch, keyboard or other). - const sensors = useSensors(useSensor(PointerSensor)); + // Drag & drop module for user interactions (mouse, touch, keyboard or other). + const sensors = useSensors(useSensor(PointerSensor)); - // Provides the necessary props and helpers to make this item draggable and reorderable. - // Includes event listeners, accessibility attributes, DOM ref, drag transform/transition values, - // and a flag indicating whether the item is dragging. - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: String(currentId) }); + // Provides the necessary props and helpers to make this item draggable and reorderable. + // Includes event listeners, accessibility attributes, DOM ref, drag transform/transition values, + // and a flag indicating whether the item is dragging. + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id: String(currentId) }); - // Style applied to the sortable item: - // - handles drag movement (transform), - // - animations (transition), - // - and visual feedback (opacity, zIndex) while dragging. - const style = { - transform: CSS.Transform.toString(transform), - transition, - opacity: isDragging ? 0.5 : 1, - zIndex: isDragging ? 50 : 0, - }; - - // Get all enum values, labels and names. - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; - - // Set the current state of the accordion. - const [openIndex, setOpenIndex] = useState(""); - - // Get the current enum value. - const currentEnum = Object.values(enumDynamicFieldTypes).find( - (def) => def.value === currentField.type - ); - // Set a prefix related to the current enum. - const enumCurrentBase = `${currentEnum?.name}_`; - - // Set the editable part of the current key. - const [editableKey, setEditableKey] = useState(() => { - return (currentField.key.startsWith(enumCurrentBase)) ? currentField.key.replace(enumCurrentBase, "") : currentField.key; - }); - - // Set the complete key (prefix + editable) that will be sent to the backend. - const completeKey = `${enumCurrentBase}${editableKey}`; - - // Set the state of copying key. - const [copied, setCopied] = useState(false); - // Copy the complete key in the clipboard. - const handleClick = () => { - navigator.clipboard.writeText(completeKey); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }; - - /** - * Reorder the elements list. - * @param event DragEndEvent - * @return void - */ - const handleOnDragEnd = (event: DragEndEvent) => { - const { active, over } = event; - if (!over || active.id === over.id) return; - - const oldIndex = currentField.children?.findIndex((c) => String(c.id) === String(active.id)) ?? -1; - const newIndex = currentField.children?.findIndex((c) => String(c.id) === String(over.id)) ?? -1; - - if (oldIndex < 0 || newIndex < 0) return; - const reordered = arrayMove(currentField.children!, oldIndex, newIndex) - .map((child, index) => ({ - ...child, - order: index + 1, - })); - updateField(currentId, { children: reordered }); - }; - - /** - * Add a new field to the list. - * @return void - */ - const handleAddNewChild = () => { - const existing = currentField.children ?? []; - const maxOrder = Math.max(0, ...existing.map((field) => field.order ?? 0)) + 1; - const maxIndex = Math.max(0, ...existing.map((field) => field.id ?? 0)) + 1; - - const newChild: ConfigInternalField = { - id: maxIndex, - key: `${enumDynamicFieldTypes.string.name}_`, - label: "", - type: enumDynamicFieldTypes.string.value, - validation: enumDynamicFieldTypes.string.validation, - order: maxOrder, - children: [], + // Style applied to the sortable item: + // - handles drag movement (transform), + // - animations (transition), + // - and visual feedback (opacity, zIndex) while dragging. + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + zIndex: isDragging ? 50 : 0, }; - const newChildren = [...(currentField.children ?? []), newChild]; - updateField(currentId, { children: newChildren }); - }; - /** - * Remove a specific element from the list. - * @param childId number - * @return void - */ - const handleDeleteChild = (childId: number) => { - const children = (currentField.children ?? []); - const targetChild = children.filter((child) => child.id === childId)[0]; - removeSensitiveField(`${parentFieldKey}.${targetChild.key}`); - const childrenUpdated = children.filter( - (c) => c.id !== childId + // Get all enum values, labels and names. + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; + + // Set the current state of the accordion. + const [openIndex, setOpenIndex] = useState(""); + + // Get the current enum value. + const currentEnum = Object.values(enumDynamicFieldTypes).find( + (def) => def.value === currentField.type, ); - updateField(currentId, { children: childrenUpdated }); - }; + // Set a prefix related to the current enum. + const enumCurrentBase = `${currentEnum?.name}_`; - /** - * Update the input type. - * @param value string - * @return void - */ - const updatingType = (value: string) => { - const selectedType = Object.values(enumDynamicFieldTypes).find( - (def) => def.value === parseInt(value) + // Set the editable part of the current key. + const [editableKey, setEditableKey] = useState(() => { + return currentField.key.startsWith(enumCurrentBase) + ? currentField.key.replace(enumCurrentBase, "") + : currentField.key; + }); + + //* Translations + const transKeyAlreadyPresent = useTrans("validation.key_already_present"); + + // Set the complete key (prefix + editable) that will be sent to the backend. + const completeKey = `${enumCurrentBase}${editableKey}`; + + // Set the state of copying key. + const [copied, setCopied] = useState(false); + // Copy the complete key in the clipboard. + const handleClick = () => { + navigator.clipboard.writeText(completeKey); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + + /** + * Reorder the elements list. + * @param event DragEndEvent + * @return void + */ + const handleOnDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + if (!over || active.id === over.id) return; + + const oldIndex = + currentField.children?.findIndex( + (c) => String(c.id) === String(active.id), + ) ?? -1; + const newIndex = + currentField.children?.findIndex( + (c) => String(c.id) === String(over.id), + ) ?? -1; + + if (oldIndex < 0 || newIndex < 0) return; + const reordered = arrayMove( + currentField.children!, + oldIndex, + newIndex, + ).map((child, index) => ({ + ...child, + order: index + 1, + })); + updateField(currentId, { children: reordered }); + }; + + /** + * Add a new field to the list. + * @return void + */ + const handleAddNewChild = () => { + const existing = currentField.children ?? []; + const maxOrder = + Math.max(0, ...existing.map((field) => field.order ?? 0)) + 1; + const maxIndex = + Math.max(0, ...existing.map((field) => field.id ?? 0)) + 1; + + const newChild: ConfigInternalField = { + id: maxIndex, + key: `${enumDynamicFieldTypes.string.name}_`, + label: "", + type: enumDynamicFieldTypes.string.value, + validation: enumDynamicFieldTypes.string.validation, + order: maxOrder, + children: [], + }; + const newChildren = [...(currentField.children ?? []), newChild]; + updateField(currentId, { children: newChildren }); + }; + + /** + * Remove a specific element from the list. + * @param childId number + * @return void + */ + const handleDeleteChild = (childId: number) => { + const children = currentField.children ?? []; + const targetChild = children.filter((child) => child.id === childId)[0]; + removeSensitiveField(`${parentFieldKey}.${targetChild.key}`); + const childrenUpdated = children.filter((c) => c.id !== childId); + updateField(currentId, { children: childrenUpdated }); + }; + + /** + * Update the input type. + * @param value string + * @return void + */ + const updatingType = (value: string) => { + const selectedType = Object.values(enumDynamicFieldTypes).find( + (def) => def.value === Number(value), + ); + if (selectedType) { + const resetCommon = { + type: selectedType.value, + validation: selectedType.validation, + key: `${selectedType.name}_${editableKey}`, + children: undefined, + }; + updateField(currentId, resetCommon); + } + }; + + return ( +
+ + + key.startsWith( + `${currentFieldKey}.${currentIndex}`, + ), + ), + })} + > + + {/* HEADER */} +
+
+
+ + } + tooltipContent={transDragAndDrop} + className="cursor-grab touch-none h-full w-full" + type="button" + variant="outline" + size="icon" + disabled={parentAccordionState !== ""} + /* eslint-disable react/jsx-props-no-spreading */ + {...attributes} + {...listeners} + /* eslint-enable react/jsx-props-no-spreading */ + /> +
+
+ + + + + } + tooltipContent={ +
+

+ {str( + useTrans( + "back.config_complete_label", + ), + ) + .ucFirst() + .value()} +

+

+ {completeKey} +

+
+ } + type="button" + variant="ghost" + size="icon" + onClick={handleClick} + /> + + } + tooltipContent={transDelete} + type="button" + variant="destructive" + size="icon" + onClick={() => { + if ( + parentAccordionState === + `item-${currentId}` + ) { + setParentAccordionState(""); + } + removeField(currentId); + }} + /> +
+
+
+ + {currentField.label.length + ? currentField.label + : `Champs n°${currentIndex + 1}`} + +
+
+ {/* CONTENT */} + +
+ + updateField(currentId, { label: value }) + } + parentErrors={localErrors} + /> + {!sensitiveField.includes( + `${parentFieldKey}.${completeKey}`, + ) && ( + <> + { + const newCompleteKey = `${enumCurrentBase}${value}`; + if ( + sensitiveField.includes( + `${parentFieldKey}.${newCompleteKey}`, + ) + ) { + setLocalErrors((prev) => ({ + ...prev, + [`${currentFieldKey}.${currentIndex}.key`]: + transKeyAlreadyPresent, + })); + } else { + setLocalErrors((prev) => { + const { + [`${currentFieldKey}.${currentIndex}.key`]: + // eslint-disable-next-line @typescript-eslint/no-unused-vars + removedKey, + ...rest + } = prev; + return rest; + }); + setEditableKey(value); + updateField(currentId, { + key: newCompleteKey, + }); + } + }} + pattern="^[a-z0-9]+(?:[\-_][a-z0-9]+)*$" + parentErrors={localErrors} + /> + { + updatingType(value); + }} + required={currentRequired} + disabled={currentDisabled} + parentErrors={localErrors} + /> + + )} + + updateField(currentId, { + validation: value, + }) + } + required={currentRequired} + disabled={currentDisabled} + parentErrors={localErrors} + /> +
+ {/* CHILDREN */} + {currentEnum?.isarray && ( + + + String(c.id))} + strategy={ + verticalListSortingStrategy + } + > + {(currentField.children ?? []).map( + ( + child: ConfigInternalField, + i: number, + ) => ( + , + ) => { + const newChildren = + ( + currentField.children ?? + [] + ).map((c) => + c.id === + childId + ? { + ...c, + ...updatedChild, + } + : c, + ); + updateField( + currentId, + { + children: + newChildren, + }, + ); + }} + removeField={ + handleDeleteChild + } + transDelete={ + transDelete + } + transDragAndDrop={ + transDragAndDrop + } + sensitiveField={ + sensitiveField + } + removeSensitiveField={ + removeSensitiveField + } + localErrors={ + localErrors + } + setLocalErrors={ + setLocalErrors + } + parentAccordionState={ + openIndex + } + setParentAccordionState={ + setOpenIndex + } + limitMaxChildren={ + limitMaxChildren + } + /> + ), + )} + + + + + )} +
+
+
+
+
); - if (selectedType) { - const resetCommon = { - type: selectedType.value, - validation: selectedType.validation, - key: `${selectedType.name}_${editableKey}`, - children: undefined, - }; - updateField(currentId, resetCommon); - } - } - - return ( -
- - key.startsWith(`${currentFieldKey}.${currentIndex}`)), - })}> - - {/* HEADER */} -
-
-
- } - tooltipContent={transDragAndDrop} - className="cursor-grab touch-none h-full w-full" - type="button" - variant="outline" - size="icon" - disabled={parentAccordionState !== ""} - {...attributes} - {...listeners} - /> -
-
- - - - - } - tooltipContent={ -
-

{str(useTrans("back.config_complete_label")).ucFirst().value()}

-

{completeKey}

-
- } - type="button" - variant="ghost" - size="icon" - onClick={handleClick} - /> - } - tooltipContent={transDelete} - type="button" - variant="destructive" - size="icon" - onClick={() => { - if (parentAccordionState === `item-${currentId}`) { - setParentAccordionState("") - } - removeField(currentId); - }} - /> -
-
-
- - {currentField.label.length ? currentField.label : `Champs n°${currentIndex + 1}`} - -
-
- {/* CONTENT */} - -
- updateField(currentId, { label: value })} - parentErrors={localErrors} - /> - {!sensitiveField.includes(`${parentFieldKey}.${completeKey}`) && ( - <> - { - const newCompleteKey = `${enumCurrentBase}${value}`; - if (sensitiveField.includes(`${parentFieldKey}.${newCompleteKey}`)) { - setLocalErrors(prev => ({ - ...prev, - [`${currentFieldKey}.${currentIndex}.key`]: useTrans('validation.key_already_present'), - })); - } else { - setLocalErrors((prev) => { - const { [`${currentFieldKey}.${currentIndex}.key`]: _, ...rest } = prev; - return rest; - }); - setEditableKey(value) - updateField(currentId, { key: newCompleteKey }) - } - }} - pattern="^[a-z0-9]+(?:[\-_][a-z0-9]+)*$" - parentErrors={localErrors} - /> - { - updatingType(value); - }} - required={currentRequired} - disabled={currentDisabled} - parentErrors={localErrors} - /> - - )} - updateField(currentId, { validation: value })} - required={currentRequired} - disabled={currentDisabled} - parentErrors={localErrors} - /> -
- {/* CHILDREN */} - {currentEnum?.isarray && ( - <> - - - String(c.id))} - strategy={verticalListSortingStrategy} - > - {(currentField.children ?? []).map((child: ConfigInternalField, i: number) => ( - ) => { - const newChildren = (currentField.children ?? []).map((c) => - c.id === childId ? { ...c, ...updatedChild } : c - ); - updateField(currentId, { children: newChildren }); - }} - removeField={handleDeleteChild} - transDelete={transDelete} - transDragAndDrop={transDragAndDrop} - sensitiveField={sensitiveField} - removeSensitiveField={removeSensitiveField} - localErrors={localErrors} - setLocalErrors={setLocalErrors} - parentAccordionState={openIndex} - setParentAccordionState={setOpenIndex} - limitMaxChildren={limitMaxChildren} - /> - ))} - - - - - - )} -
-
-
-
-
- ); } diff --git a/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx b/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx index 354395d5..fdba1747 100644 --- a/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx +++ b/resources/ts/back/Components/PageConfigs/ImportConfigJson.tsx @@ -1,16 +1,29 @@ // * Packages -import { useRef, useState } from "react"; -import { JsonEditor, IconReplacements, LocalisedStrings } from "json-edit-react"; -import { CheckIcon, ChevronDownIcon, CopyIcon, PencilIcon, PlusIcon, Trash2Icon, UploadIcon, XIcon } from "lucide-react"; +import { ChangeEvent, DragEvent, useRef, useState } from "react"; +import { + JsonEditor, + IconReplacements, + LocalisedStrings, +} from "json-edit-react"; +import { + CheckIcon, + ChevronDownIcon, + CopyIcon, + PencilIcon, + PlusIcon, + Trash2Icon, + UploadIcon, + XIcon, +} from "lucide-react"; import z from "zod"; // * Components shadcn import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, - DialogFooter, - DialogDescription, + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, + DialogDescription, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; // * Other @@ -24,292 +37,344 @@ import useTrans from "@/hooks/use-translations"; type JsonPrimitive = string | number | boolean | null; type JsonObject = { - [key: string]: JsonPrimitive | JsonObject | JsonObject[]; + [key: string]: JsonPrimitive | JsonObject | JsonObject[]; }; type ImportConfigJsonProps = { - onConfirm: (data: JsonObject[], overwrite: boolean) => void; + // eslint-disable-next-line no-unused-vars + onConfirm: (data: JsonObject[], overwrite: boolean) => void; }; // Zod schemas. const jsonObjectSchema: z.ZodType = z.lazy(() => - z.record( - z.string(), - z.union([ - z.string(), - z.number(), - z.boolean(), - z.null(), - jsonObjectSchema, - z.array(jsonObjectSchema), - ]) - ) + z.record( + z.string(), + z.union([ + z.string(), + z.number(), + z.boolean(), + z.null(), + jsonObjectSchema, + z.array(jsonObjectSchema), + ]), + ), ); const jsonArraySchema = z.array(jsonObjectSchema); -export default function ImportConfigJson({ - onConfirm, -}: ImportConfigJsonProps) { - // Json content. - const [jsonText, setJsonText] = useState([]); +export default function ImportConfigJson({ onConfirm }: ImportConfigJsonProps) { + // Json content. + const [jsonText, setJsonText] = useState([]); - // Modale state. - const [isOpen, setIsOpen] = useState(false); - // Event state. - const [isDragging, setIsDragging] = useState(false); - // Overwrite state. - const [overwrite, setOverwrite] = useState(false); + // Modale state. + const [isOpen, setIsOpen] = useState(false); + // Event state. + const [isDragging, setIsDragging] = useState(false); + // Overwrite state. + const [overwrite, setOverwrite] = useState(false); - // Local errors. - const [globalErrors, setGlobalErrors] = useState>({}); - const [editorErrors, setEditorErrors] = useState>({}); + // Local errors. + const [globalErrors, setGlobalErrors] = useState>( + {}, + ); + const [editorErrors, setEditorErrors] = useState>( + {}, + ); - // Input file reference. - const inputRef = useRef(null); + // Input file reference. + const inputRef = useRef(null); - // Maximum file size accepted (2MB). - const maxSize = 2 * 1024 * 1024; + // Maximum file size accepted (2MB). + const maxSize = 2 * 1024 * 1024; - /** - * Get translation of specific key. - * - * @param key string - * @return string - */ - const getTranslation = (key: string): string => str(useTrans(key)).ucFirst().value(); + /** + * Get translation of specific key. + * + * @param key string + * @return string + */ + const useGetTranslation = (key: string): string => + str(useTrans(key)).ucFirst().value(); - // Custom icons. - const icons: IconReplacements = { - add: , - edit: , - delete: , - copy: , - ok: , - cancel: , - chevron: , - }; + const transJsonEditorMaxSize = useTrans( + "back.json_editor.validation.max_size", + { + params: { value: "2MB" }, + }, + ); + const transJsonEditorMimes = useTrans("back.json_editor.validation.mimes", { + params: { values: ".json" }, + }); + const transJsonEditorInvalidFileJson = useTrans( + "back.json_editor.validation.invalid_file_json", + ); + const transInvalidContentJson = useTrans( + "back.json_editor.validation.invalid_content_json", + ); - // Custom translations. - const translations: LocalisedStrings = { - ITEM_SINGLE: getTranslation('back.json_editor.item_single'), - ITEMS_MULTIPLE: getTranslation('back.json_editor.item_multiple'), - KEY_NEW: getTranslation('back.json_editor.key_new'), - KEY_SELECT: getTranslation('back.json_editor.key_select'), - NO_KEY_OPTIONS: getTranslation('back.json_editor.no_key_options'), - ERROR_KEY_EXISTS: getTranslation('back.json_editor.error_key_exists'), - ERROR_INVALID_JSON: getTranslation('back.json_editor.error_invalid_json'), - ERROR_UPDATE: getTranslation('back.json_editor.error_update'), - ERROR_DELETE: getTranslation('back.json_editor.error_delete'), - ERROR_ADD: getTranslation('back.json_editor.error_add'), - DEFAULT_STRING: getTranslation('back.json_editor.default_string'), - DEFAULT_NEW_KEY: getTranslation('back.json_editor.default_new_key'), - SHOW_LESS: getTranslation('back.json_editor.show_less'), - EMPTY_STRING: getTranslation('back.json_editor.empty_string'), - TOOLTIP_COPY: getTranslation('back.json_editor.copy'), - TOOLTIP_EDIT: getTranslation('back.json_editor.edit'), - TOOLTIP_DELETE: getTranslation('back.json_editor.delete'), - TOOLTIP_ADD: getTranslation('back.json_editor.add'), - }; + // Custom icons. + const icons: IconReplacements = { + add: , + edit: , + delete: , + copy: , + ok: , + cancel: , + chevron: , + }; - /** - * Simulates click on input file. - * - * @return void - */ - const openFilePicker = (): void => { - inputRef.current?.click(); - }; + // Custom translations. + const translations: LocalisedStrings = { + ITEM_SINGLE: useGetTranslation("back.json_editor.item_single"), + ITEMS_MULTIPLE: useGetTranslation("back.json_editor.item_multiple"), + KEY_NEW: useGetTranslation("back.json_editor.key_new"), + KEY_SELECT: useGetTranslation("back.json_editor.key_select"), + NO_KEY_OPTIONS: useGetTranslation("back.json_editor.no_key_options"), + ERROR_KEY_EXISTS: useGetTranslation( + "back.json_editor.error_key_exists", + ), + ERROR_INVALID_JSON: useGetTranslation( + "back.json_editor.error_invalid_json", + ), + ERROR_UPDATE: useGetTranslation("back.json_editor.error_update"), + ERROR_DELETE: useGetTranslation("back.json_editor.error_delete"), + ERROR_ADD: useGetTranslation("back.json_editor.error_add"), + DEFAULT_STRING: useGetTranslation("back.json_editor.default_string"), + DEFAULT_NEW_KEY: useGetTranslation("back.json_editor.default_new_key"), + SHOW_LESS: useGetTranslation("back.json_editor.show_less"), + EMPTY_STRING: useGetTranslation("back.json_editor.empty_string"), + TOOLTIP_COPY: useGetTranslation("back.json_editor.copy"), + TOOLTIP_EDIT: useGetTranslation("back.json_editor.edit"), + TOOLTIP_DELETE: useGetTranslation("back.json_editor.delete"), + TOOLTIP_ADD: useGetTranslation("back.json_editor.add"), + }; - /** - * Set json from content file. - * - * @param file File - * @return Promise - */ - const processFile = async (file: File): Promise => { - if (file.size > maxSize) { - setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.max_size', { - params: { value: '2MB' } - }) })); - return; - } + /** + * Simulates click on input file. + * + * @return void + */ + const openFilePicker = (): void => { + inputRef.current?.click(); + }; + /** + * Set json from content file. + * + * @param file File + * @return Promise + */ + const processFile = async (file: File): Promise => { + if (file.size > maxSize) { + setGlobalErrors((prev) => ({ + ...prev, + "global-error": transJsonEditorMaxSize, + })); + return; + } - if (!file.name.endsWith(".json")) { - setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.mimes', { - params: { values: '.json' } - }) })); - return; - } + if (!file.name.endsWith(".json")) { + setGlobalErrors((prev) => ({ + ...prev, + "global-error": transJsonEditorMimes, + })); + return; + } - try { - const text = await file.text(); - const parsed = JSON.parse(text); + try { + const text = await file.text(); + const parsed = JSON.parse(text); - // Validate json with zod. - jsonArraySchema.parse(parsed); + // Validate json with zod. + jsonArraySchema.parse(parsed); - setJsonText(parsed); - setGlobalErrors({}); - setIsOpen(true); - } catch { - setGlobalErrors(prev => ({ ...prev, 'global-error': useTrans('back.json_editor.validation.invalid_file_json') })); - } - }; + setJsonText(parsed); + setGlobalErrors({}); + setIsOpen(true); + } catch { + setGlobalErrors((prev) => ({ + ...prev, + "global-error": transJsonEditorInvalidFileJson, + })); + } + }; - /** - * Action when changing file. - * - * @param event - * @return void - */ - const handleFileChange = (e: React.ChangeEvent): void => { - const file = e.target.files?.[0]; - if (file) processFile(file); - }; + /** + * Reset component. + * + * @return void + */ + const resetComponent = (): void => { + setIsOpen(false); + setTimeout(() => { + setJsonText([]); + setGlobalErrors({}); + setEditorErrors({}); + setOverwrite(false); + }, 200); + }; - /** - * Action when droping file. - * - * @param event - * @return void - */ - const handleDrop = (event: React.DragEvent): void => { - event.preventDefault(); - setIsDragging(false); + /** + * Action when changing file. + * + * @param event + * @return void + */ + const handleFileChange = (e: ChangeEvent): void => { + const file = e.target.files?.[0]; + if (file) processFile(file); + }; - const file = event.dataTransfer.files?.[0]; - if (file) processFile(file); - }; + /** + * Action when droping file. + * + * @param event + * @return void + */ + const handleDrop = (event: DragEvent): void => { + event.preventDefault(); + setIsDragging(false); - /** - * Confirm the json. - * - * @return void - */ - const handleConfirm = (): void => { - try { - // Validate json with zod. - jsonArraySchema.parse(jsonText); - onConfirm(jsonText, overwrite); - resetComponent(); - } catch { - setEditorErrors(prev => ({ ...prev, 'editor-error': useTrans('back.json_editor.validation.invalid_content_json') })); - } - }; + const file = event.dataTransfer.files?.[0]; + if (file) processFile(file); + }; - /** - * Reset component. - * - * @return void - */ - const resetComponent = (): void => { - setIsOpen(false); - setTimeout(() => { - setJsonText([]); - setGlobalErrors({}); - setEditorErrors({}); - setOverwrite(false); - }, 200); - } + /** + * Confirm the json. + * + * @return void + */ + const handleConfirm = (): void => { + try { + // Validate json with zod. + jsonArraySchema.parse(jsonText); + onConfirm(jsonText, overwrite); + resetComponent(); + } catch { + setEditorErrors((prev) => ({ + ...prev, + "editor-error": transInvalidContentJson, + })); + } + }; - return ( - <> - {/* Dropzone */} - - - {/* Modal */} - - - - {getTranslation('back.json_editor.modal_title')} - - {getTranslation('back.json_editor.modal_description')} - - -
- {/* JSON editor */} - setJsonText(val as JsonObject[])} - icons={icons} - translations={translations} - showIconTooltips={true} - collapseAnimationTime={200} - maxWidth="100%" - searchFilter="all" - /> -
- - - setOverwrite(value)} - /> -
- + {/* Dropzone */} +
-
-
-
- - ); + 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", + { "text-accent-foreground bg-accent": isDragging }, + { + "border-destructive mb-1.5": + Object.values(globalErrors).length, + }, + )} + onClick={openFilePicker} + onDragOver={(e) => { + e.preventDefault(); + setIsDragging(true); + }} + onDragLeave={() => setIsDragging(false)} + // @ts-expect-error function return are not compatible for ts + onDrop={handleDrop} + > + +
+ +

+ {useTrans("back.json_editor.select-file")} +

+ + {str( + useTrans("back.json_editor.allowed_format", { + params: { format: ".json" }, + }), + ) + .ucFirst() + .value()} + .{" "} + {str( + useTrans("back.json_editor.rules_weight", { + params: { size: "2MB" }, + }), + ) + .ucFirst() + .value()} + +
+ + + {/* Modal */} + + + + + {useGetTranslation("back.json_editor.modal_title")} + + + {useGetTranslation( + "back.json_editor.modal_description", + )} + + +
+ {/* JSON editor */} + setJsonText(val as JsonObject[])} + icons={icons} + translations={translations} + showIconTooltips + collapseAnimationTime={200} + maxWidth="100%" + searchFilter="all" + /> +
+ + + setOverwrite(value)} + /> +
+ + +
+
+
+
+ + ); } diff --git a/resources/ts/back/Components/Pagination/PaginationPerPage.tsx b/resources/ts/back/Components/Pagination/PaginationPerPage.tsx index 5db7cd28..4695f0fa 100644 --- a/resources/ts/back/Components/Pagination/PaginationPerPage.tsx +++ b/resources/ts/back/Components/Pagination/PaginationPerPage.tsx @@ -20,7 +20,8 @@ export default function PaginationPerPage({ perPage: number; total: number; }) { - const enumItemsPerPagination = usePage().props.enumItemsPerPagination as Record< + const enumItemsPerPagination = usePage().props + .enumItemsPerPagination as Record< string, { label: string; name: string; value: number } >; diff --git a/resources/ts/back/Components/Pagination/PaginationWrapper.tsx b/resources/ts/back/Components/Pagination/PaginationWrapper.tsx index 83c6f8a9..96e15a48 100644 --- a/resources/ts/back/Components/Pagination/PaginationWrapper.tsx +++ b/resources/ts/back/Components/Pagination/PaginationWrapper.tsx @@ -2,22 +2,13 @@ import { Paginator } from "@/back/types/global"; import PaginationCustom from "@/back/Components/Pagination/PaginationCustom"; import PaginationPerPage from "@/back/Components/Pagination/PaginationPerPage"; -import useTrans from "@/hooks/use-translations"; +import { GetTranslation } from "@/lib/utils"; export default function PaginationWrapper({ modelsPaginate, }: { modelsPaginate: Paginator; }) { - const GetTranslation = () => { - return useTrans("pagination.informations", { - params: { - total: String(modelsPaginate.total), - page: String(modelsPaginate.last_page), - }, - choice: modelsPaginate.last_page > 1 ? 2 : 1, - }); - }; return ( modelsPaginate.total > 1 && (
@@ -26,7 +17,13 @@ export default function PaginationWrapper({ total={modelsPaginate.total} />

- {GetTranslation()} + {GetTranslation("pagination.informations", { + params: { + total: String(modelsPaginate.total), + page: String(modelsPaginate.last_page), + }, + choice: modelsPaginate.last_page > 1 ? 2 : 1, + })}

diff --git a/resources/ts/back/Components/SoftdeleteWarning.tsx b/resources/ts/back/Components/SoftdeleteWarning.tsx index bbe3aeb8..094a6335 100644 --- a/resources/ts/back/Components/SoftdeleteWarning.tsx +++ b/resources/ts/back/Components/SoftdeleteWarning.tsx @@ -9,17 +9,14 @@ import useTrans from "@/hooks/use-translations"; export default function SoftdeleteWarning() { return ( <> - + - {useTrans('back.warning')} + {useTrans("back.warning")} -

{useTrans('back.warning_trash')}

+

{useTrans("back.warning_trash")}

- + ); } diff --git a/resources/ts/back/Components/SubmitButton.tsx b/resources/ts/back/Components/SubmitButton.tsx index 49ed37ff..039dc4df 100644 --- a/resources/ts/back/Components/SubmitButton.tsx +++ b/resources/ts/back/Components/SubmitButton.tsx @@ -1,14 +1,15 @@ +// * Packages +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import str from "@/hooks/use-string"; -import BtnOptionnalLinkWithTooltip from "./BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; -const SubmitButton = ({ +function SubmitButton({ isInDialog = false, - modelTrans + modelTrans, }: { - isInDialog?: boolean, - modelTrans: string -}) => { + isInDialog?: boolean; + modelTrans: string; +}) { return ( - ) + ); } export default SubmitButton; diff --git a/resources/ts/back/Components/Table/DataTable.tsx b/resources/ts/back/Components/Table/DataTable.tsx index b8b08469..5fad4da5 100644 --- a/resources/ts/back/Components/Table/DataTable.tsx +++ b/resources/ts/back/Components/Table/DataTable.tsx @@ -62,10 +62,10 @@ export default function DataTable({ {header.isPlaceholder ? null : flexRender( - header.column.columnDef - .header, - header.getContext(), - )} + header.column.columnDef + .header, + header.getContext(), + )} ); })} @@ -82,7 +82,9 @@ export default function DataTable({ table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => ( ({ actions={actions} modelRoute={modelRoute} model={row.original as Model} - inDialog={true} + inDialog /> )} diff --git a/resources/ts/back/Components/Table/DataTableFilterButton.tsx b/resources/ts/back/Components/Table/DataTableFilterButton.tsx index db7c2f36..cb8e8e8e 100644 --- a/resources/ts/back/Components/Table/DataTableFilterButton.tsx +++ b/resources/ts/back/Components/Table/DataTableFilterButton.tsx @@ -1,5 +1,10 @@ // * Packages -import { ArrowDownIcon, ArrowUpIcon, ArrowUpDownIcon, EraserIcon } from "lucide-react"; +import { + ArrowDownIcon, + ArrowUpIcon, + ArrowUpDownIcon, + EraserIcon, +} from "lucide-react"; import { router } from "@inertiajs/react"; // * Components shadcn import { Button } from "@/components/ui/button"; @@ -24,7 +29,11 @@ export default function DataTableFilterButton({ const params = new URLSearchParams(url.search); const sortDescCondition = params.get("sort_col") === field && - params.get("sort_way") === "desc" ? : ; + params.get("sort_way") === "desc" ? ( + + ) : ( + + ); const filterButtonTrans = useTrans("back.table_filter_button", { params: { field: label ?? "" }, }); @@ -39,7 +48,9 @@ export default function DataTableFilterButton({
) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -138,7 +117,7 @@ export default function Index({ header: () => (

{str( - useTrans("models.classes.company-sector", { + GetTranslation("models.classes.company-sector", { choice: 1, }), ) @@ -168,9 +147,9 @@ export default function Index({ } tooltipContent={

- {useTrans("back.access_model", { + {GetTranslation("back.access_model", { params: { - model: useTrans( + model: GetTranslation( "models.classes.company-sector", { choice: 1 }, ), @@ -190,7 +169,7 @@ export default function Index({

) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -199,11 +178,11 @@ export default function Index({ accessorKey: "coords", header: () => (

- {str(useTrans("validation.custom.latitude")) + {str(GetTranslation("validation.custom.latitude")) .ucFirst() .value()} / - {str(useTrans("validation.custom.longitude")) + {str(GetTranslation("validation.custom.longitude")) .ucFirst() .value()}

@@ -220,7 +199,7 @@ export default function Index({ accessorKey: "published", header: ({ column }: { column: { id: string } }) => ( )} {str( - useTrans( + GetTranslation( row.getValue("published") ? "back.yes" : "back.no", ), ) @@ -250,7 +229,58 @@ export default function Index({ ), }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, ]; +}; + +export default function Index({ + companyModels, + searchFields, + modelName, +}: { + companyModels: Resource; + searchFields: string; + modelName: string; +}) { + const { appEnv, auth } = usePage().props as unknown as { + appEnv: AppEnv; + auth: AuthProp; + }; + const { viewAny, viewTrash, create } = auth.policies.companies; + const { viewAny: viewAnyCompanyActivities } = + auth.policies.companyActivities; + const { viewAny: viewAnyCompanySectors } = auth.policies.companySectors; + const isArchiveRoute = route().current(`back.${modelName}.trash`); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; + const columns = getColumns( + appEnv, + viewAnyCompanyActivities, + viewAnyCompanySectors, + ); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, @@ -262,7 +292,7 @@ export default function Index({ const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) .ucFirst() .value(); - + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -271,14 +301,28 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transBackToList}

} />
) ); }; + const transAccessToCompanyActivity = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.company-activity", { choice: 2 }), + }, + }); + const transAccessToCompanySector = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.company-sector", { choice: 2 }), + }, + }); + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -288,16 +332,7 @@ export default function Index({ link={route(`back.company-activities.index`)} content={} tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.company-activity", - { choice: 2 }, - ), - }, - })} -

+

{transAccessToCompanyActivity}

} variant="outline" /> @@ -306,18 +341,7 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.company-sector", - { choice: 2 }, - ), - }, - })} -

- } + tooltipContent={

{transAccessToCompanySector}

} variant="outline" /> )} @@ -325,27 +349,15 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "back.archived_entries", - ), - }, - })} -

- } - variant={"outline"} + tooltipContent={

{transAccessToArchived}

} + variant="outline" /> )} {create && ( } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transAddEntry}

} /> )}
diff --git a/resources/ts/back/Pages/Companies/Show.tsx b/resources/ts/back/Pages/Companies/Show.tsx index 30cc4e1d..9b81dd37 100644 --- a/resources/ts/back/Pages/Companies/Show.tsx +++ b/resources/ts/back/Pages/Companies/Show.tsx @@ -9,108 +9,125 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, SingleResource } from "@/back/types/global"; import { - AppEnv, - AuthProp, CompanyActivityModel, CompanyModel, CompanySectorModel, - SingleResource, -} from "@/back/types/global"; +} from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -export default function Show({ data, modelName }: { data: SingleResource, modelName: string }) { - const { appEnv, auth } = usePage().props as unknown as { - appEnv: AppEnv; - auth: AuthProp; - }; - const { viewAny } = auth.policies.companies; - const companyModel = data.data as CompanyModel; - const actionModels = [ - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const singularModelName = str(modelName).singular().value(); - const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, - }); - const columns = [ +const getColumns = (appEnv: AppEnv, auth: AuthProp) => { + return [ { accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "logo", - header: str(useTrans("validation.custom.logo")).ucFirst().value(), + header: str(GetTranslation("validation.custom.logo")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "responsable", - header: str(useTrans("validation.custom.responsable")).ucFirst().value(), + header: str(GetTranslation("validation.custom.responsable")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "url", - header: str(useTrans("validation.custom.url")).ucFirst().value(), + header: str(GetTranslation("validation.custom.url")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "informations", - header: str(useTrans("validation.custom.informations")).ucFirst().value(), + header: str(GetTranslation("validation.custom.informations")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "employees", - header: str(useTrans("validation.custom.employees")).ucFirst().value(), + header: str(GetTranslation("validation.custom.employees")) + .ucFirst() + .value(), cell: ({ value }: { value: number }) => value, }, { accessorKey: "latitude", - header: str(useTrans("validation.custom.latitude")).ucFirst().value(), + header: str(GetTranslation("validation.custom.latitude")) + .ucFirst() + .value(), cell: ({ value }: { value: number }) => value, }, { accessorKey: "longitude", - header: str(useTrans("validation.custom.longitude")).ucFirst().value(), + header: str(GetTranslation("validation.custom.longitude")) + .ucFirst() + .value(), cell: ({ value }: { value: number }) => value, }, { accessorKey: "company_activity", - header: str(useTrans('models.classes.company-activity', { choice: 1 })).ucFirst().value(), - cell: ({ value }: { value: CompanyActivityModel }) => auth.policies.companyActivities.viewAny ? ( - - - {value.name[appEnv.locale]} - - } - tooltipContent={ -

{useTrans("back.access_model", { - params: { - model: useTrans('models.classes.company-activity', { choice: 1 }) - } - })}

- } - type="button" - size="default" - variant="secondary" - /> - ) : {value.name[appEnv.locale]} + header: str( + GetTranslation("models.classes.company-activity", { + choice: 1, + }), + ) + .ucFirst() + .value(), + cell: ({ value }: { value: CompanyActivityModel }) => + auth.policies.companyActivities.viewAny ? ( + + + {value.name[appEnv.locale]} + + } + tooltipContent={ +

+ {GetTranslation("back.access_model", { + params: { + model: GetTranslation( + "models.classes.company-activity", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + {value.name[appEnv.locale]} + ), }, { accessorKey: "company_sector", - header: str(useTrans('models.classes.company-sector', { choice: 1 })).ucFirst().value(), - cell: ({ value }: { value: CompanySectorModel|null }) => value !== null && ( - auth.policies.companySectors.viewAny ? ( + header: str( + GetTranslation("models.classes.company-sector", { choice: 1 }), + ) + .ucFirst() + .value(), + cell: ({ value }: { value: CompanySectorModel | null }) => + value !== null && + (auth.policies.companySectors.viewAny ? ( @@ -118,59 +135,95 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN } tooltipContent={ -

{useTrans("back.access_model", { - params: { - model: useTrans('models.classes.company-sector', { choice: 1 }) - } - })}

+

+ {GetTranslation("back.access_model", { + params: { + model: GetTranslation( + "models.classes.company-sector", + { choice: 1 }, + ), + }, + })} +

} type="button" size="default" variant="secondary" /> - ) : {value.name[appEnv.locale]} - ) + ) : ( + {value.name[appEnv.locale]} + )), }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; +export default function Show({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { appEnv, auth } = usePage().props as unknown as { + appEnv: AppEnv; + auth: AuthProp; + }; + const { viewAny } = auth.policies.companies; + const companyModel = data.data as CompanyModel; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; + const singularModelName = str(modelName).singular().value(); + const transTitle = useTrans("crud.helpers.visualization_model", { + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, + }); + const columns = getColumns(appEnv, auth); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
- + })} + />
); diff --git a/resources/ts/back/Pages/CompanyActivities/Index.tsx b/resources/ts/back/Pages/CompanyActivities/Index.tsx index 930124f6..93f7804f 100644 --- a/resources/ts/back/Pages/CompanyActivities/Index.tsx +++ b/resources/ts/back/Pages/CompanyActivities/Index.tsx @@ -2,10 +2,20 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; +import { + ArchiveIcon, + ArrowLeftIcon, + CheckIcon, + PlusIcon, + XIcon, +} from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; @@ -13,15 +23,127 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { Views } from "@/lib/utils"; -import { - AuthProp, - CompanyActivityModel, - Resource, -} from "@/back/types/global"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AuthProp, Resource } from "@/back/types/global"; +import { CompanyActivityModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "color", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return ( + + +
+ + {row.getValue("color")} + + ); + }, + }, + { + accessorKey: "companies", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return

{row.original.companies.length}

; + }, + }, + { + accessorKey: "published", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {row.getValue("published") ? ( + + ) : ( + + )} + {str( + GetTranslation( + row.getValue("published") ? "back.yes" : "back.no", + ), + ) + .ucFirst() + .value()} + + ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ companyActivityModels, @@ -37,120 +159,68 @@ export default function Index({ }; const { viewAny, viewTrash, create } = auth.policies.companyActivities; const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) - }, - }, - { - accessorKey: "color", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return ( - - -
-
- {row.getValue("color")} -
- ) - }, - }, - { - accessorKey: "companies", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return (

{row.original.companies.length}

); - }, - }, - { - accessorKey: "published", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {row.getValue("published") ? ( - - ) : ( - - )} - {str(useTrans(row.getValue("published") ? "back.yes" : "back.no")).ucFirst().value()} - - ), - }, - ]; - - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; + const columns = getColumns(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} - variant="outline" - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewTrash && ( + } + tooltipContent={

{transAccessToArchived}

} + variant="outline" + /> + )} + {create && ( + } + tooltipContent={

{transAddEntry}

} + /> + )} +
+ ) ); }; diff --git a/resources/ts/back/Pages/CompanyActivities/Show.tsx b/resources/ts/back/Pages/CompanyActivities/Show.tsx index e2c5d8f7..d6e280d1 100644 --- a/resources/ts/back/Pages/CompanyActivities/Show.tsx +++ b/resources/ts/back/Pages/CompanyActivities/Show.tsx @@ -1,6 +1,7 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeftIcon, CheckIcon, XIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -9,110 +10,128 @@ import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import AssociatedCompaniesList from "@/back/Components/AssociatedCompaniesList"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AuthProp, - CompanyActivityModel, - Resource, - SingleResource, - TranslationField, -} from "@/back/types/global"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AuthProp, Resource, SingleResource } from "@/back/types/global"; +import { TranslationField } from "@/back/types/i18n"; +import { CompanyActivityModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { ArrowLeftIcon, CheckIcon, XIcon } from "lucide-react"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Show({ data, companies, modelName }: { data: SingleResource, companies: Resource, modelName: string }) { - const { auth } = usePage().props as unknown as { - auth: AuthProp; - }; - const { viewAny } = auth.policies.companyActivities; - const companyActivityModel = data.data as CompanyActivityModel; - const actionModels = [ - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const singularModelName = str(modelName).singular().value(); - const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, - }); - const columns = [ +const getColumns = () => { + return [ { accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), }, { accessorKey: "color", - header: str(useTrans("validation.custom.color")).ucFirst().value(), + header: str(GetTranslation("validation.custom.color")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => value, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "published", - header: str(useTrans("validation.custom.published")).ucFirst().value(), + header: str(GetTranslation("validation.custom.published")) + .ucFirst() + .value(), cell: ({ value }: { value: boolean }) => ( {value ? ( ) : ( )} - {str(useTrans(value ? "back.yes" : "back.no")).ucFirst().value()} + {str(GetTranslation(value ? "back.yes" : "back.no")) + .ucFirst() + .value()} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; +export default function Show({ + data, + companies, + modelName, +}: { + data: SingleResource; + companies: Resource; + modelName: string; +}) { + const { auth } = usePage().props as unknown as { + auth: AuthProp; + }; + const { viewAny } = auth.policies.companyActivities; + const companyActivityModel = data.data as CompanyActivityModel; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; + const singularModelName = str(modelName).singular().value(); + const transTitle = useTrans("crud.helpers.visualization_model", { + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, + }); + const columns = getColumns(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
- + })} + />
); diff --git a/resources/ts/back/Pages/CompanySectors/Index.tsx b/resources/ts/back/Pages/CompanySectors/Index.tsx index 01228af1..ab5e2de6 100644 --- a/resources/ts/back/Pages/CompanySectors/Index.tsx +++ b/resources/ts/back/Pages/CompanySectors/Index.tsx @@ -2,7 +2,13 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; +import { + ArchiveIcon, + ArrowLeftIcon, + CheckIcon, + PlusIcon, + XIcon, +} from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -12,16 +18,101 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { Views } from "@/lib/utils"; -import { - AppEnv, - AuthProp, - CompanySectorModel, - Resource, -} from "@/back/types/global"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, Resource } from "@/back/types/global"; +import { CompanySectorModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "companies", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return

{row.original.companies.length}

; + }, + }, + { + accessorKey: "published", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {row.getValue("published") ? ( + + ) : ( + + )} + {str( + GetTranslation( + row.getValue("published") ? "back.yes" : "back.no", + ), + ) + .ucFirst() + .value()} + + ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ companySectorModels, @@ -38,99 +129,69 @@ export default function Index({ }; const { viewAny, viewTrash, create } = auth.policies.companySectors; const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) - }, - }, - { - accessorKey: "companies", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return (

{row.original.companies.length}

); - }, - }, - { - accessorKey: "published", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {row.getValue("published") ? ( - - ) : ( - - )} - {str(useTrans(row.getValue("published") ? "back.yes" : "back.no")).ucFirst().value()} - - ), - }, - ]; + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; + const columns = getColumns(); - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} - variant={"outline"} - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewTrash && ( + } + tooltipContent={

{transAccessToArchived}

} + variant="outline" + /> + )} + {create && ( + } + tooltipContent={

{transAddEntry}

} + /> + )} +
+ ) ); }; diff --git a/resources/ts/back/Pages/CompanySectors/Show.tsx b/resources/ts/back/Pages/CompanySectors/Show.tsx index 73bd5088..570c8a76 100644 --- a/resources/ts/back/Pages/CompanySectors/Show.tsx +++ b/resources/ts/back/Pages/CompanySectors/Show.tsx @@ -10,102 +10,121 @@ import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import AssociatedCompaniesList from "@/back/Components/AssociatedCompaniesList"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AuthProp, - CompanySectorModel, - Resource, - SingleResource, - TranslationField, -} from "@/back/types/global"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AuthProp, Resource, SingleResource } from "@/back/types/global"; +import { CompanySectorModel } from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Show({ data, companies, modelName }: { data: SingleResource, companies: Resource, modelName: string }) { - const { auth } = usePage().props as unknown as { - auth: AuthProp; - }; - const { viewAny } = auth.policies.companySectors; - const companySectorModel = data.data as CompanySectorModel; - const actionModels = [ - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const singularModelName = str(modelName).singular().value(); - const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, - }); - const columns = [ +const getColumns = () => { + return [ { accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), }, { accessorKey: "published", - header: str(useTrans("validation.custom.published")).ucFirst().value(), + header: str(GetTranslation("validation.custom.published")) + .ucFirst() + .value(), cell: ({ value }: { value: boolean }) => ( {value ? ( ) : ( )} - {str(useTrans(value ? "back.yes" : "back.no")).ucFirst().value()} + {str(GetTranslation(value ? "back.yes" : "back.no")) + .ucFirst() + .value()} ), }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; +export default function Show({ + data, + companies, + modelName, +}: { + data: SingleResource; + companies: Resource; + modelName: string; +}) { + const { auth } = usePage().props as unknown as { + auth: AuthProp; + }; + const { viewAny } = auth.policies.companySectors; + const companySectorModel = data.data as CompanySectorModel; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; + const singularModelName = str(modelName).singular().value(); + const transTitle = useTrans("crud.helpers.visualization_model", { + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, + }); + const columns = getColumns(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { + return [ { accessorKey: "type", header: ({ column }: { column: { id: string } }) => (

{str( - useTrans( + GetTranslation( `validation.custom.contact_count.${column.id}`, ), ) @@ -33,7 +30,7 @@ export default function Index({ const type = Object.values(contactFormType).find( (item) => item.value === row.getValue("type"), ); - if (!type) return; + if (!type) return ""; return (

{str(type.label).ucFirst().value()} @@ -46,7 +43,7 @@ export default function Index({ header: ({ column }: { column: { id: string } }) => (

{str( - useTrans( + GetTranslation( `validation.custom.contact_count.${column.id}`, ), ) @@ -55,7 +52,34 @@ export default function Index({

), }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( +

+ {str(GetTranslation(`validation.attributes.${column.id}`)) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, ]; +}; + +export default function Index({ + contactCountModels, + contactFormType, + modelName, +}: { + contactCountModels: Resource; + contactFormType: LaravelEnum; + modelName: string; +}) { + const columns = getColumns(contactFormType); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, diff --git a/resources/ts/back/Pages/Dashboard/Index.tsx b/resources/ts/back/Pages/Dashboard/Index.tsx index a49bb6c5..3c340a80 100644 --- a/resources/ts/back/Pages/Dashboard/Index.tsx +++ b/resources/ts/back/Pages/Dashboard/Index.tsx @@ -104,13 +104,15 @@ export default function Dashboard() { - {tool.label} - - } + content={ + <> + {tool.label} + + + } tooltipContent={

{uwilTooltip}

} size="default" - externalLink={true} + externalLink />
diff --git a/resources/ts/back/Pages/Document/Create.tsx b/resources/ts/back/Pages/Document/Create.tsx index 0641d9e5..ff332fa0 100644 --- a/resources/ts/back/Pages/Document/Create.tsx +++ b/resources/ts/back/Pages/Document/Create.tsx @@ -8,18 +8,24 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import { - AuthProp, - DocumentModel, - SingleResource, -} from "@/back/types/global"; +import { AuthProp, SingleResource } from "@/back/types/global"; +import { DocumentModel } from "@/back/types/others"; import Form from "@/back/Pages/Document/Form"; import str from "@/hooks/use-string"; -export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) { +export default function Create({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { const { viewAny } = (usePage().props.auth as AuthProp).policies.documents; const documentModel = data.data as DocumentModel; const singularModelName = str(modelName).singular().value(); + + // Translations. + const transBackToList = useTrans("back.crud_back_to_list"); const transTitle = useTrans( route().current(`back.${modelName}.duplicate`) ? "crud.helpers.duplication_model" @@ -34,22 +40,21 @@ export default function Create({ data, modelName }: { data: SingleResource, mode ); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + (null); - const defaultCategoriesOptions = extractIdsFromDatabasePivotRelation(model?.categories); + const defaultCategoriesOptions = extractIdsFromDatabasePivotRelation( + model?.categories, + ); const defaultTagsOptions = extractIdsFromDatabasePivotRelation(model?.tags); /** Form section */ @@ -68,7 +66,7 @@ export default function Form({ action, model, post, - data + data, }); const originalDataPath = @@ -94,6 +92,23 @@ export default function Form({ } }; + //* TRANSLATIONS + const transAssociatedIssuPathLabel = useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.issuu_path"), + }, + choice: 1, + }); + const transAssociatedIssuPathPlaceholder = useTrans( + "back.issuu.issuu_path.placeholder", + ); + const transAssociatePathLabel = useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.file"), + }, + choice: 1, + }); + const transRefreshOriginal = useTrans("back.refresh_original"); return ( @@ -117,7 +132,7 @@ export default function Form({ ) .ucFirst() .value()} - required={true} + required placeholder="ex: John Doe" value={data.name ?? ""} setData={setData} @@ -133,7 +148,7 @@ export default function Form({ name="published_at" setData={setData} date={data.published_at} - hasTime={true} + hasTime label={str( useTrans("back.form_associate_to", { params: { @@ -151,7 +166,7 @@ export default function Form({ name="unpublished_at" setData={setData} date={data.unpublished_at} - hasTime={true} + hasTime label={str( useTrans("back.form_associate_to", { params: { @@ -178,7 +193,7 @@ export default function Form({ ) .ucFirst() .value()} - placeholder={"ex: " + enumDocStatus.unpublished.label} + placeholder={`ex: ${enumDocStatus.unpublished.label}`} selected={Number(data.status)} setData={setData} /> @@ -194,7 +209,7 @@ export default function Form({ label={str(useTrans("validation.custom.is_issuu")) .ucFirst() .value()} - name={"is_issuu"} + name="is_issuu" checked={data.is_issuu} setData={(_, value) => { if (data.path || data.issuu_path) { @@ -213,21 +228,12 @@ export default function Form({ {data.is_issuu ? ( )} @@ -269,21 +266,20 @@ export default function Form({ variant="secondary" onClick={refreshFileFromDb} content={} - tooltipContent={str( - useTrans("back.refresh_original"), - ) + tooltipContent={str(transRefreshOriginal) .ucFirst() .value()} /> )}
- {(!data.is_issuu && model?.path && originalDataPath) && ( + {!data.is_issuu && model?.path && originalDataPath && ( - {url + "/" + originalDataPath} + {`${url}/${originalDataPath}`} )}
@@ -302,19 +298,17 @@ export default function Form({ ) .ucFirst() .value()} - multiple={true} + multiple name="tags" required={false} variant="inverted" - placeholder={str( - useTrans("back.document.tag.placeholder"), - ) + placeholder={str(useTrans("back.document.tag.placeholder")) .ucFirst() .value()} - singleLine={true} + singleLine setData={setData} defaultValues={defaultTagsOptions} - closeButtonVisible={true} + closeButtonVisible /> -
{ + return [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - const locale = appEnv.locale; + const { locale } = appEnv; const issuuPath = row.original.issuu_path; - const path = row.original.path; + const { path } = row.original; const hasIssuuPathForLocale = Boolean(issuuPath?.[locale]); const hasPathForLocale = Boolean(path?.[locale]); @@ -84,16 +63,18 @@ export default function Index({

- {str(useTrans("back.document.no_link")) + {str( + GetTranslation( + "back.document.no_link", + ), + ) .ucFirst() .value()}

)} - {renderTranslationCell( - row.getValue("name") as TranslationField, - )} +
); }, @@ -103,7 +84,7 @@ export default function Index({ header: () => (

{str( - useTrans("models.classes.document-category", { + GetTranslation("models.classes.document-category", { choice: 2, }), ) @@ -134,14 +115,17 @@ export default function Index({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.document-category", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.document-category", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -157,7 +141,7 @@ export default function Index({
) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -166,7 +150,7 @@ export default function Index({ accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( }) => { return ( ); }, @@ -184,7 +168,7 @@ export default function Index({ accessorKey: "published_at", header: ({ column }: { column: { id: string } }) => ( }) => ( - {useFormatedDate(row.getValue("published_at"))} + {GetFormatedDate(row.getValue("published_at"))} ), }, @@ -200,7 +184,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( }) => ( - {useFormatedDate(row.getValue("updated_at"))} + {GetFormatedDate(row.getValue("updated_at"))} ), }, ]; +}; + +export default function Index({ + documentsModel, + searchFields, + modelName, +}: { + documentsModel: Resource; + searchFields: string; + modelName: string; +}) { + const { auth, appEnv } = usePage().props as unknown as { + auth: AuthProp; + appEnv: AppEnv; + }; + const { create } = auth.policies.documents; + const { viewAny: viewAnyDocumentCategories } = + auth.policies.documentCategories; + const { viewAny: viewAnyDocumentTags } = auth.policies.documentTags; + const actionModels = [Views.VISUALIZATION, Views.EDITION, Views.DELETION]; + const columns = getColumns(appEnv, viewAnyDocumentTags); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, ); const transTitle = str(transModel).ucFirst().value(); - + const transAccessToDocumentCategory = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.document-category", { choice: 2 }), + }, + }); + const transAccessToDocumentTag = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.document-tag", { choice: 2 }), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return (
@@ -226,18 +243,7 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.document-category", - { choice: 2 }, - ), - }, - })} -

- } + tooltipContent={

{transAccessToDocumentCategory}

} variant="outline" /> )} @@ -245,18 +251,7 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.document-tag", - { choice: 2 }, - ), - }, - })} -

- } + tooltipContent={

{transAccessToDocumentTag}

} variant="outline" /> )} @@ -264,9 +259,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transAddEntry}

} /> )}
@@ -275,10 +268,7 @@ export default function Index({ return ( - + { + return [ { accessorKey: "name", - header: str(useTrans("validation.attributes.name")) + header: str(GetTranslation("validation.attributes.name")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -61,13 +38,13 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "path", - header: str(useTrans("validation.custom.file")) + header: str(GetTranslation("validation.custom.file")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -75,19 +52,20 @@ export default function Show({ - {appEnv.url + "/" + value[appEnv.locale]} + {`${appEnv.url}/${value[appEnv.locale]}`} ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "issuu_path", - header: str(useTrans("validation.custom.issuu_path")) + header: str(GetTranslation("validation.custom.issuu_path")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -96,23 +74,27 @@ export default function Show({ target="_blank" className="text-blue-500 underline" href={value[appEnv.locale]} + rel="noreferrer" > {value[appEnv.locale]} ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "exercice", header: str( - useTrans("back.associated_model", { + GetTranslation("back.associated_model", { params: { - model: useTrans("models.classes.document-exercice", { - choice: 2, - }), + model: GetTranslation( + "models.classes.document-exercice", + { + choice: 2, + }, + ), }, choice: 2, }), @@ -120,19 +102,25 @@ export default function Show({ .ucFirst() .value(), cell: ({ value }: { value: string }) => { - return ; + return ; }, }, { accessorKey: "status", - header: str(useTrans("validation.custom.status")).ucFirst().value(), + header: str(GetTranslation("validation.custom.status")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { - return ; + return ; }, }, { accessorKey: "categories", - header: str(useTrans("models.classes.document-category", { choice: 2 })) + header: str( + GetTranslation("models.classes.document-category", { + choice: 2, + }), + ) .ucFirst() .value(), cell: ({ value }: { value?: DocumentCategoryModel[] }) => { @@ -155,14 +143,17 @@ export default function Show({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.document-category", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.document-category", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -178,14 +169,16 @@ export default function Show({
) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, }, { accessorKey: "tags", - header: str(useTrans("models.classes.document-tag", { choice: 2 })) + header: str( + GetTranslation("models.classes.document-tag", { choice: 2 }), + ) .ucFirst() .value(), cell: ({ value }: { value?: DocumentTagModel[] }) => { @@ -208,14 +201,17 @@ export default function Show({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.document-tag", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.document-tag", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -231,53 +227,86 @@ export default function Show({
) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")) + header: str(GetTranslation("validation.attributes.created_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => { return ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ); }, }, { accessorKey: "published_at", - header: str(useTrans("validation.custom.published_at")) + header: str(GetTranslation("validation.custom.published_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value, undefined, true)} + {GetFormatedDate(value, undefined, true)} ), }, { accessorKey: "unpublished_at", - header: str(useTrans("validation.custom.unpublished_at")) + header: str(GetTranslation("validation.custom.unpublished_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")) + header: str(GetTranslation("validation.attributes.updated_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; +export default function Show({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { auth, appEnv } = usePage().props as unknown as { + auth: AuthProp; + appEnv: AppEnv; + }; + const { viewAny } = auth.policies.documents; + const { viewAny: viewAnyDocumentCategories } = + auth.policies.documentCategories; + const { viewAny: viewAnyDocumentTags } = auth.policies.documentTags; + const docsModel = data.data as DocumentModel; + const actionModels = [Views.EDITION, Views.DELETION]; + const singularModelName = str(modelName).singular().value(); + const transTitle = useTrans("crud.helpers.visualization_model", { + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, + }); + const columns = getColumns( + appEnv, + viewAnyDocumentCategories, + viewAnyDocumentTags, + ); + + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( viewAny && ( @@ -285,9 +314,7 @@ export default function Show({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transBackToList}

} /> ) diff --git a/resources/ts/back/Pages/DocumentCategory/Create.tsx b/resources/ts/back/Pages/DocumentCategory/Create.tsx index 65c3f8fe..194df98f 100644 --- a/resources/ts/back/Pages/DocumentCategory/Create.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Create.tsx @@ -7,18 +7,25 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import { - AuthProp, - DocumentCategoryModel, - SingleResource, -} from "@/back/types/global"; +import { AuthProp, SingleResource } from "@/back/types/global"; +import { DocumentCategoryModel } from "@/back/types/others"; import Form from "@/back/Pages/DocumentCategory/Form"; import str from "@/hooks/use-string"; -export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) { - const { viewAny } = (usePage().props.auth as AuthProp).policies.documentCategories; +export default function Create({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { viewAny } = (usePage().props.auth as AuthProp).policies + .documentCategories; const documentCategoryModel = data.data as DocumentCategoryModel; const singularModelName = str(modelName).singular().value(); + + // Translations. + const transBackToList = useTrans("back.crud_back_to_list"); const transTitle = useTrans( route().current(`back.${modelName}.duplicate`) ? "crud.helpers.duplication_model" @@ -33,22 +40,21 @@ export default function Create({ data, modelName }: { data: SingleResource, mode ); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
- + })} + />
); diff --git a/resources/ts/back/Pages/DocumentCategory/Index.tsx b/resources/ts/back/Pages/DocumentCategory/Index.tsx index 546abb02..eeb4c5a7 100644 --- a/resources/ts/back/Pages/DocumentCategory/Index.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Index.tsx @@ -11,18 +11,79 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AppEnv, - AuthProp, - DocumentCategoryModel, - Resource, -} from "@/back/types/global"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, Resource } from "@/back/types/global"; +import { DocumentCategoryModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "documents", + header: () => ( +

+ {str( + GetTranslation("back.associated_model", { + params: { + model: GetTranslation( + "models.classes.document", + { + choice: 2, + }, + ), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => ( +
+

{row.original.documents_count ?? 0}

+
+ ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ documentCategoryModel, @@ -47,62 +108,7 @@ export default function Index({ Views.DUPLICATION, Views.ARCHIVATION, ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("name")); - }, - }, - { - accessorKey: "documents", - header: () => ( -

- {str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.document", { - choice: 2, - }), - }, - choice: 2, - }), - ) - .ucFirst() - .value()} -

- ), - cell: ({ row }: { row: Row }) => ( -
-

{row.original.documents_count ?? 0}

-
- ), - }, - { - accessorKey: "updated_at", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {useFormatedDate(row.getValue("updated_at"))} - - ), - }, - ]; + const columns = getColumns(); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, @@ -114,6 +120,7 @@ export default function Index({ .ucFirst() .value(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -122,14 +129,18 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transBackToList}

} /> ) ); }; + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -138,9 +149,7 @@ export default function Index({ } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} + tooltipContent={

{transAccessToArchived}

} variant="outline" /> )} @@ -148,9 +157,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transAddEntry}

} /> )} diff --git a/resources/ts/back/Pages/DocumentCategory/Show.tsx b/resources/ts/back/Pages/DocumentCategory/Show.tsx index 84909f4e..cc007510 100644 --- a/resources/ts/back/Pages/DocumentCategory/Show.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Show.tsx @@ -1,97 +1,119 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; import { AppEnv, AuthProp, - DocumentTagModel, Resource, SingleResource, - TranslationField, } from "@/back/types/global"; +import { DocumentTagModel } from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; -import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +const getColumns = (appEnv: AppEnv) => { + return [ + { + accessorKey: "name", + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), + }, + { + accessorKey: "slug", + header: str(GetTranslation("validation.custom.slug")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {GetTranslation("back.table_not_known")} +

+ ), + }, + { + accessorKey: "created_at", + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + {GetFormatedDate(value)} + ); + }, + }, + { + accessorKey: "updated_at", + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => ( + {GetFormatedDate(value)} + ), + }, + ]; +}; -export default function Show({ data, modelName, documents }: { data: SingleResource, modelName: string, documents: Resource }) { +export default function Show({ + data, + modelName, + documents, +}: { + data: SingleResource; + modelName: string; + documents: Resource; +}) { const { auth, appEnv } = usePage().props as unknown as { auth: AuthProp; appEnv: AppEnv; }; const { viewAny } = auth.policies.documentCategories; const model = data.data as DocumentTagModel; - const actionModels = [ - Views.EDITION, - Views.DELETION, - ]; + const actionModels = [Views.EDITION, Views.DELETION]; const singularModelName = str(modelName).singular().value(); const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, }); - const columns = [ - { - accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } - }, - { - accessorKey: "slug", - header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), - }, - { - accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => { - return ( - {useFormatedDate(value)} - ) - }, - }, - { - accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} - ), - }, - ]; + const columns = getColumns(appEnv); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + diff --git a/resources/ts/back/Pages/DocumentTag/Index.tsx b/resources/ts/back/Pages/DocumentTag/Index.tsx index 21c904d8..8687b368 100644 --- a/resources/ts/back/Pages/DocumentTag/Index.tsx +++ b/resources/ts/back/Pages/DocumentTag/Index.tsx @@ -16,18 +16,105 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AppEnv, - AuthProp, - DocumentTagModel, - Resource, -} from "@/back/types/global"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, Resource } from "@/back/types/global"; +import { DocumentTagModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "color", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return ( + + +
+ + {row.getValue("color")} + + ); + }, + }, + { + accessorKey: "documents", + header: () => ( +

+ {str( + GetTranslation("back.associated_model", { + params: { + model: GetTranslation( + "models.classes.document", + { + choice: 2, + }, + ), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => ( +
+

{row.original.documents_count ?? 0}

+
+ ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ documentTagModel, @@ -52,88 +139,7 @@ export default function Index({ Views.DUPLICATION, Views.ARCHIVATION, ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("name")); - }, - }, - { - accessorKey: "color", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return ( - - -
-
- {row.getValue("color")} -
- ); - }, - }, - { - accessorKey: "documents", - header: () => ( -

- {str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.document", { - choice: 2, - }), - }, - choice: 2, - }), - ) - .ucFirst() - .value()} -

- ), - cell: ({ row }: { row: Row }) => ( -
-

{row.original.documents_count ?? 0}

-
- ), - }, - { - accessorKey: "updated_at", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {useFormatedDate(row.getValue("updated_at"))} - - ), - }, - ]; + const columns = getColumns(); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, @@ -145,6 +151,7 @@ export default function Index({ .ucFirst() .value(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -153,15 +160,19 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transBackToList}

} />
) ); }; + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -170,9 +181,7 @@ export default function Index({ } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} + tooltipContent={

{transAccessToArchived}

} variant="outline" /> )} @@ -180,9 +189,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transAddEntry}

} /> )} diff --git a/resources/ts/back/Pages/DocumentTag/Show.tsx b/resources/ts/back/Pages/DocumentTag/Show.tsx index 7651ebbe..a0db37e5 100644 --- a/resources/ts/back/Pages/DocumentTag/Show.tsx +++ b/resources/ts/back/Pages/DocumentTag/Show.tsx @@ -1,29 +1,101 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; import { AppEnv, AuthProp, - DocumentTagModel, Resource, SingleResource, - TranslationField, } from "@/back/types/global"; +import { DocumentTagModel } from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; -import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = (appEnv: AppEnv) => { + return [ + { + accessorKey: "name", + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), + }, + { + accessorKey: "slug", + header: str(GetTranslation("validation.custom.slug")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {GetTranslation("back.table_not_known")} +

+ ), + }, + { + accessorKey: "color", + header: str(GetTranslation("validation.custom.color")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + + +
+ + {value} + + ); + }, + }, + { + accessorKey: "created_at", + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + {GetFormatedDate(value)} + ); + }, + }, + { + accessorKey: "updated_at", + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => ( + {GetFormatedDate(value)} + ), + }, + ]; +}; export default function Show({ data, @@ -49,69 +121,9 @@ export default function Show({ }), }, }); - const columns = [ - { - accessorKey: "name", - header: str(useTrans("validation.attributes.name")) - .ucFirst() - .value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell(value); - }, - }, - { - accessorKey: "slug", - header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => - value[appEnv.locale] ? ( - value[appEnv.locale] - ) : ( -

- {useTrans("back.table_not_known")} -

- ), - }, - { - accessorKey: "color", - header: str(useTrans("validation.custom.color")).ucFirst().value(), - cell: ({ value }: { value: string }) => { - return ( - - -
-
- {value} -
- ); - }, - }, - { - accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")) - .ucFirst() - .value(), - cell: ({ value }: { value: string }) => { - return ( - {useFormatedDate(value)} - ); - }, - }, - { - accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")) - .ucFirst() - .value(), - cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} - ), - }, - ]; + const columns = getColumns(appEnv); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( viewAny && ( @@ -119,9 +131,7 @@ export default function Show({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transBackToList}

} />
) diff --git a/resources/ts/back/Pages/DynamicPages/Create.tsx b/resources/ts/back/Pages/DynamicPages/Create.tsx index 769447e1..33e11f7a 100644 --- a/resources/ts/back/Pages/DynamicPages/Create.tsx +++ b/resources/ts/back/Pages/DynamicPages/Create.tsx @@ -8,21 +8,29 @@ import Form from "@/back/Pages/DynamicPages/Form"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import { - AuthProp, - DynamicPageModel, - SingleResource, -} from "@/back/types/global"; +import { AuthProp, SingleResource } from "@/back/types/global"; +import { DynamicPageModel } from "@/back/types/dynamic-pages"; import str from "@/hooks/use-string"; -export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) { - const { viewAny } = (usePage().props.auth as AuthProp).policies.dynamicPages; +export default function Create({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { viewAny } = (usePage().props.auth as AuthProp).policies + .dynamicPages; const dynamicPageModel = data.data as DynamicPageModel; const singularModelName = str(modelName).singular().value(); + + // Translations. + const transBackToList = useTrans("back.crud_back_to_list"); const transTitle = useTrans( route().current(`back.${modelName}.duplicate`) ? "crud.helpers.duplication_model" - : "crud.helpers.creation_model", { + : "crud.helpers.creation_model", + { params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1, @@ -32,22 +40,21 @@ export default function Create({ data, modelName }: { data: SingleResource, mode ); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + (null); const isConceptor = userModel.role === enumUserRole.conceptor.value; - const pageConfigModels = usePage().props.pageConfigModels as Array; + const pageConfigModels = usePage().props + .pageConfigModels as Array; // Models filtered based on the presence of the locale. const filteredPageConfigModels = pageConfigModels.filter( - (model) => - model.label?.[locale] !== undefined && - model.config?.[locale] !== undefined, + (pageConfigModel) => + pageConfigModel.label?.[locale] !== undefined && + pageConfigModel.config?.[locale] !== undefined, ); // Set empty config by default. @@ -92,7 +98,9 @@ export default function Form({ } as PageConfigModel, ...filteredPageConfigModels, ]; - configOptions[defaultConfigId].label[locale] = useTrans("back.config_none_selected"); + configOptions[defaultConfigId].label[locale] = useTrans( + "back.config_none_selected", + ); // Set translations. const contentAssociateToModel = str( @@ -111,9 +119,25 @@ export default function Form({ model: useTrans("models.classes.page-config", { choice: 1 }), }, }); + const transValidationRootLabel = useTrans("validation.custom.root"); + const transValidationParentPageLabel = useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.parent_page"), + }, + choice: 2, + }); + const transAssociateToStatus = useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.status"), + }, + choice: 1, + }); + const transFormTitleIsLocked = useTrans("back.form_title_isLocked"); + const transFormSubtitleIsLocked = useTrans("back.form_subtitle_isLocked"); + const getConfig = (id: number) => - configOptions.find((objet) => objet.id == id)?.config[ - locale + configOptions.find((objet) => objet.id === id)?.config[ + locale ] as ConfigField[]; /** Form section */ @@ -127,7 +151,8 @@ export default function Form({ isLocked: model?.isLocked ?? false, isRoot: model?.isRoot ?? false, }); - + const defaultIsRootValue = + !data.isRoot && data.page_id ? [data.page_id] : []; const submit = useCrudSubmit({ method, modelRoute, @@ -135,34 +160,41 @@ export default function Form({ action, model, post, - data + data, }); function getFullSlugPath( - models: DynamicPageModel[], - selectedGroup: string | null, - locale: string = "fr", + targetModels: DynamicPageModel[], + currentSelectedGroup: string | null, + currentLocale: string = "fr", ): string | null { - if (!selectedGroup) return null; + if (!currentSelectedGroup) return null; // Trouver le modèle sélectionné à partir de son title - const current = models.find( - (m) => m.title[locale]?.toLowerCase() === selectedGroup.toLowerCase(), + const current = targetModels.find( + (targetModel) => + targetModel.title[currentLocale]?.toLowerCase() === + currentSelectedGroup.toLowerCase(), ); if (!current) return null; // Fonction récursive pour reconstruire le chemin - const buildPath = (model: DynamicPageModel): string => { - const parent = model.page_id - ? models.find((m) => m.id === model.page_id) + const buildPath = (modelParent: DynamicPageModel): string => { + const parent = modelParent.page_id + ? targetModels.find( + (targetModel) => targetModel.id === modelParent.page_id, + ) : null; - const currentTranslatedModelSlug = model.slug[locale] ?? ""; + const currentTranslatedModelSlug = + modelParent.slug[currentLocale] ?? ""; if (!parent) return currentTranslatedModelSlug; - return [buildPath(parent), currentTranslatedModelSlug].filter(Boolean).join("/"); + return [buildPath(parent), currentTranslatedModelSlug] + .filter(Boolean) + .join("/"); }; return buildPath(current); @@ -198,16 +230,7 @@ export default function Form({ { setSelectedGroup(null); setData("page_id", null); setData("slug", ""); - // @ts-ignore + // @ts-expect-error TS2345: 'name' type is dynamic, TypeScript cannot infer the correct key setData(name, value); }} /> @@ -243,23 +268,24 @@ export default function Form({ targetModel="dynamic_pages" multiple={false} field="title" - closeOnSelect={true} - label={str( - useTrans("back.form_associate_to", { - params: { - attribute: useTrans("validation.custom.parent_page"), - }, - choice: 2, - }), - ) + closeOnSelect + label={str(transValidationParentPageLabel) .ucFirst() .value()} placeholder="ex: " - defaultValues={!data.isRoot ? (data.page_id ? [data.page_id] : []) : []} + defaultValues={defaultIsRootValue} exclude={model?.id} required={false} setData={setData} - onModelChange={(value) => setSelectedGroup((value && value.length > 0) ? (value[0] as DynamicPageModel).title[locale] : null)} + onModelChange={(value) => + setSelectedGroup( + value && value.length > 0 + ? (value[0] as DynamicPageModel).title[ + locale + ] + : null, + ) + } disabled={data.isRoot} /> @@ -291,9 +328,9 @@ export default function Form({ name="config_id" targetModel="page_configs" multiple={false} - closeOnSelect={true} + closeOnSelect field="label" - responsive={true} + responsive label={str( useTrans("back.form_associate_to", { params: { @@ -308,7 +345,9 @@ export default function Form({ .value()} required={false} placeholder="ex: John Doe" - defaultValues={data.config_id ? [data.config_id] : []} + defaultValues={ + data.config_id ? [data.config_id] : [] + } setData={setData} /> {isConceptor && @@ -379,10 +418,12 @@ export default function Form({ name="content" config={getConfig(Number(data.config_id))} content={ - typeof data.content === "object" ? data.content : null + typeof data.content === "object" + ? data.content + : null } setData={setData} - // @ts-ignore + // @ts-expect-error Types diff between custom reset and useForm reset. reset={reset} /> )} @@ -390,9 +431,9 @@ export default function Form({ {isConceptor && ( } - description={useTrans("back.form_subtitle_isLocked")} + description={transFormSubtitleIsLocked} inline > )}
- + })} + />
); diff --git a/resources/ts/back/Pages/DynamicPages/Index.tsx b/resources/ts/back/Pages/DynamicPages/Index.tsx index bfd4db08..90915892 100644 --- a/resources/ts/back/Pages/DynamicPages/Index.tsx +++ b/resources/ts/back/Pages/DynamicPages/Index.tsx @@ -27,65 +27,42 @@ import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import DynamicStatusBadge from "@/back/Components/DynamicPages/DynamicStatusBadge"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { Views } from "@/lib/utils"; -import { - AppEnv, - AuthProp, - DynamicPageModel, - PageConfigModel, - Resource, - TranslationField, -} from "@/back/types/global"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, Resource } from "@/back/types/global"; +import { DynamicPageModel, PageConfigModel } from "@/back/types/dynamic-pages"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Index({ - dynamicPageModels, - searchFields, - modelName, -}: { - dynamicPageModels: Resource; - searchFields: string; - modelName: string; -}) { - const { auth, appEnv } = usePage().props as unknown as { - auth: AuthProp; - appEnv: AppEnv; - }; - const { viewAny, viewTrash, create } = auth.policies.dynamicPages; - const { viewAny: viewAnyPageConfigs } = auth.policies.pageConfigs; - const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - - const columns = [ +const getColumns = ( + appEnv: AppEnv, + modelName: string, + viewAny: boolean, + viewAnyPageConfigs: boolean, +) => { + return [ { accessorKey: "title", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => (
- {renderTranslationCell(row.getValue("title") as TranslationField)} + {row.original.isRoot && ( - {useTrans("back.page_root")} + {GetTranslation("back.page_root")} )} @@ -96,7 +73,7 @@ export default function Index({ accessorKey: "parent_page", header: ({ column }: { column: { id: string } }) => ( }) => { if (row.getValue("parent_page")) { - const dynamicPageModel = row.getValue("parent_page") as DynamicPageModel; + const dynamicPageModel = row.getValue( + "parent_page", + ) as DynamicPageModel; const cellValue = dynamicPageModel.title[appEnv.locale]; let value = {cellValue}; if (viewAny) { @@ -122,9 +101,9 @@ export default function Index({ } tooltipContent={

- {useTrans("back.access_model", { + {GetTranslation("back.access_model", { params: { - model: useTrans( + model: GetTranslation( "models.classes.dynamic-page", { choice: 1 }, ), @@ -141,9 +120,7 @@ export default function Index({ if (dynamicPageModel.deleted_at !== null) { value = (

- - {value} - + {value} - {useTrans("back.group_archived")} + {GetTranslation("back.group_archived")}
@@ -162,7 +139,7 @@ export default function Index({ } return (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -171,7 +148,7 @@ export default function Index({ accessorKey: "config", header: ({ column }: { column: { id: string } }) => ( }) => { if (row.getValue("config")) { - const pageConfigModel = row.getValue("config") as PageConfigModel; + const pageConfigModel = row.getValue( + "config", + ) as PageConfigModel; const cellValue = pageConfigModel.label[appEnv.locale]; let value = {cellValue}; if (viewAnyPageConfigs) { @@ -197,9 +176,9 @@ export default function Index({ } tooltipContent={

- {useTrans("back.access_model", { + {GetTranslation("back.access_model", { params: { - model: useTrans( + model: GetTranslation( "models.classes.page-config", { choice: 1 }, ), @@ -216,9 +195,7 @@ export default function Index({ if (pageConfigModel.deleted_at !== null) { value = (

- - {value} - + {value} - {useTrans("back.config_archived")} + {GetTranslation("back.config_archived")}
@@ -237,7 +214,7 @@ export default function Index({ } return (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -246,7 +223,7 @@ export default function Index({ accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( - {useTrans("back.page_locked")} + {GetTranslation("back.page_locked")} )} @@ -272,50 +249,102 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => ( - {useFormatedDate(row.getValue("updated_at"))} + {GetFormatedDate(row.getValue("updated_at"))} ), }, ]; +}; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); +export default function Index({ + dynamicPageModels, + searchFields, + modelName, +}: { + dynamicPageModels: Resource; + searchFields: string; + modelName: string; +}) { + const { auth, appEnv } = usePage().props as unknown as { + auth: AuthProp; + appEnv: AppEnv; + }; + const { viewAny, viewTrash, create } = auth.policies.dynamicPages; + const { viewAny: viewAnyPageConfigs } = auth.policies.pageConfigs; + const isArchiveRoute = route().current(`back.${modelName}.trash`); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; + const columns = getColumns(appEnv, modelName, viewAny, viewAnyPageConfigs); + + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; + const transAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} - variant="outline" - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewTrash && ( + } + tooltipContent={

{transAccessToArchived}

} + variant="outline" + /> + )} + {create && ( + } + tooltipContent={

{transAddEntry}

} + /> + )} +
+ ) ); }; diff --git a/resources/ts/back/Pages/DynamicPages/Show.tsx b/resources/ts/back/Pages/DynamicPages/Show.tsx index e8eeaea2..7308a485 100644 --- a/resources/ts/back/Pages/DynamicPages/Show.tsx +++ b/resources/ts/back/Pages/DynamicPages/Show.tsx @@ -1,5 +1,11 @@ // * Packages -import { ArrowLeftIcon, CheckIcon, CogIcon, StickyNoteIcon, XIcon } from "lucide-react"; +import { + ArrowLeftIcon, + CheckIcon, + CogIcon, + StickyNoteIcon, + XIcon, +} from "lucide-react"; import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; // * Components shadcn @@ -10,190 +16,258 @@ import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; import DynamicStatusBadge from "@/back/Components/DynamicPages/DynamicStatusBadge"; import RecursiveContent from "@/back/Components/DynamicPages/DynamicPageDetails"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, SingleResource } from "@/back/types/global"; import { - AppEnv, - AuthProp, - DynamicPageModel, + DynamicPageModelWithRelations, PageConfigModel, - SingleResource, - TranslationField, -} from "@/back/types/global"; +} from "@/back/types/dynamic-pages"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Show({ data, modelName }: { data: SingleResource, modelName: string }) { - const { auth, appEnv } = usePage().props as unknown as { - auth: AuthProp; - appEnv: AppEnv; - }; - const { viewAny } = auth.policies.dynamicPages; - const dynamicPageModel = data.data as DynamicPageModel; - const actionModels = [ - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const columns = [ +const getColumns = ( + appEnv: AppEnv, + auth: AuthProp, + modelName: string, + dynamicPageModel: DynamicPageModelWithRelations, +) => { + return [ { accessorKey: "title", - header: str(useTrans("validation.attributes.title")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.title")) + .ucFirst() + .value(), cell: ({ value }: { value: TranslationField }) => ( - renderTranslationCell( - value - ) + ), }, { accessorKey: "parent_page", - header: str(useTrans("validation.custom.parent_page")).ucFirst().value(), - cell: ({ value }: { value: DynamicPageModel }) => auth.policies.dynamicPages.viewAny ? ( - - - {value.title[appEnv.locale]} - - } - tooltipContent={ -

{useTrans("back.access_model", { - params: { - model: useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 1 }) - } - })}

- } - type="button" - size="default" - variant="secondary" - /> - ) : {value.title[appEnv.locale]} + header: str(GetTranslation("validation.custom.parent_page")) + .ucFirst() + .value(), + cell: ({ value }: { value: DynamicPageModelWithRelations }) => + auth.policies.dynamicPages.viewAny ? ( + + + {value.title[appEnv.locale]} + + } + tooltipContent={ +

+ {GetTranslation("back.access_model", { + params: { + model: GetTranslation( + `models.classes.${str(modelName).singular().value()}`, + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + {value.title[appEnv.locale]} + ), }, { accessorKey: "config", - header: str(useTrans("validation.custom.config")).ucFirst().value(), - cell: ({ value }: { value: PageConfigModel }) => auth.policies.pageConfigs.viewAny ? ( - - - {value.label[appEnv.locale]} - - } - tooltipContent={ -

{useTrans("back.access_model", { - params: { - model: useTrans('models.classes.page-config', { choice: 1 }) - } - })}

- } - type="button" - size="default" - variant="secondary" - /> - ) : {value.label[appEnv.locale]} + header: str(GetTranslation("validation.custom.config")) + .ucFirst() + .value(), + cell: ({ value }: { value: PageConfigModel }) => + auth.policies.pageConfigs.viewAny ? ( + + + {value.label[appEnv.locale]} + + } + tooltipContent={ +

+ {GetTranslation("back.access_model", { + params: { + model: GetTranslation( + "models.classes.page-config", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + {value.label[appEnv.locale]} + ), }, { accessorKey: "content", - header: str(useTrans("validation.attributes.content")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.content")) + .ucFirst() + .value(), cell: ({ value }: { value: TranslationField }) => { - if (typeof value[appEnv.locale] === "object" && dynamicPageModel.config?.config?.[appEnv.locale]) { + if ( + typeof value[appEnv.locale] === "object" && + dynamicPageModel.config?.config?.[appEnv.locale] + ) { return ( ); - } else if (typeof value[appEnv.locale] === "string" && String(value[appEnv.locale]).trim().length > 0) { + } + if ( + typeof value[appEnv.locale] === "string" && + String(value[appEnv.locale]).trim().length > 0 + ) { return

{String(value[appEnv.locale])}

; } return ( - {tableNotKnownTrans} + {GetTranslation("back.table_not_known")} ); }, }, { accessorKey: "status", - header: str(useTrans(`validation.custom.status`)).ucFirst().value(), - cell: ({ value }: { value: number }) => , + header: str(GetTranslation(`validation.custom.status`)) + .ucFirst() + .value(), + cell: ({ value }: { value: number }) => ( + + ), }, { accessorKey: "isLocked", - header: str(useTrans("validation.custom.locked")).ucFirst().value(), + header: str(GetTranslation("validation.custom.locked")) + .ucFirst() + .value(), cell: ({ value }: { value: boolean }) => ( - {value ? : } - {str(useTrans(value ? "back.yes" : "back.no")).ucFirst().value()} + {value ? ( + + ) : ( + + )} + {str(GetTranslation(value ? "back.yes" : "back.no")) + .ucFirst() + .value()} ), }, { accessorKey: "isRoot", - header: str(useTrans("validation.custom.root")).ucFirst().value(), + header: str(GetTranslation("validation.custom.root")) + .ucFirst() + .value(), cell: ({ value }: { value: boolean }) => ( - {value ? : } - {str(useTrans(value ? "back.yes" : "back.no")).ucFirst().value()} + {value ? ( + + ) : ( + + )} + {str(GetTranslation(value ? "back.yes" : "back.no")) + .ucFirst() + .value()} ), }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(GetTranslation("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; + +export default function Show({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { auth, appEnv } = usePage().props as unknown as { + auth: AuthProp; + appEnv: AppEnv; + }; + const { viewAny } = auth.policies.dynamicPages; + const dynamicPageModel = data.data as DynamicPageModelWithRelations; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; + const columns = getColumns(appEnv, auth, modelName, dynamicPageModel); const singularModelName = str(modelName).singular().value(); const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, }); - const tableNotKnownTrans = useTrans("back.table_not_known"); + const transBackToList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + @@ -33,9 +31,7 @@ export default function Default({ status }: { status: number }) { diff --git a/resources/ts/back/Pages/News/Create.tsx b/resources/ts/back/Pages/News/Create.tsx index a98bc55c..31dd6565 100644 --- a/resources/ts/back/Pages/News/Create.tsx +++ b/resources/ts/back/Pages/News/Create.tsx @@ -8,15 +8,21 @@ import Form from "@/back/Pages/News/Form"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import { - AuthProp, - NewsModel, - SingleResource, -} from "@/back/types/global"; +import { AuthProp, SingleResource } from "@/back/types/global"; +import { NewsModel } from "@/back/types/others"; -export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) { +export default function Create({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { const { viewAny } = (usePage().props.auth as AuthProp).policies.pageConfigs; const newsModel = data.data as NewsModel; + + // Translations. + const transBackToList = useTrans("back.crud_back_to_list"); const transTitle = useTrans( route().current(`back.${modelName}.duplicate`) ? "crud.helpers.duplication_model" @@ -31,22 +37,21 @@ export default function Create({ data, modelName }: { data: SingleResource, mode ); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { return value instanceof File; - } + }; /** Form section */ const { post, setData, data, reset } = useForm({ @@ -83,10 +81,10 @@ export default function Form({ const refreshFileFromDb = () => { if (model && model.picture) { - const isGif = + const newIsGifValue = typeof model.picture === "string" && model.picture.toLowerCase().endsWith(".gif"); - setIsGif(isGif); + setIsGif(newIsGifValue); setData("picture", model.picture); setDynamicKey(Date.now()); } @@ -99,7 +97,7 @@ export default function Form({ action, model, post, - data + data, }); useEffect(() => { @@ -112,10 +110,9 @@ export default function Form({ } return false; }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - - return ( @@ -139,7 +136,7 @@ export default function Form({ ) .ucFirst() .value()} - required={true} + required placeholder="ex: John Doe" value={data.seo_title ?? ""} setData={setData} @@ -159,7 +156,7 @@ export default function Form({ .ucFirst() .value()} placeholder="ex: John Doe" - required={true} + required value={data.seo_description ?? ""} setData={setData} /> @@ -200,7 +197,7 @@ export default function Form({ choice: 1, })} pathField={data.slug} - additionalGroupPath={"actualites"} // TODO: ce sera translatable plus tard + additionalGroupPath="actualites" // TODO: ce sera translatable plus tard isAvailable={ model?.status === enumNewsStatus.published.value } @@ -216,7 +213,7 @@ export default function Form({ name="published_at" setData={setData} date={data.published_at} - hasTime={true} + hasTime label={str( useTrans("back.form_associate_to", { params: { @@ -234,7 +231,7 @@ export default function Form({ name="unpublished_at" setData={setData} date={data.unpublished_at} - hasTime={true} + hasTime label={str( useTrans("back.form_associate_to", { params: { @@ -261,7 +258,7 @@ export default function Form({ ) .ucFirst() .value()} - placeholder={"ex: " + enumNewsStatus.unpublished.label} + placeholder={`ex: ${enumNewsStatus.unpublished.label}`} selected={data.status} setData={setData} /> @@ -275,7 +272,7 @@ export default function Form({
@@ -333,7 +330,7 @@ export default function Form({
diff --git a/resources/ts/back/Pages/News/Index.tsx b/resources/ts/back/Pages/News/Index.tsx index 055f96b3..92379494 100644 --- a/resources/ts/back/Pages/News/Index.tsx +++ b/resources/ts/back/Pages/News/Index.tsx @@ -19,65 +19,37 @@ import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AppEnv, - AuthProp, - NewsCategoryModel, - NewsModel, - Resource, -} from "@/back/types/global"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, Resource } from "@/back/types/global"; +import { NewsModel, NewsCategoryModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Index({ - newsModels, - searchFields, - modelName, -}: { - newsModels: Resource; - searchFields: string; - modelName: string; -}) { - const { appEnv, auth } = usePage().props as unknown as { - appEnv: AppEnv; - auth: AuthProp; - }; - const { viewAny, viewTrash, create } = auth.policies.news; - const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; - const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; - const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute - ? [Views.RESTORATION, Views.FORCEDELETION] - : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; - const columns = [ +const getColumns = (appEnv: AppEnv, viewAnyNewsCategories: boolean) => { + return [ { accessorKey: "title", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("title")); - }, + cell: ({ row }: { row: Row }) => ( + + ), }, { accessorKey: "categories", header: () => (

{str( - useTrans("models.classes.news-category", { + GetTranslation("models.classes.news-category", { choice: 2, }), ) @@ -108,14 +80,17 @@ export default function Index({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.news-category", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.news-category", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -131,7 +106,7 @@ export default function Index({
) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, @@ -140,7 +115,7 @@ export default function Index({ accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( }) => { return ( - + ); }, }, @@ -156,7 +131,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( }) => ( - {useFormatedDate(row.getValue("updated_at"))} + {GetFormatedDate(row.getValue("updated_at"))} ), }, ]; +}; + +export default function Index({ + newsModels, + searchFields, + modelName, +}: { + newsModels: Resource; + searchFields: string; + modelName: string; +}) { + const { appEnv, auth } = usePage().props as unknown as { + appEnv: AppEnv; + auth: AuthProp; + }; + const { viewAny, viewTrash, create } = auth.policies.news; + const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; + const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; + const isArchiveRoute = route().current(`back.${modelName}.trash`); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; + const columns = getColumns(appEnv, viewAnyNewsCategories); const transModel = useTrans(`models.classes.${modelName}`, { choice: 2 }); const transArchiveTitle = useTrans("crud.helpers.archives_model", { @@ -178,6 +183,7 @@ export default function Index({ .ucFirst() .value(); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -186,14 +192,29 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transCrudBackList}

} /> ) ); }; + + const transBackAccessToNewsCategory = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.news-category", { choice: 2 }), + }, + }); + const transBackAccessToNewsTag = useTrans("back.crud_access_to", { + params: { + target: useTrans("models.classes.news-tag", { choice: 2 }), + }, + }); + const transBackAccessToArchived = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transBackAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -203,16 +224,7 @@ export default function Index({ link={route(`back.news-categories.index`)} content={} tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.news-category", - { choice: 2 }, - ), - }, - })} -

+

{transBackAccessToNewsCategory}

} variant="outline" /> @@ -221,18 +233,7 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "models.classes.news-tag", - { choice: 2 }, - ), - }, - })} -

- } + tooltipContent={

{transBackAccessToNewsTag}

} variant="outline" /> )} @@ -240,17 +241,7 @@ export default function Index({ } - tooltipContent={ -

- {useTrans("back.crud_access_to", { - params: { - target: useTrans( - "back.archived_entries", - ), - }, - })} -

- } + tooltipContent={

{transBackAccessToArchived}

} variant="outline" /> )} @@ -258,9 +249,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transBackAddEntry}

} /> )} diff --git a/resources/ts/back/Pages/News/Show.tsx b/resources/ts/back/Pages/News/Show.tsx index 94cccd96..435d550d 100644 --- a/resources/ts/back/Pages/News/Show.tsx +++ b/resources/ts/back/Pages/News/Show.tsx @@ -8,49 +8,30 @@ import { Badge } from "@/components/ui/badge"; import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AppEnv, AuthProp, SingleResource } from "@/back/types/global"; import { - AppEnv, - AuthProp, - NewsCategoryModel, NewsModel, + NewsCategoryModel, NewsTagModel, - SingleResource, - TranslationField, -} from "@/back/types/global"; +} from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; import useLocale from "@/store/use-locale-store"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Show({ - data, - modelName, -}: { - data: SingleResource; - modelName: string; -}) { - const { auth, appEnv } = usePage().props as unknown as { - auth: AuthProp; - appEnv: AppEnv; - }; - const { viewAny } = auth.policies.news; - const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; - const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; - const newsModel = data.data as NewsModel; - const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; - const transTitle = useTrans("crud.helpers.visualization_model", { - params: { - model: useTrans(`models.classes.${modelName}`, { choice: 1 }), - }, - }); - const columns = [ +const getColumns = ( + appEnv: AppEnv, + viewAnyNewsCategories: boolean, + viewAnyNewsTags: boolean, +) => { + return [ { accessorKey: "seo_title", - header: str(useTrans("validation.custom.seo.title")) + header: str(GetTranslation("validation.custom.seo.title")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -58,13 +39,13 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "seo_description", - header: str(useTrans("validation.custom.seo.description")) + header: str(GetTranslation("validation.custom.seo.description")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -72,34 +53,36 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "title", - header: str(useTrans("validation.attributes.title")) + header: str(GetTranslation("validation.attributes.title")) .ucFirst() .value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell(value); - }, + cell: ({ value }: { value: TranslationField }) => ( + + ), }, { accessorKey: "slug", - header: str(useTrans("validation.custom.slug")).ucFirst().value(), + header: str(GetTranslation("validation.custom.slug")) + .ucFirst() + .value(), cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] ? ( value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "content", - header: str(useTrans("validation.attributes.content")) + header: str(GetTranslation("validation.attributes.content")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -107,20 +90,24 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "status", - header: str(useTrans("validation.custom.status")).ucFirst().value(), + header: str(GetTranslation("validation.custom.status")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { - return ; + return ; }, }, { accessorKey: "categories", - header: str(useTrans("models.classes.news-category", { choice: 2 })) + header: str( + GetTranslation("models.classes.news-category", { choice: 2 }), + ) .ucFirst() .value(), cell: ({ value }: { value?: NewsCategoryModel[] }) => { @@ -143,14 +130,17 @@ export default function Show({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.news-category", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.news-category", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -166,14 +156,16 @@ export default function Show({ ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, }, { accessorKey: "tags", - header: str(useTrans("models.classes.news-tag", { choice: 2 })) + header: str( + GetTranslation("models.classes.news-tag", { choice: 2 }), + ) .ucFirst() .value(), cell: ({ value }: { value?: NewsTagModel[] }) => { @@ -196,14 +188,17 @@ export default function Show({ } tooltipContent={

- {useTrans("back.access_model", { - params: { - model: useTrans( - "models.classes.news-category", - { choice: 1 }, - ), + {GetTranslation( + "back.access_model", + { + params: { + model: GetTranslation( + "models.classes.news-category", + { choice: 1 }, + ), + }, }, - })} + )}

} type="button" @@ -219,34 +214,34 @@ export default function Show({ ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

); }, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")) + header: str(GetTranslation("validation.attributes.created_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => { return ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ); }, }, { accessorKey: "picture", - header: str(useTrans("validation.attributes.image")) + header: str(GetTranslation("validation.attributes.image")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - + ), }, { accessorKey: "picture_alt", - header: str(useTrans("validation.custom.image_alt")) + header: str(GetTranslation("validation.custom.image_alt")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -254,13 +249,13 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "picture_title", - header: str(useTrans("validation.custom.image_title")) + header: str(GetTranslation("validation.custom.image_title")) .ucFirst() .value(), cell: ({ value }: { value: TranslationField }) => @@ -268,50 +263,74 @@ export default function Show({ value[appEnv.locale] ) : (

- {useTrans("back.table_not_known")} + {GetTranslation("back.table_not_known")}

), }, { accessorKey: "published_at", - header: str(useTrans("validation.custom.published_at")) + header: str(GetTranslation("validation.custom.published_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value, useLocale.use.timezone(), true)} + {GetFormatedDate(value, useLocale.use.timezone(), true)} ), }, { accessorKey: "unpublished_at", - header: str(useTrans("validation.custom.unpublished_at")) + header: str(GetTranslation("validation.custom.unpublished_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")) + header: str(GetTranslation("validation.attributes.updated_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")) + header: str(GetTranslation("validation.attributes.deleted_at")) .ucFirst() .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} + {GetFormatedDate(value)} ), }, ]; +}; +export default function Show({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { auth, appEnv } = usePage().props as unknown as { + auth: AuthProp; + appEnv: AppEnv; + }; + const { viewAny } = auth.policies.news; + const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; + const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; + const newsModel = data.data as NewsModel; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; + const transTitle = useTrans("crud.helpers.visualization_model", { + params: { + model: useTrans(`models.classes.${modelName}`, { choice: 1 }), + }, + }); + const columns = getColumns(appEnv, viewAnyNewsCategories, viewAnyNewsTags); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( viewAny && ( @@ -319,9 +338,7 @@ export default function Show({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transCrudBackList}

} /> ) diff --git a/resources/ts/back/Pages/NewsCategory/Create.tsx b/resources/ts/back/Pages/NewsCategory/Create.tsx index 274e1d19..2bc61769 100644 --- a/resources/ts/back/Pages/NewsCategory/Create.tsx +++ b/resources/ts/back/Pages/NewsCategory/Create.tsx @@ -7,45 +7,49 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import { - AuthProp, - NewsCategoryModel, - SingleResource, -} from "@/back/types/global"; -import Form from "./Form"; +import { AuthProp, SingleResource } from "@/back/types/global"; +import { NewsCategoryModel } from "@/back/types/others"; +import Form from "@/back/Pages/NewsCategory/Form"; import str from "@/hooks/use-string"; -export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) { - const { viewAny } = (usePage().props.auth as AuthProp).policies.newsCategories; +export default function Create({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { + const { viewAny } = (usePage().props.auth as AuthProp).policies + .newsCategories; const newsCategoryModel = data.data as NewsCategoryModel; const singularModelName = str(modelName).singular().value(); - const transTitle = useTrans("crud.helpers.creation_model", - { - params: { - model: useTrans(`models.classes.${singularModelName}`, { - choice: 1, - }), - }, + + // Translations. + const transBackToList = useTrans("back.crud_back_to_list"); + const transTitle = useTrans("crud.helpers.creation_model", { + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), }, - ); + }); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
- + })} + />
); diff --git a/resources/ts/back/Pages/NewsCategory/Index.tsx b/resources/ts/back/Pages/NewsCategory/Index.tsx index 67880cb8..8b743784 100644 --- a/resources/ts/back/Pages/NewsCategory/Index.tsx +++ b/resources/ts/back/Pages/NewsCategory/Index.tsx @@ -1,11 +1,7 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; -import { - ArchiveIcon, - ArrowLeftIcon, - Plus, -} from "lucide-react"; +import { ArchiveIcon, ArrowLeftIcon, Plus } from "lucide-react"; import { Row } from "@tanstack/react-table"; // * Components shadcn import { Badge } from "@/components/ui/badge"; @@ -15,13 +11,76 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { AuthProp, NewsCategoryModel, Resource } from "@/back/types/global"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AuthProp, Resource } from "@/back/types/global"; +import { NewsCategoryModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "news", + header: () => ( +

+ {str( + GetTranslation("back.associated_model", { + params: { + model: GetTranslation("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => ( +
+

{row.original.news_count ?? 0}

+
+ ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ newsCategoryModels, @@ -45,62 +104,7 @@ export default function Index({ Views.DUPLICATION, Views.ARCHIVATION, ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("name")); - }, - }, - { - accessorKey: "news", - header: () => ( -

- {str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.news", { - choice: 2, - }), - }, - choice: 2, - }), - ) - .ucFirst() - .value()} -

- ), - cell: ({ row }: { row: Row }) => ( -
-

{row.original.news_count ?? 0}

-
- ), - }, - { - accessorKey: "updated_at", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {useFormatedDate(row.getValue("updated_at"))} - - ), - }, - ]; + const columns = getColumns(); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, @@ -112,6 +116,7 @@ export default function Index({ .ucFirst() .value(); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -120,14 +125,19 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transCrudBackList}

} /> ) ); }; + + const transCrudAccessTo = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transCrudAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -136,9 +146,7 @@ export default function Index({ } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} + tooltipContent={

{transCrudAccessTo}

} variant="outline" /> )} @@ -146,9 +154,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transCrudAddEntry}

} /> )} diff --git a/resources/ts/back/Pages/NewsCategory/Show.tsx b/resources/ts/back/Pages/NewsCategory/Show.tsx index 7f075b82..6755d441 100644 --- a/resources/ts/back/Pages/NewsCategory/Show.tsx +++ b/resources/ts/back/Pages/NewsCategory/Show.tsx @@ -1,97 +1,119 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; import { AppEnv, AuthProp, - NewsCategoryModel, Resource, SingleResource, - TranslationField, } from "@/back/types/global"; +import { NewsCategoryModel } from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; -import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +const getColumns = (appEnv: AppEnv) => { + return [ + { + accessorKey: "name", + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), + }, + { + accessorKey: "slug", + header: str(GetTranslation("validation.custom.slug")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {GetTranslation("back.table_not_known")} +

+ ), + }, + { + accessorKey: "created_at", + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + {GetFormatedDate(value)} + ); + }, + }, + { + accessorKey: "updated_at", + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => ( + {GetFormatedDate(value)} + ), + }, + ]; +}; -export default function Show({ data, modelName, news }: { data: SingleResource, modelName: string, news: Resource }) { +export default function Show({ + data, + modelName, + news, +}: { + data: SingleResource; + modelName: string; + news: Resource; +}) { const { auth, appEnv } = usePage().props as unknown as { auth: AuthProp; appEnv: AppEnv; }; const { viewAny } = auth.policies.newsCategories; const model = data.data as NewsCategoryModel; - const actionModels = [ - Views.EDITION, - Views.DELETION, - ]; + const actionModels = [Views.EDITION, Views.DELETION]; const singularModelName = str(modelName).singular().value(); const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, }); - const columns = [ - { - accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } - }, - { - accessorKey: "slug", - header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), - }, - { - accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => { - return ( - {useFormatedDate(value)} - ) - }, - }, - { - accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} - ), - }, - ]; + const columns = getColumns(appEnv); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transCrudBackList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
- + })} + />
); diff --git a/resources/ts/back/Pages/NewsTag/Index.tsx b/resources/ts/back/Pages/NewsTag/Index.tsx index 1c866d25..f841f20d 100644 --- a/resources/ts/back/Pages/NewsTag/Index.tsx +++ b/resources/ts/back/Pages/NewsTag/Index.tsx @@ -16,13 +16,102 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; -import { AuthProp, NewsTagModel, Resource } from "@/back/types/global"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; +import { AuthProp, Resource } from "@/back/types/global"; +import { NewsTagModel } from "@/back/types/others"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; + +const getColumns = () => { + return [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + ), + }, + { + accessorKey: "color", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return ( + + +
+ + {row.getValue("color")} + + ); + }, + }, + { + accessorKey: "news", + header: () => ( +

+ {str( + GetTranslation("back.associated_model", { + params: { + model: GetTranslation("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => ( +
+

{row.original.news_count ?? 0}

+
+ ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {GetFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; +}; export default function Index({ newsTagModels, @@ -46,88 +135,7 @@ export default function Index({ Views.DUPLICATION, Views.ARCHIVATION, ]; - const columns = [ - { - accessorKey: "name", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell(row.getValue("name")); - }, - }, - { - accessorKey: "color", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return ( - - -
-
- {row.getValue("color")} -
- ); - }, - }, - { - accessorKey: "news", - header: () => ( -

- {str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.news", { - choice: 2, - }), - }, - choice: 2, - }), - ) - .ucFirst() - .value()} -

- ), - cell: ({ row }: { row: Row }) => ( -
-

{row.original.news_count ?? 0}

-
- ), - }, - { - accessorKey: "updated_at", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => ( - - {useFormatedDate(row.getValue("updated_at"))} - - ), - }, - ]; + const columns = getColumns(); const transModel = useTrans( `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, @@ -139,6 +147,7 @@ export default function Index({ .ucFirst() .value(); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { return ( isArchiveRoute && @@ -147,14 +156,19 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_back_to_list")}

- } + tooltipContent={

{transCrudBackList}

} />
) ); }; + + const transCrudAccessTo = useTrans("back.crud_access_to", { + params: { + target: useTrans("back.archived_entries"), + }, + }); + const transCrudAddEntry = useTrans("back.crud_add_entry"); const afterNode = () => { return ( !isArchiveRoute && ( @@ -163,9 +177,7 @@ export default function Index({ } - tooltipContent={

{useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

} + tooltipContent={

{transCrudAccessTo}

} variant="outline" /> )} @@ -173,9 +185,7 @@ export default function Index({ } - tooltipContent={ -

{useTrans("back.crud_add_entry")}

- } + tooltipContent={

{transCrudAddEntry}

} /> )} diff --git a/resources/ts/back/Pages/NewsTag/Show.tsx b/resources/ts/back/Pages/NewsTag/Show.tsx index 893e99c6..38c3e2a9 100644 --- a/resources/ts/back/Pages/NewsTag/Show.tsx +++ b/resources/ts/back/Pages/NewsTag/Show.tsx @@ -1,114 +1,145 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DetailsTable from "@/back/Components/Table/DetailsTable"; import ModelActions from "@/back/Components/ModelActions"; -import { Views } from "@/lib/utils"; -import { useFormatedDate } from "@/hooks/use-formated-value"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; +import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell"; +import { GetFormatedDate, GetTranslation, Views } from "@/lib/utils"; import { AppEnv, AuthProp, - NewsTagModel, Resource, SingleResource, - TranslationField, } from "@/back/types/global"; +import { NewsTagModel } from "@/back/types/others"; +import { TranslationField } from "@/back/types/i18n"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +const getColumns = (appEnv: AppEnv) => { + return [ + { + accessorKey: "name", + header: str(GetTranslation("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => ( + + ), + }, + { + accessorKey: "slug", + header: str(GetTranslation("validation.custom.slug")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {GetTranslation("back.table_not_known")} +

+ ), + }, + { + accessorKey: "color", + header: str(GetTranslation("validation.custom.color")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + + +
+ + {value} + + ); + }, + }, + { + accessorKey: "created_at", + header: str(GetTranslation("validation.attributes.created_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => { + return ( + {GetFormatedDate(value)} + ); + }, + }, + { + accessorKey: "updated_at", + header: str(GetTranslation("validation.attributes.updated_at")) + .ucFirst() + .value(), + cell: ({ value }: { value: string }) => ( + {GetFormatedDate(value)} + ), + }, + ]; +}; -export default function Show({ data, modelName, news }: { data: SingleResource, modelName: string, news: Resource }) { +export default function Show({ + data, + modelName, + news, +}: { + data: SingleResource; + modelName: string; + news: Resource; +}) { const { auth, appEnv } = usePage().props as unknown as { auth: AuthProp; appEnv: AppEnv; }; const { viewAny } = auth.policies.newsTags; const model = data.data as NewsTagModel; - const actionModels = [ - Views.EDITION, - Views.DELETION, - ]; + const actionModels = [Views.EDITION, Views.DELETION]; const singularModelName = str(modelName).singular().value(); const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) }, + params: { + model: useTrans(`models.classes.${singularModelName}`, { + choice: 1, + }), + }, }); - const columns = [ - { - accessorKey: "name", - header: str(useTrans("validation.attributes.name")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } - }, - { - accessorKey: "slug", - header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), - }, - { - accessorKey: "color", - header: str(useTrans("validation.custom.color")).ucFirst().value(), - cell: ({ value }: { value: string }) => { - return ( - - -
-
- {value} -
- ) - } - }, - { - accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => { - return ( - {useFormatedDate(value)} - ) - }, - }, - { - accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), - cell: ({ value }: { value: string }) => ( - {useFormatedDate(value)} - ), - }, - ]; + const columns = getColumns(appEnv); + const transCrudBackList = useTrans("back.crud_back_to_list"); const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transCrudBackList}

} + /> +
+ ) ); }; return ( - + { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - +
{ - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={

{transBackToList}

} + /> +
+ ) ); }; return ( - + (null); - const otherConfigs = Object.entries(model!.config ?? {}).filter(([configLocale]) => configLocale !== appEnv.locale); + const otherConfigs = Object.entries(model!.config ?? {}).filter( + ([configLocale]) => configLocale !== appEnv.locale, + ); // Translations. - const transSelectConfigLocale = useTrans('back.config_select_fields'); + const transSelectConfigLocale = useTrans("back.config_select_fields"); const transDialogTitle = useTrans("back.are_you_sure"); - const transDialogParagraph = useTrans("back.config_save_warning", { params: { locale: str(appEnv.locale).upperCase().value() } }); + const transDialogParagraph = useTrans("back.config_save_warning", { + params: { locale: str(appEnv.locale).upperCase().value() }, + }); const transDialogParagraphList = useTrans("back.config_save_warning_list", { - params: { models: useTrans('models.classes.dynamic-page', { choice: 2 }) }, + params: { + models: useTrans("models.classes.dynamic-page", { choice: 2 }), + }, choice: 2, }); const transDialogCancel = useTrans("back.no_cancel"); const transDialogSave = useTrans("back.yes_update"); - + const transJsonExportTooltip = useTrans("back.json_editor.export_tooltip"); + const transModelName = useTrans(`models.classes.${modelName}`, { + choice: 1, + }); + const transSubmitBtn = useTrans(`models.classes.${modelName}`, { + choice: 1, + }); /** Form section */ const { post, setData, data } = useForm({ label: model?.label ? model?.label[appEnv.locale] : "", view: model?.view, - config: model?.config ? model?.config[appEnv.locale] ?? [] : [], + config: model?.config ? (model?.config[appEnv.locale] ?? []) : [], }); const submit = useCrudSubmit({ @@ -88,38 +103,51 @@ export default function Form({ action, model, post, - data + data, }); const resetConfig = (localeData: string) => { - const customLocaleData = str(localeData).lowerCase().value() - setData("config", model?.config ? model?.config[customLocaleData] ?? [] : []); - } + const customLocaleData = str(localeData).lowerCase().value(); + setData( + "config", + model?.config ? (model?.config[customLocaleData] ?? []) : [], + ); + }; /** * Check if auth user must be notified when the config is updated. * @return boolean */ const mustBeNotified = () => { - return !route().current(`back.page-configs.create`) - && model?.pages - && model?.pages.length - && data.config !== model?.config[appEnv.locale] + return ( + !route().current(`back.page-configs.create`) && + model?.pages && + model?.pages.length && + data.config !== model?.config[appEnv.locale] + ); }; useEffect(() => { - const isEmpty = data.config === null || (typeof data.config === "object" && Object.keys(data.config).length === 0); + const isEmpty = + data.config === null || + (typeof data.config === "object" && + Object.keys(data.config).length === 0); if (isEmpty && selectedConfig !== null) { setSelectedConfig(null); } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [data.config]); useEffect(() => { if (selectedConfig !== null) { - const lowerSelectedLocale = str(selectedConfig ?? "FR").slug().lowerCase().value(); - setData('config', model?.config[lowerSelectedLocale] ?? []); + const lowerSelectedLocale = str(selectedConfig ?? "FR") + .slug() + .lowerCase() + .value(); + setData("config", model?.config[lowerSelectedLocale] ?? []); } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedConfig]); return ( @@ -140,7 +168,9 @@ export default function Form({ }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.label} setData={setData} @@ -154,7 +184,9 @@ export default function Form({ }, choice: 2, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" required={false} value={data.view ?? ""} @@ -168,18 +200,26 @@ export default function Form({ > {/* Import configuration from json file. */} {auth.user.role === enumUserRole.conceptor.value && ( -
+
{ - const newConfig = (!overwrite) ? [...data.config, ...value] : value; - setData('config', newConfig as ConfigField[]) - setResetState(prev => prev + 1) + const newConfig = !overwrite + ? [...data.config, ...value] + : value; + setData("config", newConfig as ConfigField[]); + setResetState((prev) => prev + 1); }} />
)} {/* Show only on editing page. */} - {route().current('back.page-configs.edit') && ( + {route().current("back.page-configs.edit") && (
{/* Select config from another locale */}