refactor: hudge bump !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!111

Fixes #59
This commit is contained in:
Jeremy Munsch 2026-10-16 12:07:08 +02:00 • committed by Jérémy Munsch
parent 9116a4bf88
commit 9efcb32ee1
Signed by: forge-joniko
GPG key ID: D7EFE2F5CB6CC0E4
173 changed files with 10299 additions and 9503 deletions

View file

@ -30,24 +30,19 @@ module.exports = {
es2021: true,
node: true,
},
ignorePatterns: ["resources/ts/components/ui/**"],
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:jsx-a11y/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/recommended",
"airbnb",
"airbnb/hooks",
"plugin:prettier/recommended",
],
plugins: [
"react",
"react-hooks",
"jsx-a11y",
"@typescript-eslint",
"prettier",
],
plugins: ["react", "react-hooks", "@typescript-eslint", "import", "prettier"],
rules: {
"no-undef": "off",
"react/display-name": "off",
"react/jsx-key": "off",
"react/jsx-filename-extension": ["error", { extensions: [".tsx", ".jsx"] }],
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",

1
.gitignore vendored
View file

@ -25,3 +25,4 @@ Thumbs.db
.npmrc
public/favicon-back
/docker-compose.yml

File diff suppressed because it is too large Load diff

View file

@ -1,75 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Middlewares;
use App\Enums\Contact\ActivitySectorEnum;
use App\Enums\Contact\ObjectEnum;
use Domain\Models\ValueObjects\Products\BreedingMethod;
use Domain\Models\ValueObjects\Products\Business;
use Domain\Models\ValueObjects\Products\ProductCategory;
use Domain\Models\ValueObjects\Products\ProductFormat;
use Domain\Models\ValueObjects\Products\Technology;
use Domain\Models\ValueObjects\Recipes\ConsumptionTime;
use Domain\Models\ValueObjects\Recipes\Inspiration;
use Domain\Models\ValueObjects\Recipes\Season;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Inertia\Middleware;
use Uwil\LaravelCommon\Helpers\InertiaHelper;
use Uwil\LaravelCommon\Support\InertiaSharedRegistry;
use Uwil\LaravelDynamicPages\Enums\PageStatusEnum;
use Uwil\LaravelDynamicPages\Models\DynamicPage;
class HandleInertiaRequests extends Middleware
{
/**
* Define the props that are shared by default.
*
* @return array<array-key,mixed>
*/
public function share(Request $request): array
{
// Load all published dynamic pages with each parent page relationship.
$dynamicPageModels = DynamicPage::getModelsCached()
->where('status', PageStatusEnum::published);
$dynamicPages = [];
foreach ($dynamicPageModels as $dynamicPageModel) {
$pascalCase =
str_replace(' ', '', ucwords(str_replace('-', ' ', $dynamicPageModel->id_key)));
$dynamicPages["page{$pascalCase}"] = $dynamicPageModel;
}
$props = [
...InertiaHelper::errorProps(parent::share($request)),
'dynamicPages' => $dynamicPages,
// More props here.
];
return array_replace_recursive(
$props,
InertiaSharedRegistry::resolve($request)
);
}
public function shareOnce(Request $request): array
{
return array_merge(parent::shareOnce($request), [
'recaptchaKey' => fn () => Config::string('services.google.recaptcha.public'),
'activitySectorEnum' => fn () => ActivitySectorEnum::toArray(),
'objectEnum' => fn () => ObjectEnum::toArray(),
'breedingMethodEnum' => fn () => BreedingMethod::toArray(),
'businessEnum' => fn () => Business::toArray(),
'productCategoryEnum' => fn () => ProductCategory::toArray(),
'productFormatEnum' => fn () => ProductFormat::toArray(),
'technologyEnum' => fn () => Technology::toArray(),
'consumptionTimeEnum' => fn () => ConsumptionTime::toArray(),
'inspirationEnum' => fn () => Inspiration::toArray(),
'seasonEnum' => fn () => Season::toArray(),
]);
}
}

View file

@ -91,6 +91,11 @@ class SecureHeaders
// * BAN address autocomplete (api-adresse.data.gouv.fr)
'https://api-adresse.data.gouv.fr',
'https://maps.googleapis.com',
// * Google reCAPTCHA
'https://www.google.com/recaptcha/',
'https://recaptcha.google.com/recaptcha/',
'https://www.google.com',
'https://www.recaptcha.net/',
// * VITE DEV
$viteDevSocket,
$viteDevOrigin,

View file

@ -16,11 +16,11 @@ use Illuminate\Validation\Rules\Enum;
class StoreProductRequest extends FormRequest
{
protected const MAX_FILE_SIZE_KB = 5120;
protected const int MAX_FILE_SIZE_KB = 5120;
protected const PICTURE_WIDTH = 800;
protected const int PICTURE_WIDTH = 800;
protected const PICTURE_HEIGHT = 800;
protected const int PICTURE_HEIGHT = 800;
public function __construct(
private readonly AdminAuthService $authService

View file

@ -18,11 +18,11 @@ class UpdateProductRequest extends StoreProductRequest
return array_merge(parent::rules(), [
'pdf' => [
'nullable',
[$this, 'validatePdf'],
$this->validatePdf(...),
],
'picture' => [
'required',
[$this, 'validatePicture'],
$this->validatePicture(...),
],
]);
}
@ -83,10 +83,10 @@ class UpdateProductRequest extends StoreProductRequest
default => 0,
};
if (($sizeInBytes / 1024) > static::MAX_FILE_SIZE_KB) {
if (($sizeInBytes / 1024) > self::MAX_FILE_SIZE_KB) {
$fail(trans('validation.max.file', [
'attribute' => $this->attributes()[$attribute] ?? $attribute,
'max' => static::MAX_FILE_SIZE_KB,
'max' => self::MAX_FILE_SIZE_KB,
]));
}
}

View file

@ -15,11 +15,11 @@ use Illuminate\Validation\Rules\Enum;
class StoreRecipeRequest extends FormRequest
{
protected const MAX_FILE_SIZE_KB = 5120;
protected const int MAX_FILE_SIZE_KB = 5120;
protected const PICTURE_WIDTH = 800;
protected const int PICTURE_WIDTH = 800;
protected const PICTURE_HEIGHT = 800;
protected const int PICTURE_HEIGHT = 800;
public function __construct(
private readonly AdminAuthService $authService

View file

@ -21,7 +21,7 @@ class UpdateRecipeRequest extends StoreRecipeRequest
return array_merge(parent::rules(), [
'picture' => [
'required',
[$this, 'validatePicture'],
$this->validatePicture(...),
],
]);
}
@ -42,8 +42,8 @@ class UpdateRecipeRequest extends StoreRecipeRequest
$valuePath,
$fail,
(object) [
'minWidth' => static::PICTURE_WIDTH,
'maxWidth' => static::PICTURE_WIDTH,
'minWidth' => self::PICTURE_WIDTH,
'maxWidth' => self::PICTURE_WIDTH,
'minHeight' => self::PICTURE_HEIGHT,
'maxHeight' => self::PICTURE_HEIGHT,
]
@ -61,10 +61,10 @@ class UpdateRecipeRequest extends StoreRecipeRequest
default => 0,
};
if (($sizeInBytes / 1024) > static::MAX_FILE_SIZE_KB) {
if (($sizeInBytes / 1024) > self::MAX_FILE_SIZE_KB) {
$fail(trans('validation.max.file', [
'attribute' => $this->attributes()[$attribute] ?? $attribute,
'max' => static::MAX_FILE_SIZE_KB,
'max' => self::MAX_FILE_SIZE_KB,
]));
}
}

View file

@ -23,11 +23,11 @@ use Illuminate\Support\Str;
use Laravel\Scout\Searchable;
use Ramsey\Uuid\Uuid;
use Spatie\Translatable\HasTranslations;
use Uwil\LaravelActivityLogs\Traits\HasActivityLog;
use Uwil\LaravelBackend\Interfaces\TranslatableModel;
use Uwil\LaravelBackend\Traits\Models\HasActivityLog;
use Uwil\LaravelBackend\Traits\Models\HasCache;
use Uwil\LaravelBackend\Traits\Models\HasModelNaming;
use Uwil\LaravelBackend\Traits\Models\HasUwilImages;
use Uwil\LaravelI18n\Interfaces\TranslatableModel;
// phpcs:disable Generic.Files.LineLength.TooLong
@ -56,7 +56,7 @@ use Uwil\LaravelI18n\Interfaces\TranslatableModel;
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelActivityLogs\Models\ActivityLog> $activityLogs
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelBackend\Models\ActivityLog> $activityLogs
* @property-read array $translatable_columns_from
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Recipe> $recipes
* @property-read mixed $translations
@ -149,6 +149,16 @@ class Product extends Model implements TranslatableModel
return $this->belongsToMany(Recipe::class);
}
/**
* Relations should be share to views.
*
* @return array<int,string>
*/
public static function getPropsRelations(): array
{
return self::getCacheRelations();
}
private static function manageFields(self $model): void
{
self::assertNameIsUnique($model->name, $model->id);

View file

@ -20,11 +20,11 @@ use Illuminate\Support\Str;
use Laravel\Scout\Searchable;
use Ramsey\Uuid\Uuid;
use Spatie\Translatable\HasTranslations;
use Uwil\LaravelActivityLogs\Traits\HasActivityLog;
use Uwil\LaravelBackend\Interfaces\TranslatableModel;
use Uwil\LaravelBackend\Traits\Models\HasActivityLog;
use Uwil\LaravelBackend\Traits\Models\HasCache;
use Uwil\LaravelBackend\Traits\Models\HasModelNaming;
use Uwil\LaravelBackend\Traits\Models\HasUwilImages;
use Uwil\LaravelI18n\Interfaces\TranslatableModel;
// phpcs:disable Generic.Files.LineLength.TooLong
@ -51,7 +51,7 @@ use Uwil\LaravelI18n\Interfaces\TranslatableModel;
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelActivityLogs\Models\ActivityLog> $activityLogs
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelBackend\Models\ActivityLog> $activityLogs
* @property-read array $translatable_columns_from
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Product> $products
* @property-read mixed $translations
@ -136,6 +136,16 @@ class Recipe extends Model implements TranslatableModel
return $this->belongsToMany(Product::class);
}
/**
* Relations should be share to views.
*
* @return array<int,string>
*/
public static function getPropsRelations(): array
{
return self::getCacheRelations();
}
private static function manageFields(self $model): void
{
self::assertNameIsUnique($model->name, $model->id);

View file

@ -8,16 +8,31 @@ use App\Contracts\Directories\ProductDirectory;
use App\Contracts\Directories\RecipeDirectory;
use App\Directories\EloquentProductDirectory;
use App\Directories\EloquentRecipeDirectory;
use App\Enums\Contact\ActivitySectorEnum;
use App\Enums\Contact\ObjectEnum;
use App\Services\AdminAuthService;
use Domain\Models\ValueObjects\Pagination;
use Domain\Models\ValueObjects\Products\BreedingMethod;
use Domain\Models\ValueObjects\Products\Business;
use Domain\Models\ValueObjects\Products\ProductCategory;
use Domain\Models\ValueObjects\Products\ProductFormat;
use Domain\Models\ValueObjects\Products\Technology;
use Domain\Models\ValueObjects\Recipes\ConsumptionTime;
use Domain\Models\ValueObjects\Recipes\Inspiration;
use Domain\Models\ValueObjects\Recipes\Season;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
use Uwil\LaravelBackend\Support\ModelListRegistry;
use Uwil\LaravelCommon\Support\InertiaSharedRegistry;
use Uwil\LaravelDynamicPages\Enums\PageStatusEnum;
use Uwil\LaravelDynamicPages\Models\DynamicPage;
class AppServiceProvider extends ServiceProvider
{
@ -47,6 +62,8 @@ class AppServiceProvider extends ServiceProvider
{
$this->dateSetup();
$this->laravelGlobalSetup();
$this->registerSharedInertiaProps();
$this->registerModelsInBackendRegistry();
}
private function laravelGlobalSetup(): void
@ -58,6 +75,53 @@ class AppServiceProvider extends ServiceProvider
URL::forceScheme('https');
}
private function registerSharedInertiaProps(): void
{
InertiaSharedRegistry::add('dynamicPages', function (): array {
if (! Schema::hasTable('dynamic_pages')) {
return [];
}
$dynamicPageModels = DynamicPage::getModelsCached()
->where('status', PageStatusEnum::published);
$dynamicPages = [];
foreach ($dynamicPageModels as $dynamicPageModel) {
$pascalCase = str_replace(' ', '', ucwords(str_replace('-', ' ', $dynamicPageModel->id_key)));
$dynamicPages["page{$pascalCase}"] = $dynamicPageModel;
}
return $dynamicPages;
});
InertiaSharedRegistry::add('activitySectorEnum', fn () => ActivitySectorEnum::toArray());
InertiaSharedRegistry::add('objectEnum', fn () => ObjectEnum::toArray());
InertiaSharedRegistry::add('breedingMethodEnum', fn () => BreedingMethod::toArray());
InertiaSharedRegistry::add('businessEnum', fn () => Business::toArray());
InertiaSharedRegistry::add('productCategoryEnum', fn () => ProductCategory::toArray());
InertiaSharedRegistry::add('productFormatEnum', fn () => ProductFormat::toArray());
InertiaSharedRegistry::add('technologyEnum', fn () => Technology::toArray());
InertiaSharedRegistry::add('consumptionTimeEnum', fn () => ConsumptionTime::toArray());
InertiaSharedRegistry::add('inspirationEnum', fn () => Inspiration::toArray());
InertiaSharedRegistry::add('seasonEnum', fn () => Season::toArray());
}
private function registerModelsInBackendRegistry(): void
{
ModelListRegistry::add(
2,
'products',
trans_choice('models.classes.product', 1),
'name',
);
ModelListRegistry::add(
3,
'recipes',
trans_choice('models.classes.recipe', 1),
'name',
);
}
private function dateSetup(): void
{
foreach ([\LC_TIME, \LC_MESSAGES, \LC_COLLATE, \LC_CTYPE, \LC_MONETARY] as $constant) {
@ -77,6 +141,7 @@ class AppServiceProvider extends ServiceProvider
private function requestMacro(): void
{
Request::macro('pagination', function (int $defaultPageSize = 25): Pagination {
/** @var \Illuminate\Http\Request $this */
if ($this->has('offset') || $this->has('limit')) {
return Pagination::ofOffsetAndLimit(
$this->integer('offset', 0),

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Providers;
use Illuminate\Contracts\View\View as ContractsView;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function boot(): void
{
if ($this->app->runningInConsole()) {
return;
}
View::composer('*', function (ContractsView $view) {
$view->with('csp_nonce', Vite::cspNonce());
});
}
}

View file

@ -2,7 +2,6 @@
declare(strict_types=1);
use App\Http\Middlewares\HandleInertiaRequests;
use App\Http\Middlewares\HtmlSanitizer;
use App\Http\Middlewares\SecureHeaders;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
@ -14,19 +13,19 @@ use Uwil\LaravelBackend\Middlewares\Authenticate;
use Uwil\LaravelBackend\Middlewares\EncryptCookies;
use Uwil\LaravelBackend\Middlewares\LogoutUnpublishedUsers;
use Uwil\LaravelBackend\Middlewares\RedirectIfAuthenticated;
use Uwil\LaravelCommon\Middlewares\ForceLocale;
use Uwil\LaravelCommon\Middlewares\HandleInertiaRequests;
use Uwil\LaravelCommon\Middlewares\TrimStrings;
use Uwil\LaravelCommon\Middlewares\TrustHosts;
use Uwil\LaravelCommon\Middlewares\TrustProxies;
use Uwil\LaravelCommon\Middlewares\VerifyCsrfToken;
use Uwil\LaravelI18n\Middlewares\ForceLocale;
$redirectGuests = function (Request $request) {
$logins = [
'backend' => route('back.login'),
'frontend' => '/',
'backend' => route('back.login'),
'frontend' => '/',
];
foreach ($request->route()->gatherMiddleware() as $middleware) {
foreach ($request->route()?->gatherMiddleware() ?? [] as $middleware) {
if (\is_string($middleware) && str_contains($middleware, 'auth:')) {
$route = $logins[str_replace('auth:', '', $middleware)] ?? null;
if ($route) {
@ -43,7 +42,7 @@ $redirectUsers = function (Request $request) {
'backend' => route('back.dashboard.index'),
'frontend' => '/',
];
foreach ($request->route()->gatherMiddleware() as $middleware) {
foreach ($request->route()?->gatherMiddleware() ?? [] as $middleware) {
if (\is_string($middleware) && str_contains($middleware, 'auth:')) {
$route = $logins[str_replace('auth:', '', $middleware)] ?? null;
if ($route) {
@ -60,12 +59,6 @@ return function (Middleware $middleware) use ($redirectGuests, $redirectUsers):
$middleware->redirectGuestsTo($redirectGuests);
$middleware->redirectUsersTo($redirectUsers);
$middleware->alias([
'auth' => Authenticate::class,
'guest' => RedirectIfAuthenticated::class,
'htmlsanitize' => HtmlSanitizer::class,
]);
$middleware->web(append: [
ForceLocale::class,
HandleInertiaRequests::class,
@ -74,17 +67,19 @@ return function (Middleware $middleware) use ($redirectGuests, $redirectUsers):
TrimStrings::class,
TrustHosts::class,
TrustProxies::class,
VerifyCsrfToken::class,
LogoutUnpublishedUsers::class,
]);
$middleware->preventRequestForgery(except: [
'/csp-report',
]);
$middleware->group('saml', [
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
]);
$middleware->alias([
'auth' => Authenticate::class,
'guest' => RedirectIfAuthenticated::class,
'htmlsanitize' => HtmlSanitizer::class,
'auth' => Authenticate::class,
'guest' => RedirectIfAuthenticated::class,
'htmlsanitize' => HtmlSanitizer::class,
]);
};

View file

@ -5,15 +5,11 @@ declare(strict_types=1);
use App\Providers\AppServiceProvider;
use App\Providers\AuthServiceProvider;
use App\Providers\RouteServiceProvider;
use Uwil\K8S\Laravel\K8SServiceProvider;
use Uwil\LaravelCommon\Providers\AppServiceProvider as UwilAppServiceProvider;
use Uwil\LaravelCommon\Providers\TranslationServiceProvider;
use App\Providers\ViewServiceProvider;
return [
AppServiceProvider::class,
AuthServiceProvider::class,
RouteServiceProvider::class,
UwilAppServiceProvider::class,
TranslationServiceProvider::class,
K8SServiceProvider::class,
ViewServiceProvider::class,
];

1905
bun.lock

File diff suppressed because it is too large Load diff

View file

@ -9,24 +9,22 @@
],
"license": "MIT",
"require": {
"php": "^8.2",
"24slides/laravel-saml2": "^2.4",
"php": "^8.5",
"scaler-tech/laravel-saml2": "^2.5",
"diglactic/laravel-breadcrumbs": "^10.0",
"inertiajs/inertia-laravel": "^2.0",
"laravel/framework": "^12.0",
"inertiajs/inertia-laravel": "^3.0",
"laravel/framework": "^13.0",
"laravel/scout": "^11.3",
"laravel/telescope": "^5.7",
"laravel/tinker": "^2.10.1",
"laravel/tinker": "^3.0",
"meilisearch/meilisearch-php": "^1.16",
"monolog/monolog": "^3.0",
"psr/log": "^3.0",
"sentry/sentry-laravel": "^4.25",
"tightenco/ziggy": "^2.5",
"uwil/k8s-laravel": "^2.0",
"uwil/laravel-backend": "^4.0",
"uwil/laravel-common": "^5.1",
"uwil/laravel-dynamic-pages": "^1.0",
"uwil/laravel-i18n": "^2.1"
"uwil/k8s-laravel": "^3.0",
"uwil/admin-secure-laravel": "^6.0",
"uwil/laravel-dynamic-pages": "^5.0"
},
"require-dev": {
"barryvdh/laravel-ide-helper": "^3.7",
@ -37,8 +35,8 @@
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.29",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.50",
"nunomaduro/collision": "^8.9",
"phpunit/phpunit": "^12.0",
"slevomat/coding-standard": "^8.22"
},
"autoload": {
@ -117,6 +115,7 @@
"prefer-stable": true,
"repositories": [
{
"name": "lab.s-web.fr",
"type": "composer",
"url": "https://lab.s-web.fr/api/v4/group/23/-/packages/composer/packages.json"
}

2567
composer.lock generated

File diff suppressed because it is too large Load diff

21
config/cookie-notice.php Normal file
View file

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
return [
'google' => [
'recaptcha' => [
'public' => env('GOOGLE_RECAPTCHA_PUBLIC'),
'private' => env('GOOGLE_RECAPTCHA_PRIVATE'),
'version' => env('GOOGLE_RECAPTCHA_VERSION', '3') === '3' ? true : false,
'bypassKey' => 'bypass',
],
'analytics' => [
'id' => env('GOOGLE_ANALYTICS_ID'),
],
],
'matomo' => [
'site_id' => env('MATOMO_SITE_ID'),
],
];

View file

@ -147,7 +147,6 @@ return [
*/
'x509cert' => env('SAML2_SP_CERT_x509', ''),
'privateKey' => env('SAML2_SP_CERT_PRIVATEKEY', ''),
'basecert' => env('SAML2_SP_CERT_BASE', ''),
/**
*--------------------------------------------------------------------------

View file

@ -16,7 +16,7 @@ return [
* of their individual configuration, which simply provides a single
* and convenient way to enable or disable Telescope data storage.
*/
'enabled' => env('TELESCOPE_ENABLED', true),
'enabled' => env('TELESCOPE_ENABLED', false),
/**
*--------------------------------------------------------------------------

64
config/uwil-backend.php Normal file
View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
use Uwil\LaravelBackend\Models\User;
use Uwil\LaravelBackend\Requests\Users\StoreUserRequest;
use Uwil\LaravelBackend\Requests\Users\UpdateUserRequest;
return [
/**
*--------------------------------------------------------------------------
* Routes
*--------------------------------------------------------------------------
*
* This option may be used to edit routes informations.
* - prefix: string.
* - name: string.
*/
'routes' => [
'prefix' => 'admin',
'name' => 'back.',
],
/**
*--------------------------------------------------------------------------
* Redirects
*--------------------------------------------------------------------------
*
* This option may be used to edit redirects.
* - redirect_logout: string.
*/
'redirect_logout' => 'front.dynamic-pages.accueil.fr',
/**
*--------------------------------------------------------------------------
* Saml
*--------------------------------------------------------------------------
*
* This option may be used to active or not the saml connection.
* - enabled: boolean.
*/
'saml' => [
'enabled' => true,
],
/**
*--------------------------------------------------------------------------
* User
*--------------------------------------------------------------------------
*
* This options may be used when overriding the User model.
* - model: class.
* - store: class.
* - update: class.
*/
'user' => [
'model' => User::class,
'requests' => [
'store' => StoreUserRequest::class,
'update' => UpdateUserRequest::class,
],
],
];

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
return [
/**
*--------------------------------------------------------------------------
* Path of the default view.
*--------------------------------------------------------------------------
*
* This option may be used to edit routes informations.
* - default-view: string.
*/
'default-view' => 'front/Pages/DynamicPageDefault',
];

View file

@ -9,6 +9,8 @@ use Illuminate\Database\Seeder;
class ProductSeeder extends Seeder
{
public static string $table = 'products';
public function run(): void
{
Product::factory()->count(50)->create();

View file

@ -10,6 +10,8 @@ use Illuminate\Database\Seeder;
class RecipeSeeder extends Seeder
{
public static string $table = 'recipes';
/**
* Run the database seeds.
*/

View file

@ -5,30 +5,14 @@ declare(strict_types=1);
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Psr\Log\LoggerInterface;
class DatabaseSeeder extends Seeder
{
public function __construct(
private readonly LoggerInterface $logger
) {
}
/**
* Seed the application's database.
*/
public function run(): void
{
$this->callOnce(MandatorySeeder::class);
$this->logger->info('Fixing dynamic page home slug');
DB::table('dynamic_pages')
->where('id_key', 'accueil')
->update([
'slug' => json_encode((object) [
'fr' => '/',
]),
]);
}
}

View file

@ -16,6 +16,8 @@ use Illuminate\Support\Str;
class ImportProductsCsvSeeder extends Seeder
{
public static string $table = 'products';
public function run(): void
{
$filePathName = database_path('seeders/data/products.csv');

View file

@ -15,6 +15,8 @@ use Illuminate\Support\Str;
class ImportRecipesCsvSeeder extends Seeder
{
public static string $table = 'recipes';
public function run(): void
{
$filePathName = database_path('seeders/data/recipes.csv');

View file

@ -185,6 +185,7 @@
"Reset Content": "Reset Content",
"Reset Password": "Reset Password",
"Reset Password Notification": "Reset Password Notification",
"Reset your password": "Reset your password",
"Restore": "Restore",
"Restore :name": "Restore :name",
"results": "results",
@ -222,6 +223,8 @@
"Tags": "Tags",
"Temporary Redirect": "Temporary Redirect",
"Thanks for signing up! Before getting started, could you verify your email address by clicking on the link we just emailed to you? If you didn't receive the email, we will gladly send you another.": "Thanks for signing up! Before getting started, could you verify your email address by clicking on the link we just emailed to you? If you didn't receive the email, we will gladly send you another.",
"The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.",
"The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.",
"The given data was invalid.": "The given data was invalid.",
"The response is not a streamed response.": "The response is not a streamed response.",
"The response is not a view.": "The response is not a view.",
@ -234,6 +237,7 @@
"Too Many Requests": "Too Many Requests",
"Translate": "Translate",
"Translate It": "Translate It",
"Unable to write the encrypted environment file.": "Unable to write the encrypted environment file.",
"Unauthorized": "Unauthorized",
"Unavailable For Legal Reasons": "Unavailable For Legal Reasons",
"Unknown Error": "Unknown Error",
@ -252,6 +256,7 @@
"User": "User",
"Variant Also Negotiates": "Variant Also Negotiates",
"Verify Email Address": "Verify Email Address",
"Verify your email address": "Verify your email address",
"View": "View",
"View :name": "View :name",
"Web Server is Down": "Web Server is Down",

View file

@ -13,7 +13,9 @@ return [
'alpha_num' => 'The :attribute field must only contain letters and numbers.',
'any_of' => 'The :attribute field is invalid.',
'array' => 'The :attribute field must be an array.',
'array_keys' => 'The :attribute field must only contain the following keys: :values.',
'ascii' => 'The :attribute field must only contain single-byte alphanumeric characters and symbols.',
'base64' => 'The :attribute field must be a valid Base64 string.',
'before' => 'The :attribute field must be a date before :date.',
'before_or_equal' => 'The :attribute field must be a date before or equal to :date.',
'between' => [

View file

@ -185,6 +185,7 @@
"Reset Content": "Réinitialiser le contenu",
"Reset Password": "Réinitialisation du mot de passe",
"Reset Password Notification": "Notification de réinitialisation du mot de passe",
"Reset your password": "Réinitialiser votre mot de passe",
"Restore": "Restaurer",
"Restore :name": "Restaurer :name",
"results": "résultats",
@ -222,6 +223,8 @@
"Tags": "Mots clés",
"Temporary Redirect": "Redirection temporaire",
"Thanks for signing up! Before getting started, could you verify your email address by clicking on the link we just emailed to you? If you didn't receive the email, we will gladly send you another.": "Merci de vous être inscrit(e) ! Avant de commencer, veuillez vérifier votre adresse e-mail en cliquant sur le lien que nous venons de vous envoyer. Si vous n'avez pas reçu cet e-mail, nous vous en enverrons un nouveau avec plaisir.",
"The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.",
"The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.",
"The given data was invalid.": "La donnée renseignée est incorrecte.",
"The response is not a streamed response.": "La réponse n'est pas une réponse diffusée.",
"The response is not a view.": "La réponse n'est pas une vue.",
@ -234,6 +237,7 @@
"Too Many Requests": "Trop de requêtes",
"Translate": "Traduire",
"Translate It": "Traduis le",
"Unable to write the encrypted environment file.": "Unable to write the encrypted environment file.",
"Unauthorized": "Non autorisé",
"Unavailable For Legal Reasons": "Indisponible pour des raisons légales",
"Unknown Error": "Erreur inconnue",
@ -252,6 +256,7 @@
"User": "Utilisateur",
"Variant Also Negotiates": "La variante négocie également",
"Verify Email Address": "Vérifier l'adresse e-mail",
"Verify your email address": "Vérifier votre adresse e-mail",
"View": "Vue",
"View :name": "Voir :name",
"Web Server is Down": "Le serveur Web est en panne",

View file

@ -13,7 +13,9 @@ return [
'alpha_num' => 'Le champ :attribute doit contenir uniquement des chiffres et des lettres.',
'any_of' => 'Le champ :attribute est invalide.',
'array' => 'Le champ :attribute doit être un tableau.',
'array_keys' => 'Le champ :attribute ne doit contenir que les clés suivantes : :values.',
'ascii' => 'Le champ :attribute ne doit contenir que des caractères alphanumériques et des symboles codés sur un octet.',
'base64' => 'Le champ :attribute doit être une chaîne Base64 valide.',
'before' => 'Le champ :attribute doit être une date antérieure au :date.',
'before_or_equal' => 'Le champ :attribute doit être une date antérieure ou égale au :date.',
'between' => [
@ -196,8 +198,8 @@ return [
'day' => 'jour',
'deleted_at' => 'date de suppression',
'description' => 'description',
'details_and_advantages' => 'détails et avantages',
'details' => 'détails',
'details_and_advantages' => 'détails et avantages',
'display_type' => 'type d\'affichage',
'district' => 'quartier',
'duration' => 'durée',

2648
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -17,48 +17,48 @@
},
"devDependencies": {
"@headlessui/react": "^2.2.10",
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-checkbox": "^1.3.5",
"@radix-ui/react-collapsible": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.18",
"@radix-ui/react-label": "^2.1.10",
"@radix-ui/react-popover": "^1.1.17",
"@radix-ui/react-progress": "^1.1.10",
"@radix-ui/react-scroll-area": "^1.2.12",
"@radix-ui/react-select": "^2.3.1",
"@radix-ui/react-separator": "^1.1.10",
"@radix-ui/react-slider": "^1.4.1",
"@radix-ui/react-slot": "^1.3.0",
"@radix-ui/react-switch": "^1.3.1",
"@radix-ui/react-toast": "^1.2.17",
"@radix-ui/react-tooltip": "^1.2.10",
"@radix-ui/react-accordion": "^1.3.1",
"@radix-ui/react-checkbox": "^1.4.1",
"@radix-ui/react-collapsible": "^1.2.1",
"@radix-ui/react-dropdown-menu": "^2.2.1",
"@radix-ui/react-label": "^2.1.17",
"@radix-ui/react-popover": "^1.3.1",
"@radix-ui/react-progress": "^1.2.1",
"@radix-ui/react-scroll-area": "^1.4.0",
"@radix-ui/react-select": "^2.4.1",
"@radix-ui/react-separator": "^1.2.0",
"@radix-ui/react-slider": "^1.6.1",
"@radix-ui/react-slot": "^1.5.0",
"@radix-ui/react-switch": "^1.4.1",
"@radix-ui/react-toast": "^1.3.1",
"@radix-ui/react-tooltip": "^1.4.1",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.20",
"@types/react-color": "^3.0.13",
"@typescript-eslint/eslint-plugin": "^8.62.0",
"@typescript-eslint/parser": "^8.62.0",
"@uwil/husky-config": "^1.0.1",
"@typescript-eslint/eslint-plugin": "^8.71.2",
"@typescript-eslint/parser": "^8.71.2",
"@uwil/husky-config": "^1.1.1",
"@vitejs/plugin-basic-ssl": "^2.3.0",
"@vitejs/plugin-react": "^6.0.3",
"autoprefixer": "^10.5.2",
"concurrently": "^9.2.3",
"@vitejs/plugin-react": "^6.1.2",
"autoprefixer": "^10.6.1",
"concurrently": "^9.2.5",
"eslint": "^8.57.1",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prettier": "^5.5.6",
"eslint-plugin-prettier": "^5.5.7",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^4.6.2",
"flag-icons": "^7.5.0",
"flag-icons": "^7.6.0",
"pluralize": "^8.0.0",
"prettier": "^3.8.4",
"react": "^19.2.7",
"prettier": "^3.9.10",
"react": "^19.3.1",
"react-day-picker": "^9.14.0",
"react-dom": "^19.2.7",
"react-dom": "^19.3.1",
"rollup-plugin-copy": "^3.5.0",
"sass-embedded": "^1.100.0",
"sass-embedded": "^1.105.2",
"stylelint": "^16.26.1",
"stylelint-config-idiomatic-order": "^10.0.0",
"stylelint-config-sass-guidelines": "^12.1.0",
@ -66,8 +66,8 @@
"stylelint-scss": "^6.14.0",
"tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7",
"typescript-eslint": "^8.62.1",
"vite": "^8.1.0",
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4",
"vite-plugin-eslint": "^1.8.1",
"vite-plugin-stylelint": "^6.3.0"
},
@ -75,64 +75,64 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@inertiajs/core": "^2.3.27",
"@inertiajs/react": "^2.3.27",
"@inertiajs/core": "^3.9.1",
"@inertiajs/react": "^3.9.1",
"@ldc-web/cookie-notice": "^6.1.1",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dialog": "^1.3.1",
"@tanstack/react-table": "^8.21.3",
"@tiptap/core": "^3.27.1",
"@tiptap/extension-blockquote": "^3.27.1",
"@tiptap/extension-bold": "^3.27.1",
"@tiptap/extension-bullet-list": "^3.27.1",
"@tiptap/extension-color": "^3.27.1",
"@tiptap/extension-heading": "^3.27.1",
"@tiptap/extension-history": "^3.27.1",
"@tiptap/extension-horizontal-rule": "^3.27.1",
"@tiptap/extension-image": "^3.27.1",
"@tiptap/extension-invisible-characters": "^3.27.1",
"@tiptap/extension-italic": "^3.27.1",
"@tiptap/extension-link": "^3.27.1",
"@tiptap/extension-list": "^3.27.1",
"@tiptap/extension-ordered-list": "^3.27.1",
"@tiptap/extension-placeholder": "^3.27.1",
"@tiptap/extension-strike": "^3.27.1",
"@tiptap/extension-subscript": "^3.27.1",
"@tiptap/extension-superscript": "^3.27.1",
"@tiptap/extension-table": "^3.27.1",
"@tiptap/extension-table-cell": "^3.27.1",
"@tiptap/extension-table-header": "^3.27.1",
"@tiptap/extension-table-row": "^3.27.1",
"@tiptap/extension-text-align": "^3.27.1",
"@tiptap/extension-underline": "^3.27.1",
"@tiptap/react": "^3.27.1",
"@tiptap/starter-kit": "^3.27.1",
"@tiptap/core": "^3.32.0",
"@tiptap/extension-blockquote": "^3.32.0",
"@tiptap/extension-bold": "^3.32.0",
"@tiptap/extension-bullet-list": "^3.32.0",
"@tiptap/extension-color": "^3.32.0",
"@tiptap/extension-heading": "^3.32.0",
"@tiptap/extension-history": "^3.32.0",
"@tiptap/extension-horizontal-rule": "^3.32.0",
"@tiptap/extension-image": "^3.32.0",
"@tiptap/extension-invisible-characters": "^3.32.0",
"@tiptap/extension-italic": "^3.32.0",
"@tiptap/extension-link": "^3.32.0",
"@tiptap/extension-list": "^3.32.0",
"@tiptap/extension-ordered-list": "^3.32.0",
"@tiptap/extension-placeholder": "^3.32.0",
"@tiptap/extension-strike": "^3.32.0",
"@tiptap/extension-subscript": "^3.32.0",
"@tiptap/extension-superscript": "^3.32.0",
"@tiptap/extension-table": "^3.32.0",
"@tiptap/extension-table-cell": "^3.32.0",
"@tiptap/extension-table-header": "^3.32.0",
"@tiptap/extension-table-row": "^3.32.0",
"@tiptap/extension-text-align": "^3.32.0",
"@tiptap/extension-underline": "^3.32.0",
"@tiptap/react": "^3.32.0",
"@tiptap/starter-kit": "^3.32.0",
"@types/pluralize": "^0.0.33",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"awilix": "^13.0.5",
"axios": "^1.18.1",
"axios": "^1.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
"dompurify": "^3.4.11",
"dompurify": "^3.4.17",
"json-edit-react": "^1.30.2",
"laravel-precognition-react": "^2.0.0",
"laravel-vite-plugin": "^3.1.0",
"laravel-precognition-react": "^2.1.1",
"laravel-vite-plugin": "^3.2.0",
"lucide-react": "^0.503.0",
"motion": "^12.42.0",
"motion": "^12.43.0",
"prosemirror-state": "^1.4.4",
"radix-ui": "^1.6.0",
"radix-ui": "^1.8.1",
"react-color": "^2.19.3",
"react-dropzone": "^14.4.1",
"react-image-crop": "^11.1.2",
"slugify": "^1.6.9",
"swiper": "^12.2.0",
"tailwind-merge": "^3.6.0",
"tailwind-merge": "^3.7.0",
"typescript": "^6.0.3",
"vaul": "^1.1.2",
"ziggy-js": "^2.6.3",
"zod": "^4.4.3",
"zustand": "^5.0.14"
"ziggy-js": "^2.6.5",
"zod": "^4.6.7",
"zustand": "^5.0.15"
}
}

BIN
public/favicon-96x96.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

3
public/favicon.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View file

@ -1,22 +1,39 @@
import { axiosAdapter } from "@inertiajs/core";
import { createInertiaApp } from "@inertiajs/react";
import CookieNotice from "@ldc-web/cookie-notice";
import axios from "axios";
import { resolvePageComponent } from "laravel-vite-plugin/inertia-helpers";
import type { ComponentType } from "react";
import { createRoot } from "react-dom/client";
import recaptcha from "./hooks/use-recaptcha";
// ASSETS
import.meta.glob("../../assets/images/**/*");
const appName = import.meta.env.VITE_APP_NAME || "Laravel";
type PageComponent = ComponentType<Record<string, unknown>>;
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) =>
resolvePageComponent(
interface PageModule {
default: PageComponent;
}
const appName = import.meta.env.VITE_APP_NAME || "Laravel";
const appPages = import.meta.glob<PageModule>("./*/Pages/**/*.tsx");
const nonce =
document.querySelector<HTMLMetaElement>('meta[name="csp-nonce"]')?.content ??
"";
void createInertiaApp({
nonce,
http: axiosAdapter(window.axios),
title: (title) => (title ? `${title} - ${appName}` : appName),
resolve: async (name) => {
const page = await resolvePageComponent<PageModule>(
`./${name}.tsx`,
import.meta.glob("./*/Pages/**/*.tsx"),
),
appPages,
);
return page.default;
},
setup({ el, App, props }) {
const root = createRoot(el);

View file

@ -1,16 +1,15 @@
// * Packages
import { Link } from "@inertiajs/react";
import { route } from "ziggy-js";
// * Other
import { useTheme } from "@/back/providers/ThemeProvider";
import logoUwilCMSLight from "&/images/logos/uwil-cms-light.svg";
import { Link, usePage } from "@inertiajs/react";
import logoUwilCMSDark from "&/images/logos/uwil-cms-dark.svg";
import logoTinyUwilCMS from "&/images/logos/uwil-cms-light-icon.svg";
import logoUwilCMSLight from "&/images/logos/uwil-cms-light.svg";
import { useTheme } from "@/back/providers/ThemeProvider";
import type { ConfigBackend } from "@/back/types/global";
type ApplicationLogoProps = {
interface ApplicationLogoProps {
forceLight?: boolean;
isCollapsed?: boolean;
};
}
/**
* Get the logo.
@ -30,19 +29,20 @@ export default function ApplicationLogo({
forceLight = false,
isCollapsed = false,
}: ApplicationLogoProps) {
const { routes } = usePage().props.configBackend as ConfigBackend;
const { theme } = useTheme();
const wrapperClasses = isCollapsed ? "h-8" : "w-full max-w-[10rem] mx-auto";
const logo = getLogo(isCollapsed, forceLight, theme);
return (
<Link
href={route("back.dashboard.index")}
className={`${wrapperClasses} rounded-md ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`}
href={route(`${routes.name}dashboard.index`)}
className={`${wrapperClasses} rounded-md ring-offset-background focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`}
>
<img
src={logo}
alt="UWIL CMS logo"
className={`rounded-md w-auto mx-auto ${isCollapsed ? "h-full" : "max-h-full"}`}
className={`w-auto mx-auto ${isCollapsed ? "h-full" : "max-h-full"}`}
/>
</Link>
);

View file

@ -1,14 +1,13 @@
// * Packages
import { Link } from "@inertiajs/react";
import { VariantProps } from "class-variance-authority";
import { type VariantProps } from "class-variance-authority";
import {
ButtonHTMLAttributes,
CSSProperties,
MouseEventHandler,
ReactNode,
type ButtonHTMLAttributes,
type CSSProperties,
type MouseEventHandler,
type ReactNode,
} from "react";
// * Components shadcn
import { Button, buttonVariants } from "@/components/ui/button";
import { Button, type buttonVariants } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
@ -19,7 +18,7 @@ type ButtonVariant = VariantProps<typeof buttonVariants>["variant"];
type ButtonSize = VariantProps<typeof buttonVariants>["size"];
type ButtonType = ButtonHTMLAttributes<HTMLButtonElement>["type"];
type BtnOptionnalLinkWithTooltipProps = {
interface BtnOptionnalLinkWithTooltipProps {
link?: string | null;
content: ReactNode;
tooltipContent: ReactNode;
@ -31,7 +30,7 @@ type BtnOptionnalLinkWithTooltipProps = {
disabled?: boolean;
style?: CSSProperties;
onClick?: MouseEventHandler<HTMLButtonElement>;
};
}
export default function BtnOptionnalLinkWithTooltip({
link = null,
@ -54,7 +53,7 @@ export default function BtnOptionnalLinkWithTooltip({
innerContent = disabled ? (
<Button disabled>{content}</Button>
) : (
<a href={link} target="_blank" rel="noopener noreferrer">
<a href={link} target="_blank" rel="noreferrer">
{content}
</a>
);
@ -75,7 +74,6 @@ export default function BtnOptionnalLinkWithTooltip({
disabled={disabled}
onClick={onClick}
style={style}
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
>
{innerContent}

View file

@ -1,6 +1,6 @@
// * Packages
import { PanelRightOpenIcon, PanelRightCloseIcon } from "lucide-react";
// * Components shadcn
import { useEffect } from "react";
import { Button } from "@/components/ui/button";
import { useSidebar } from "@/components/ui/sidebar";
import {
@ -8,17 +8,21 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
// * Other
import useDeviceType from "@/hooks/use-device-type";
import useTrans from "@/hooks/use-translations";
export default function CustomSidebarTrigger() {
const { toggleSidebar, state } = useSidebar();
const { isMobile } = useDeviceType();
useEffect(() => {
if (state === "collapsed") {
localStorage.setItem("vite-ui-collapsed", "true");
} else {
localStorage.removeItem("vite-ui-collapsed");
}
}, [state]);
if (state === "collapsed") {
localStorage.setItem("vite-ui-collapsed", "true");
} else {
localStorage.removeItem("vite-ui-collapsed");
}
return (
<Tooltip>
<TooltipTrigger asChild>
@ -28,7 +32,7 @@ export default function CustomSidebarTrigger() {
className="rotate-180"
size="icon"
>
{state === "collapsed" ? (
{isMobile || state === "collapsed" ? (
<PanelRightOpenIcon />
) : (
<PanelRightCloseIcon />

View file

@ -1,10 +1,8 @@
// * Packages
import { ReactNode } from "react";
// * Other
import { ConfigField } from "@/back/types/dynamic-pages";
import { type ReactNode } from "react";
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
export type DynamicInputProps = {
import type { ConfigField } from "@/back/types/dynamic-pages";
export interface DynamicInputProps {
fieldName: string;
fieldValue: string | number | boolean | File | Date;
field: ConfigField;
@ -13,44 +11,43 @@ export type DynamicInputProps = {
value: string | number | boolean | File | object | null,
) => void;
errors: Record<string, string> | null | undefined;
};
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
}
// eslint-disable-next-line no-unused-vars
export type InputResolver = (props: DynamicInputProps) => ReactNode;
export default class DynamicInputRegistry {
private static resolvers: Map<string, InputResolver> = new Map();
const resolvers = new Map<string, InputResolver>();
static add(name: string, resolver: InputResolver) {
this.resolvers.set(name, resolver);
}
static get(
export const DynamicInputRegistry = {
add(name: string, resolver: InputResolver) {
resolvers.set(name, resolver);
},
get(
targetName: string,
fieldName: string,
fieldValue: string | number | boolean | File | Date,
field: ConfigField,
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
setData: (
name: string,
value: string | number | boolean | File | object | null,
) => void,
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
errors?: Record<string, string> | null | undefined,
errors?: Record<string, string> | null,
): ReactNode | null {
const resolver = this.resolvers.get(targetName.toLowerCase());
const resolver = resolvers.get(targetName.toLowerCase());
return resolver
? resolver({ fieldName, fieldValue, field, setData, errors })
: null;
}
}
},
};
// Add all custom inputs presents in files to the registry.
// @ts-expect-error Glob error.
const modules = import.meta.glob("./CustomInputs/*.tsx", {
eager: true,
}) as Record<string, { default: InputResolver }>;
const modules = import.meta.glob<{ default: InputResolver }>(
"./CustomInputs/*.tsx",
{
eager: true,
},
);
Object.entries(modules).forEach(([path, module]) => {
const name = path

View file

@ -1,36 +1,34 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { Fragment } from "react/jsx-runtime";
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleNumber from "@/back/Components/Inputs/SimpleNumber";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import SimpleWysiwyg from "@/back/Components/Inputs/Wysiwyg/SimpleWysiwyg";
import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile";
import { DynamicInputRegistry } from "@/back/Components/DynamicPages/DynamicInputRegistry";
import DynamicList from "@/back/Components/DynamicPages/DynamicList";
import SimpleTextarea from "@/back/Components/Inputs/SimpleTextarea";
import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker";
import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker";
import SimpleYoutubeId from "@/back/Components/Inputs/SimpleYoutubeId";
import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId";
import StaticRouteSelect from "@/back/Components/Inputs/StaticRouteSelect";
import DynamicWrapperModelSelect from "@/back/Components/DynamicPages/DynamicWrapperModelSelect";
import DynamicInputRegistry from "@/back/Components/DynamicPages/DynamicInputRegistry";
import {
import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile";
import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker";
import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker";
import SimpleNumber from "@/back/Components/Inputs/SimpleNumber";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import SimpleTextarea from "@/back/Components/Inputs/SimpleTextarea";
import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId";
import SimpleYoutubeId from "@/back/Components/Inputs/SimpleYoutubeId";
import StaticRouteSelect from "@/back/Components/Inputs/StaticRouteSelect";
import SimpleWysiwyg from "@/back/Components/Inputs/Wysiwyg/SimpleWysiwyg";
import type {
ConfigField,
DynamicFieldType,
DynamicInternalField,
} from "@/back/types/dynamic-pages";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import {
extractLaravelValidationValue,
extractMinMaxFromValidation,
extractRequiredValidation,
} from "@/hooks/use-laravel-validation";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
/* eslint-disable no-unused-vars */
type DynamicInputsProps = {
interface DynamicInputsProps {
name: string;
config: ConfigField[];
content: DynamicInternalField | null;
@ -41,14 +39,13 @@ type DynamicInputsProps = {
) => void;
reset: (name?: string) => void;
parentErrors?: Record<string, string> | null;
};
/* eslint-enable no-unused-vars */
}
// Allows to get specific input from enum value.
export default function DynamicInputs({
name,
config,
content = null,
content,
isChildren = false,
setData,
reset,
@ -71,13 +68,23 @@ export default function DynamicInputs({
* @returns string
*/
const getTrans = (fieldLabel: string): string => {
return str(
`${transAssociateTo.split("|")[0].replace(":attribute", fieldLabel)}`,
)
return str(transAssociateTo.split("|")[0].replace(":attribute", fieldLabel))
.ucFirst()
.value();
};
const toStr = (val: unknown): string => {
if (val === null || val === undefined) return "";
if (
typeof val === "string" ||
typeof val === "number" ||
typeof val === "boolean"
) {
return String(val);
}
return "";
};
return (
<div className="grid grid-cols-1 md:grid-cols-2 items-start gap-4">
{/* Loop on all config elements. */}
@ -102,7 +109,7 @@ export default function DynamicInputs({
name={fieldName}
label={getTrans(field.label)}
required={extractRequiredValidation(field.validation)}
value={String(fieldValue)}
value={toStr(fieldValue)}
setData={setData}
parentErrors={parentErrors}
/>
@ -115,7 +122,7 @@ export default function DynamicInputs({
name={fieldName}
label={getTrans(field.label)}
required={extractRequiredValidation(field.validation)}
value={String(fieldValue)}
value={toStr(fieldValue)}
setData={setData}
parentErrors={parentErrors}
/>
@ -129,7 +136,7 @@ export default function DynamicInputs({
tableName="dynamic_pages"
required={extractRequiredValidation(field.validation)}
label={getTrans(field.label)}
value={String(fieldValue)}
value={toStr(fieldValue)}
setData={setData}
parentErrors={parentErrors}
/>
@ -170,7 +177,7 @@ export default function DynamicInputs({
type="url"
placeholder="ex: https://..."
required={extractRequiredValidation(field.validation)}
value={String(fieldValue)}
value={toStr(fieldValue)}
setData={setData}
/>
);
@ -218,7 +225,7 @@ export default function DynamicInputs({
type="email"
placeholder="ex: john.doe@ldc.fr"
required={extractRequiredValidation(field.validation)}
value={String(fieldValue)}
value={toStr(fieldValue)}
setData={setData}
/>
);
@ -264,9 +271,10 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.vimeoid.value:
return (
<SimpleVimeoId
key={id}
name={fieldName}
setData={setData}
value={String(fieldValue)}
value={toStr(fieldValue)}
required={extractRequiredValidation(field.validation)}
/>
);
@ -274,9 +282,10 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.youtubeid.value:
return (
<SimpleYoutubeId
key={id}
name={fieldName}
setData={setData}
value={String(fieldValue)}
value={toStr(fieldValue)}
required={extractRequiredValidation(field.validation)}
/>
);
@ -284,6 +293,7 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.date.value:
return (
<SimpleDatePicker
key={id}
name={fieldName}
setData={setData}
date={fieldValue as Date}
@ -295,9 +305,10 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.color.value:
return (
<SimpleColorPicker
key={id}
name={fieldName}
setData={setData}
value={String(fieldValue)}
value={toStr(fieldValue)}
label={getTrans(field.label)}
required={extractRequiredValidation(field.validation)}
/>
@ -306,6 +317,7 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.model.value:
return (
<DynamicWrapperModelSelect
key={id}
field={field}
fieldName={fieldName}
fieldValue={fieldValue}
@ -317,6 +329,7 @@ export default function DynamicInputs({
case enumDynamicFieldTypes.staticroute.value:
return (
<StaticRouteSelect
key={id}
name={fieldName}
label={getTrans(field.label)}
selected={fieldValue as number}

View file

@ -1,9 +1,7 @@
// * Packages
import { CSS } from "@dnd-kit/utilities";
import {
closestCenter,
DndContext,
DragEndEvent,
type DragEndEvent,
PointerSensor,
useSensor,
useSensors,
@ -14,10 +12,18 @@ import {
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { usePage } from "@inertiajs/react";
import { useState } from "react";
import { GripVerticalIcon, TrashIcon } from "lucide-react";
// * Components shadcn
import { useState } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import DynamicInputs from "@/back/Components/DynamicPages/DynamicInputs";
import AddNewFieldBtn from "@/back/Components/PageConfigs/AddNewFieldBtn";
import type {
ConfigField,
DynamicInternalField,
} from "@/back/types/dynamic-pages";
import {
Accordion,
AccordionContent,
@ -26,20 +32,14 @@ import {
} from "@/components/ui/accordion";
import { Card, CardContent } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
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/dynamic-pages";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
/* eslint-disable no-unused-vars */
type SortableItemProps = {
interface SortableItemProps {
id: number;
item: DynamicInternalField | null;
itemIndex: number;
@ -48,15 +48,14 @@ type SortableItemProps = {
field: ConfigField;
setData: (
name: string,
value: string | boolean | File | object | null,
value: string | number | 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<string, string>;
};
/* eslint-enable no-unused-vars */
}
// Recursive component.
function SortableItem({
@ -99,16 +98,19 @@ function SortableItem({
// Translations.
const transDragAndDrop = useTrans("uwil-dynamic-pages::trans.dnd_field");
const transDelete = useTrans("uwil-dynamic-pages::trans.delete_field");
const transElement = useTrans("uwil-dynamic-pages::trans.element_field", {
params: { number: String(itemIndex + 1) },
});
return (
<div ref={setNodeRef} style={style} className="relative mb-3">
<AccordionItem value={`item-${itemIndex}`}>
<AccordionItem value={`item-${String(itemIndex)}`}>
<Card
className={cn({
"border-destructive/50 dark:border-destructive":
parentAccordionState !== `item-${itemIndex}` &&
parentAccordionState !== `item-${String(itemIndex)}` &&
Object.keys(localErrors).some((key) =>
key.startsWith(`${name}.${itemIndex}`),
key.startsWith(`${name}.${String(itemIndex)}`),
),
})}
>
@ -125,10 +127,8 @@ function SortableItem({
variant="outline"
size="icon"
disabled={parentAccordionState !== ""}
/* eslint-disable react/jsx-props-no-spreading */
{...listeners}
{...attributes}
/* eslint-enable react/jsx-props-no-spreading */
/>
</div>
{/* Define a delete button to destroy the current element. */}
@ -139,7 +139,7 @@ function SortableItem({
variant="destructive"
size="icon"
onClick={() => {
if (parentAccordionState === `item-${itemIndex}`) {
if (parentAccordionState === `item-${String(itemIndex)}`) {
setParentAccordionState("");
}
removeField(parentName, field.key, itemIndex);
@ -148,8 +148,8 @@ function SortableItem({
</div>
{/* Define the trigger button to open or close the current accordion. */}
<div className="w-full lg:w-2/3 xl:w-1/2">
<AccordionTrigger className="inline-flex items-center justify-between gap-2 whitespace-nowrap rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-secondary/80 h-10 px-4 py-2 w-full">
Élément n°{itemIndex + 1}
<AccordionTrigger className="inline-flex items-center justify-between gap-2 whitespace-nowrap rounded-md text-sm cursor-pointer font-medium bg-secondary text-secondary-foreground hover:bg-secondary/80 h-10 px-4 py-2 w-full">
{transElement}
</AccordionTrigger>
</div>
</div>
@ -157,7 +157,7 @@ function SortableItem({
{/* Get specific input from the config value. */}
{field.children?.length && (
<DynamicInputs
name={`${name}.${itemIndex}`}
name={`${name}.${String(itemIndex)}`}
config={field.children}
content={item}
setData={setData}
@ -174,8 +174,7 @@ function SortableItem({
);
}
/* eslint-disable no-unused-vars */
type DynamicListProps = {
interface DynamicListProps {
name: string;
parentName: string;
value: DynamicInternalField[];
@ -185,11 +184,10 @@ type DynamicListProps = {
isChildren: boolean;
setData: (
name: string,
value: string | boolean | File | object | null,
value: string | number | boolean | object | File | null,
) => void;
reset: (name?: string) => void;
};
/* eslint-enable no-unused-vars */
}
// Allows to get recursive list inputs.
export default function DynamicList({
@ -227,10 +225,10 @@ export default function DynamicList({
const [openIndex, setOpenIndex] = useState<string>("");
// Notice user there must be children config.
if (!field.children && field.children!.length > 0) {
if (!field.children || field.children.length <= 0) {
return (
<p className="text-muted-foreground text-sm">
{GetTranslation("uwil-backend::back.list_children_needed", {
{GetTranslation("uwil-dynamic-pages::trans.children_needed", {
params: { enumLabel },
})}
</p>
@ -249,10 +247,10 @@ export default function DynamicList({
fieldKey: string,
index: number,
) => {
const raw = content?.[fieldKey as keyof typeof content];
// 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]]
const list: DynamicInternalField[] = Array.isArray(raw)
? (raw as DynamicInternalField[]).map((item) => ({ ...item }))
: [];
// Remove the targeted element.
list.splice(index, 1);
@ -301,18 +299,16 @@ export default function DynamicList({
const maxOrder =
Math.max(
0,
...sortedListItems.map((currentField) => currentField.order ?? 0),
...sortedListItems.map((currentField) => currentField.order),
) + 1;
const maxIndex =
Math.max(
0,
...sortedListItems.map((currentField) => currentField.id ?? 0),
) + 1;
Math.max(0, ...sortedListItems.map((currentField) => currentField.id)) +
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);
setData(`${parentName}.${field.key}.${String(newIndex)}`, newItemWithOrder);
};
return (
@ -357,9 +353,9 @@ export default function DynamicList({
field={field}
setData={setData}
reset={reset}
removeField={(currentParentName, fieldKey, index) =>
handleRemoveField(currentParentName, fieldKey, index)
}
removeField={(currentParentName, fieldKey, index) => {
handleRemoveField(currentParentName, fieldKey, index);
}}
parentAccordionState={openIndex}
setParentAccordionState={setOpenIndex}
localErrors={localErrors}

View file

@ -1,25 +1,25 @@
// * Packages
import { ReactNode } from "react";
// * Components shadcn
import { type ReactNode } from "react";
import type { ConfigField } from "@/back/types/dynamic-pages";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
// * Other
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { ConfigField } from "@/back/types/dynamic-pages";
import { cn, GetTranslation } from "@/lib/utils";
type ChildItem = Record<string, string | number | object | ChildItem[]>;
type ChildItem = Record<string, unknown> & { id: string | number };
type FieldValue = string | number | boolean | null | undefined | ChildItem[];
const RenderRows = (
currentValue: string | number | object,
currentValue: Record<string, unknown>,
currentConfig: ConfigField[],
hasBorders: boolean = false,
path: string = "",
hasBorders = false,
path = "",
): ReactNode => {
const tableNotKnownTrans = str(useTrans("uwil-backend::back.table_not_known"))
.ucFirst()
@ -28,20 +28,18 @@ const RenderRows = (
return currentConfig.map((field, index) => {
const hasChildren = !!field.children?.length;
const accordionKey = path
? `${path}.${field.key}-${index}`
: `${field.key}-${index}`;
? `${path}.${field.key}-${String(index)}`
: `${field.key}-${String(index)}`;
const rowContent = (currentHasChildren: boolean = false) => {
const rowContent = (currentHasChildren = 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];
const fieldValue = currentValue[field.key] as FieldValue;
let cellContent: ReactNode;
if (currentHasChildren) {
const count = Array.isArray(fieldValue)
? Object.values(fieldValue).length
: 0;
const count = Array.isArray(fieldValue) ? fieldValue.length : 0;
cellContent = (
<p className={placeholderClasses}>
{GetTranslation("uwil-dynamic-pages::trans.element", {
@ -51,16 +49,18 @@ const RenderRows = (
</p>
);
} else if (fieldValue !== null && fieldValue !== undefined) {
cellContent = (
<p className={cellClasses}>
{typeof fieldValue === "boolean"
? GetTranslation(
fieldValue
? "uwil-backend::back.yes"
: "uwil-backend::back.no",
)
: fieldValue}
</p>
const displayValue = Array.isArray(fieldValue)
? null
: typeof fieldValue === "boolean"
? GetTranslation(
fieldValue ? "uwil-backend::back.yes" : "uwil-backend::back.no",
)
: String(fieldValue);
cellContent = displayValue ? (
<p className={cellClasses}>{displayValue}</p>
) : (
<p className={placeholderClasses}>{tableNotKnownTrans}</p>
);
} else {
cellContent = (
@ -77,6 +77,10 @@ const RenderRows = (
);
};
const childItems = currentValue[field.key];
const hasChildItems =
hasChildren && Array.isArray(childItems) && childItems.length > 0;
return (
<AccordionItem
key={accordionKey}
@ -97,38 +101,31 @@ const RenderRows = (
<div className="px-4 py-2">{rowContent()}</div>
)}
{hasChildren &&
Array.isArray(currentValue[field.key as keyof typeof currentValue]) &&
Object.values(currentValue[field.key as keyof typeof currentValue])
.length > 0 && (
<AccordionContent className="px-4">
<div className="space-y-1">
{Object.values(
currentValue[
field.key as keyof typeof currentValue
] as ChildItem[],
).map((childItem: ChildItem) => (
<div key={String(childItem.id)} className="border rounded-md">
{RenderRows(
childItem,
field.children!,
false,
`${accordionKey}-${childItem.id}`,
)}
</div>
))}
</div>
</AccordionContent>
)}
{hasChildItems && (
<AccordionContent className="px-4">
<div className="space-y-1">
{(childItems as ChildItem[]).map((childItem) => (
<div key={String(childItem.id)} className="border rounded-md">
{RenderRows(
childItem,
field.children ?? [],
false,
`${accordionKey}-${String(childItem.id)}`,
)}
</div>
))}
</div>
</AccordionContent>
)}
</AccordionItem>
);
});
};
type DynamicPageDetailsProps = {
value: string | object;
interface DynamicPageDetailsProps {
value: Record<string, unknown>;
config: ConfigField[];
};
}
export default function DynamicPageDetails({
value,
@ -143,14 +140,12 @@ export default function DynamicPageDetails({
return (
<Accordion type="multiple" className="w-full divide-y">
{/* HEADER */}
<div className="grid grid-cols-[1fr_1fr_auto] text-sm font-medium border-b gap-4 px-4 py-2">
<div>{transLabel}</div>
<div>{transValue}</div>
<div className="w-[16px]" />
</div>
{/* ROWS */}
{RenderRows(value, config, true)}
</Accordion>
);

View file

@ -1,20 +1,17 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { CheckIcon, PencilLineIcon, XIcon } from "lucide-react";
// * Components shadcn
import { Badge } from "@/components/ui/badge";
// * Other
import { LaravelEnumMap } from "@/types/global";
type DynamicStatusBadgeProps = {
import { Badge } from "@/components/ui/badge";
interface DynamicStatusBadgeProps {
value: number;
};
}
// Get a stylised badge for a specific enum value.
export default function DynamicStatusBadge({ value }: DynamicStatusBadgeProps) {
// Get all enum values, labels and names.
const { enumDynamicPageStatus } = usePage().props as unknown as {
enumDynamicPageStatus: LaravelEnumMap;
enumDynamicPageStatus: LaravelEnum;
};
// Set specific icon and style classes for each enum value.
@ -27,7 +24,7 @@ export default function DynamicStatusBadge({ value }: DynamicStatusBadgeProps) {
color: "bg-red-200 dark:bg-red-900",
Icon: XIcon,
},
[enumDynamicPageStatus.published?.value ?? "default"]: {
[enumDynamicPageStatus.published.value]: {
color: "bg-green-200 dark:bg-green-900",
Icon: CheckIcon,
},
@ -39,13 +36,14 @@ 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 style = enumValue ? statusStyles[enumValue.value] : null;
if (!style || !enumValue) return null;
const { color, Icon } = style;
return (
<Badge variant="outline" className={`border-0 ${color}`}>
<Icon size={15} className="mr-1" />
{enumValue?.label}
{enumValue.label}
</Badge>
);
}

View file

@ -1,16 +1,14 @@
// * Packages
import { useEffect, useRef } from "react";
// * Other
import { ModelSelect } from "@/back/Components/Inputs/ModelSelect";
import type { ConfigField } from "@/back/types/dynamic-pages";
import {
extractExcludedIdFromExists,
extractRequiredValidation,
extractTableFromExists,
} from "@/hooks/use-laravel-validation";
import { ConfigField } from "@/back/types/dynamic-pages";
/* eslint-disable no-unused-vars */
type DynamicWrapperModelSelectProps = {
interface DynamicWrapperModelSelectProps {
field: ConfigField;
fieldName: string;
fieldValue: string | number | boolean | File | Date;
@ -19,8 +17,7 @@ type DynamicWrapperModelSelectProps = {
value: string | number | boolean | File | object | null,
) => void;
getTrans: (fieldLabel: string) => string;
};
/* eslint-enable no-unused-vars */
}
export default function DynamicWrapperModelSelect({
field,
@ -31,7 +28,7 @@ export default function DynamicWrapperModelSelect({
}: DynamicWrapperModelSelectProps) {
// Extract only the model name from the validation.
const targetModel =
extractTableFromExists(field.validation) || "dynamic_pages";
extractTableFromExists(field.validation) ?? "dynamic_pages";
// Add a custom prefix in the last part of the name.
const newName = fieldName.replace(/([^.\s]+)$/, "reserved_$1");

View file

@ -1,6 +1,5 @@
// * Packages
import { ReactNode } from "react";
// * Components shadcn
import { type ReactNode } from "react";
import {
Card,
CardContent,
@ -8,7 +7,6 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
// * Other
import { cn } from "@/lib/utils";
export default function FieldsetWrapper({
@ -28,8 +26,8 @@ export default function FieldsetWrapper({
}) {
return (
<Card
className={cn("mb-4", {
"w-full sm:w-1/2 grid grid-cols-1 lg:grid-cols-2 items-center": inline,
className={cn("col-span-2", {
"sm:col-span-1 grid grid-cols-1 lg:grid-cols-2 items-center": inline,
})}
>
<CardHeader>

View file

@ -1,21 +1,23 @@
// * Packages
import { route } from "ziggy-js";
// * Other
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
import addFilterToUrl from "@/back/lib/filters";
import { LaravelEnumMap } from "@/types/global";
import AddFilterToUrl from "@/back/lib/filters";
type Props = {
enums: LaravelEnumMap;
interface Props {
enums: LaravelEnum;
fieldName: string;
modelName: string;
modelRoute: string;
prefixRoute: string;
label: string;
placeholder: string;
};
function EnumFilter(props: Props) {
const { enums, fieldName, modelName, label, placeholder } = props;
}
export default function EnumFilter({
enums,
fieldName,
modelRoute,
prefixRoute,
label,
placeholder,
}: Props) {
const selectedEnumParam = Object.values(enums).find(
(status) => status.name === route().params.status,
);
@ -35,10 +37,8 @@ function EnumFilter(props: Props) {
...route().params,
[name]: selectedStatusName,
};
addFilterToUrl({ modelName, params });
AddFilterToUrl({ modelRoute, prefixRoute, params });
}}
/>
);
}
export default EnumFilter;

View file

@ -1,21 +1,24 @@
// * Packages
import { route } from "ziggy-js";
// * Other
import { ModelSelect } from "@/back/Components/Inputs/ModelSelect";
import addFilterToUrl from "@/back/lib/filters";
import AddFilterToUrl from "@/back/lib/filters";
type Props = {
interface Props {
fieldName: string;
modelName: string;
modelRoute: string;
prefixRoute: string;
label: string;
placeholder: string;
/** Model target to display options */
targetModel?: string;
};
function MultiSelectRelationFilter(props: Props) {
const { targetModel, fieldName, label, placeholder, modelName } = props;
}
export default function MultiSelectRelationFilter({
targetModel,
fieldName,
label,
placeholder,
modelRoute,
prefixRoute,
}: Props) {
const valuesFromUrl: string[] =
typeof route().params[fieldName] === "string"
? route().params[fieldName].split(",")
@ -37,7 +40,7 @@ function MultiSelectRelationFilter(props: Props) {
...route().params,
[name]: valuesArray.length ? valuesArray.join(",") : undefined,
};
addFilterToUrl({ modelName, params });
AddFilterToUrl({ modelRoute, prefixRoute, params });
}}
defaultValue={valuesFromUrl}
responsive={{
@ -54,5 +57,3 @@ function MultiSelectRelationFilter(props: Props) {
/>
);
}
export default MultiSelectRelationFilter;

View file

@ -1,17 +1,19 @@
// * Packages
import { route } from "ziggy-js";
// * Other
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import addFilterToUrl from "@/back/lib/filters";
import AddFilterToUrl from "@/back/lib/filters";
type Props = {
fieldName: string;
modelName: string;
interface Props {
label: string;
};
fieldName: string;
modelRoute: string;
prefixRoute: string;
}
function SwitchFilter(props: Props) {
const { label, fieldName, modelName } = props;
export default function SwitchFilter({
label,
fieldName,
modelRoute,
prefixRoute,
}: Props) {
return (
<SimpleSwitch
name={fieldName}
@ -24,10 +26,8 @@ function SwitchFilter(props: Props) {
...route().params,
[name]: value,
};
addFilterToUrl({ modelName, params });
AddFilterToUrl({ modelRoute, prefixRoute, params });
}}
/>
);
}
export default SwitchFilter;

View file

@ -1,7 +1,7 @@
// * Packages
import { Filter } from "lucide-react";
import { ReactNode } from "react";
// * Components shadcn
import { type ReactNode } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import {
Sheet,
SheetContent,
@ -10,10 +10,8 @@ import {
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
function FiltersWrapper({ children }: { children: ReactNode }) {
return (

View file

@ -1,17 +1,14 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { ExternalLinkIcon } from "lucide-react";
// * Components shadcn
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
// * Other
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
import { AppEnv } from "@/types/global";
interface GoToFrontViewProps {
/** Model Name used to translate the helper */
@ -71,11 +68,11 @@ export default function GoToFrontView({
<a
href={definitivePath}
className={cn(
"flex justify-center items-center rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 underline-offset-4 hover:underline text-blue-600 hover:text-blue-600/80 visited:text-purple-600 w-fit gap-1.5",
"flex justify-center items-center rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 underline-offset-4 hover:underline text-blue-600 hover:text-blue-600/80 visited:text-purple-600 w-fit gap-1.5",
{ "ms-1": !isColumn },
)}
target="_blank"
rel="noopener noreferrer"
rel="noreferrer"
>
<p className="flex-1">{definitivePath}</p>
<ExternalLinkIcon size={12} />

View file

@ -1,22 +1,20 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { AlertCircleIcon } from "lucide-react";
// * Components shadcn
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
// * Other
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
export default function InputError({
all,
message,
}: Readonly<{
}: {
all?: boolean;
message?: string;
}>) {
}) {
const { errors } = usePage().props;
const errorsTrans = useTrans("uwil-backend::back.errors");
let messages = {} as Array<string>;
let messages = {} as string[];
if (message) {
messages = Object.values([message]);
} else if (Object.values(errors).length && all) {
@ -26,7 +24,7 @@ export default function InputError({
return (
<Alert
variant="destructive"
className={cn("text-left ", { "mb-4": all })}
className={cn("text-left col-span-2", { "mb-4": all })}
>
<AlertCircleIcon className="h-4 w-4" />
{all && <AlertTitle>{errorsTrans}</AlertTitle>}

View file

@ -1,27 +1,24 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { FileCheck, RefreshCwIcon, Trash, UploadIcon } from "lucide-react";
import { ReactNode, useCallback, useEffect, useState } from "react";
import { ErrorCode, FileWithPath, useDropzone } from "react-dropzone";
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { ErrorCode, type FileWithPath, useDropzone } from "react-dropzone";
import "react-image-crop/dist/ReactCrop.css";
// * Components shadcn
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import ImageCropper from "@/back/Components/Inputs/ImageCropper";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import str from "@/hooks/use-string";
import { useToast } from "@/hooks/use-toast";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
import { AppEnv } from "@/types/global";
type FileWithPreview = FileWithPath & {
preview: string;
};
type FileValidation = {
interface FileValidation {
validationRules?: {
width: string | null;
height: string | null;
@ -29,9 +26,8 @@ type FileValidation = {
maxFileSize: string | null;
allowedFormats: string | null;
inputType?: "image" | "file";
};
}
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
type CompleteInputFileProps = FileValidation & {
name: string;
value?: string | File | null;
@ -48,14 +44,13 @@ type CompleteInputFileProps = FileValidation & {
reset: (...fields: string[]) => void;
hasFile?: (hasFile: boolean) => void;
};
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
export default function CompleteInputFile(props: CompleteInputFileProps) {
const {
value,
setData,
originalData,
name = "defaultName",
name,
onRefreshFile,
label = "defaultLabel",
required = false,
@ -73,20 +68,16 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
const { errors } = usePage().props;
const { url } = usePage().props.appEnv as AppEnv;
const [isReset, setIsReset] = useState<boolean>(false);
const [isDialogOpen, setDialogOpen] = useState(false);
const [accept, setAccept] = useState<Record<string, Array<string>>>({
"image/*": [],
});
const [extensions, setExtensions] = useState<string>();
const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);
const finalFileName = `${fileName}.png`;
const isRefreshDisabled = value != null && typeof value === "string";
const localErrors = parentErrors ?? errors;
const localErrors = { ...errors, ...parentErrors };
const localValidationRules = {
width: validationRules?.width ? parseInt(validationRules.width, 10) : 250,
height: validationRules?.height
? parseInt(validationRules?.height, 10)
? parseInt(validationRules.height, 10)
: 250,
};
@ -140,7 +131,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
const i = Math.floor(Math.log(bytes) / Math.log(k));
const currentSize = sizes[i];
const currentBytes = parseFloat((bytes / k ** i).toFixed(2));
return `${currentBytes} ${currentSize}`;
return `${String(currentBytes)} ${currentSize}`;
};
// Translations
@ -162,7 +153,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
"uwil-backend::back.image_cropper.validation.rules_weight",
{
params: {
size: formatFileSize(localMaxFileSize).toString(),
size: formatFileSize(localMaxFileSize),
},
},
);
@ -184,11 +175,13 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
.value();
};
const buildDropzoneAccept = (): Record<string, string[]> => {
if (!allowedFormats) return {};
function buildDropzoneAccept(allowedFormats: string | null): {
accept: Record<string, string[]>;
extensions: string;
} {
if (!allowedFormats) return { accept: {}, extensions: "" };
const currentExtensions = allowedFormats.split(",");
setExtensions(allowedFormats);
const mimeMap: Record<string, string> = {
jpg: "image/jpeg",
jpeg: "image/jpeg",
@ -200,31 +193,28 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
};
const result: Record<string, Set<string>> = {};
currentExtensions.forEach((ext) => {
const cleanExt = ext.trim().toLowerCase();
const mime = mimeMap[cleanExt];
if (mime) {
if (!result[mime]) {
result[mime] = new Set();
}
result[mime] ??= new Set();
result[mime].add(`.${cleanExt}`);
}
});
// Convert Set to Array for React Dropzone
const currentAccept: Record<string, string[]> = {};
const accept: Record<string, string[]> = {};
Object.entries(result).forEach(([mime, extSet]) => {
currentAccept[mime] = Array.from(extSet);
accept[mime] = Array.from(extSet);
});
setAccept(currentAccept);
return currentAccept;
};
useEffect(() => {
buildDropzoneAccept();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { accept, extensions: allowedFormats };
}
const { accept: initialAccept, extensions: initialExtensions } =
buildDropzoneAccept(allowedFormats);
const [accept] = useState<Record<string, string[]>>(initialAccept);
const [extensions] = useState<string>(initialExtensions);
useEffect(() => {
hasFile?.(!!selectedFile);
@ -262,7 +252,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
const onDrop = useCallback(
(acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0];
const file = acceptedFiles[0] as FileWithPath | null;
if (!file) {
toast({
title: "Oups !",
@ -278,7 +268,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
if (inputType === "file") {
setData(name, file);
}
setDialogOpen(true);
setIsDialogOpen(true);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[maxFileSize, formatFileSize],
@ -291,7 +281,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
maxSize: localMaxFileSize,
onDropRejected: (fileRejections) => {
const rejection = fileRejections[0];
const rejectionCode = rejection?.errors?.[0]?.code;
const rejectionCode = rejection.errors[0]?.code as ErrorCode | undefined;
if (rejectionCode === ErrorCode.FileTooLarge) {
toast({
title: "Oups !",
@ -332,7 +322,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
value={value}
reset={reset}
setData={setData}
setDialogOpen={setDialogOpen}
setDialogOpen={setIsDialogOpen}
selectedFile={selectedFile}
validationRules={{
width: localValidationRules.width,
@ -379,10 +369,8 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
"flex border border-dashed overflow-hidden whitespace-normal [&_svg]:!pointer-events-auto [&_svg]:!size-auto [&_svg]:!shrink text-muted-foreground w-full h-36",
{ "border-destructive": localErrors[name] },
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...getRootProps()}
>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<input name={name} {...getInputProps()} />
<div className="flex flex-col justify-center items-center">
<UploadIcon />

View file

@ -1,8 +1,9 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { CheckIcon, ChevronsUpDownIcon, SearchIcon, XIcon } from "lucide-react";
import { useEffect, useState } from "react";
// * Components shadcn
import { useState } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@ -11,15 +12,11 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
import { AppEnv } from "@/types/global";
type EnumSelectProps = {
interface EnumSelectProps {
name: string;
label: string;
options?: Record<
@ -32,11 +29,9 @@ type EnumSelectProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: number | string | null) => void;
// eslint-disable-next-line no-unused-vars
onSelectValue?: (value: number | string | null) => void;
};
}
export default function EnumSelect({
name,
@ -53,22 +48,11 @@ export default function EnumSelect({
}: EnumSelectProps) {
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(([, item]) => !exclude.includes(item.value)),
);
const [currentOptions, setCurrentOptions] =
useState<
Record<string, { label: string; name: string; value: number | string }>
>(initalOptions);
const localErrors = { ...errors, ...parentErrors };
// Model key selected.
const initial =
selected === null || selected === undefined || selected === ""
? null
: selected;
selected && selected !== 0 && selected !== "" ? selected : null;
const [selectedEnum, setSelectedEnum] = useState<number | string | null>(
initial,
);
@ -76,6 +60,19 @@ export default function EnumSelect({
// String research in models collection.
const [search, setSearch] = useState<string>("");
// List of options.
const initalOptions = Object.fromEntries(
Object.entries(options).filter(([, item]) => !exclude.includes(item.value)),
);
const currentOptions =
search.length === 0
? initalOptions
: Object.fromEntries(
Object.entries(initalOptions).filter(([, item]) =>
item.label.toLowerCase().includes(search),
),
);
// Component states.
const [open, setOpen] = useState<boolean>(false);
@ -129,25 +126,6 @@ export default function EnumSelect({
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 (
<div className="flex flex-col w-full gap-1.5">
<Label htmlFor={name} className="flex items-center gap-1.5">
@ -184,7 +162,9 @@ export default function EnumSelect({
placeholder={placeholder}
value={search}
disabled={disabled}
onChange={(e) => setSearch(e.target.value)}
onChange={(e) => {
setSearch(e.target.value);
}}
className="w-[calc(100%-2.5rem-40px)] border-0 mx-9"
/>
<BtnOptionnalLinkWithTooltip
@ -218,10 +198,12 @@ export default function EnumSelect({
{Object.values(currentOptions).map((option) => (
<Button
key={option.value}
className="w-full h-auto min-h-10 justify-between whitespace-normal text-start"
className="w-full h-auto min-h-10 justify-between whitespace-normal text-start font-normal"
variant="ghost"
disabled={disabled}
onClick={() => handleSelect(option.value)}
onClick={() => {
handleSelect(option.value);
}}
>
<span>{str(option.label).ucFirst().value()}</span>
{selectedEnum === option.value && <CheckIcon />}

View file

@ -1,13 +1,4 @@
// * Packages
import {
Dispatch,
MouseEvent,
SetStateAction,
useEffect,
useRef,
useState,
type SyntheticEvent,
} from "react";
import { usePage } from "@inertiajs/react";
import {
ChevronDownIcon,
CropIcon,
@ -21,13 +12,26 @@ import {
ZoomOutIcon,
RefreshCwIcon,
} from "lucide-react";
import { usePage } from "@inertiajs/react";
import {
type Dispatch,
type MouseEvent,
type SetStateAction,
useEffect,
useRef,
useState,
type SyntheticEvent,
} from "react";
import { type FileWithPath } from "react-dropzone";
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 type { ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Dialog,
DialogClose,
@ -37,21 +41,15 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Slider } from "@/components/ui/slider";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} 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 str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
interface CropValidationRules {
@ -63,7 +61,6 @@ type FileWithPreview = FileWithPath & {
preview: string;
};
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
interface ImageCropperProps {
dialogOpen: boolean;
name: string;
@ -78,7 +75,6 @@ interface ImageCropperProps {
reset: (...fields: string[]) => void;
setIsReset: (value: boolean) => void;
}
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
export default function ImageCropper({
dialogOpen,
@ -94,13 +90,14 @@ export default function ImageCropper({
url,
finalFileName,
}: ImageCropperProps) {
const { routes } = usePage().props.configBackend as ConfigBackend;
const { errors } = usePage().props;
const aspect = 1;
const { isDesktop } = useDeviceType();
const imgRef = useRef<HTMLImageElement | null>(null);
const isDuplicating = route().current("uwil-backend::back.*.duplicate");
const isDuplicating = route().current(`${routes.name}*.duplicate`);
// Zone of the crop in %.
const [cropZone, setCropZone] = useState<Crop>();
@ -117,6 +114,12 @@ export default function ImageCropper({
width: 0,
height: 0,
});
const [prevSelectedFile, setPrevSelectedFile] = useState(selectedFile);
if (selectedFile !== prevSelectedFile) {
setPrevSelectedFile(selectedFile);
setImagePosition({ x: 0, y: 0 });
setOriginalDimensions({ width: 0, height: 0 });
}
// États pour les filtres
const [brightness, setBrightness] = useState(100);
@ -139,7 +142,10 @@ export default function ImageCropper({
const canvas = document.createElement("canvas");
canvas.width = validationRules.width;
canvas.height = validationRules.height;
const ctx = canvas.getContext("2d")!;
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("canvas context missing.");
}
// Calculer le ratio entre l'affichage et les dimensions originales
const displayScale = scaleFactor * (1 + zoom);
@ -175,12 +181,16 @@ export default function ImageCropper({
const tmpCanvas = document.createElement("canvas");
tmpCanvas.width = tmpWidth;
tmpCanvas.height = tmpHeight;
const tmpCtx = tmpCanvas.getContext("2d")!;
const tmpCtx = tmpCanvas.getContext("2d");
if (!tmpCtx) {
throw new Error("canvas context missing.");
}
tmpCtx.save();
// Appliquer les filtres
tmpCtx.filter = `brightness(${brightness}%) contrast(${contrast}%) saturate(${saturation}%) sepia(${sepia}%) grayscale(${grayscale}%)`;
tmpCtx.filter = `brightness(${String(brightness)}%) contrast(${String(contrast)}%) saturate(${String(saturation)}%) sepia(${String(sepia)}%) grayscale(${String(grayscale)}%)`;
// Translater au centre du canvas temporaire
tmpCtx.translate(tmpWidth / 2, tmpHeight / 2);
@ -229,9 +239,9 @@ export default function ImageCropper({
*/
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,
): void {
fetch(targetUrl)
@ -239,11 +249,13 @@ export default function ImageCropper({
.then((blob) => {
const reader = new FileReader();
reader.onloadend = () => callback(reader.result);
reader.onloadend = () => {
callback(reader.result);
};
reader.readAsDataURL(blob);
})
.catch((error) => {
if (errorCallback) errorCallback(error);
.catch((error: unknown) => {
if (errorCallback) errorCallback(String(error));
});
}
@ -255,7 +267,7 @@ export default function ImageCropper({
*/
function base64ToFile(dataUrl: string): File {
const [meta, base64] = dataUrl.split(",");
const mimeMatch = meta.match(/:(.*?);/);
const mimeMatch = /:(.*?);/.exec(meta);
const mime = mimeMatch ? mimeMatch[1] : "image/png";
const decodedBase64 = atob(base64);
const { length } = decodedBase64;
@ -290,15 +302,9 @@ export default function ImageCropper({
setIsDragging(false);
}
// Reset de la position et dimensions quand l'image change
useEffect(() => {
setImagePosition({ x: 0, y: 0 });
setOriginalDimensions({ width: 0, height: 0 });
}, [selectedFile]);
useEffect(() => {
if (!value || !isDuplicating) return;
const pathFileBase = `${url}/${value}`;
const pathFileBase = `${url}/${typeof value === "object" ? value.name : value}`;
urlToBase64(
pathFileBase,
(base64) => {
@ -307,16 +313,18 @@ export default function ImageCropper({
setData(name, file);
}
},
(err) => console.error(err),
(err) => {
console.error(err);
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/**
* Crop the image with all options.
* @return Promise<void>
* @return void
*/
async function onCrop(): Promise<void> {
function onCrop(): void {
try {
if (imgRef.current && cropZone) {
// Recalculer les coordonnées en pixels à partir de cropZone actuel
@ -348,8 +356,8 @@ export default function ImageCropper({
}
setDialogOpen(false);
}
} catch (error: Error | unknown) {
throw new Error(`Something went wrong : ${error}`);
} catch (error: unknown) {
throw new Error(`Something went wrong : ${String(error)}`);
}
}
@ -449,7 +457,7 @@ export default function ImageCropper({
if (value) setIsReset(true);
// Recalculer et forcer le centrage de l'image ET de la zone de crop
if (imgRef.current && originalDimensions.width > 0) {
if (originalDimensions.width > 0) {
const displayedWidth = originalDimensions.width * scaleFactor;
const displayedHeight = originalDimensions.height * scaleFactor;
@ -538,7 +546,7 @@ export default function ImageCropper({
// Filters (brightness, contrast, saturation, sepia, grayscale).
const imageFilterOptions = [
{
label: () => `${transBrightness}: ${brightness}%`,
label: () => `${transBrightness}: ${String(brightness)}%`,
tooltip: "brightness",
slider: {
min: 0,
@ -552,7 +560,7 @@ export default function ImageCropper({
},
},
{
label: () => `${transContrast}: ${contrast}%`,
label: () => `${transContrast}: ${String(contrast)}%`,
tooltip: "contrast",
slider: {
min: 0,
@ -566,7 +574,7 @@ export default function ImageCropper({
},
},
{
label: () => `${transSaturation}: ${saturation}%`,
label: () => `${transSaturation}: ${String(saturation)}%`,
tooltip: "saturation",
slider: {
min: 0,
@ -580,7 +588,7 @@ export default function ImageCropper({
},
},
{
label: () => `${transSepia}: ${sepia}%`,
label: () => `${transSepia}: ${String(sepia)}%`,
tooltip: "sepia",
slider: {
min: 0,
@ -594,7 +602,7 @@ export default function ImageCropper({
},
},
{
label: () => `${transGrayscale}: ${grayscale}%`,
label: () => `${transGrayscale}: ${String(grayscale)}%`,
tooltip: "grayscale",
slider: {
min: 0,
@ -612,7 +620,7 @@ export default function ImageCropper({
// Main options (rotation, zoom).
const mainOptions = [
{
label: () => `${transRotation}: ${rotation}°`,
label: () => `${transRotation}: ${String(rotation)}°`,
tooltip: "rotation",
slider: {
min: -180,
@ -628,17 +636,21 @@ export default function ImageCropper({
{
icon: RotateCcwIcon,
tooltip: "rotation_back",
fn: () => setRotation((r) => r - 10),
fn: () => {
setRotation((r) => r - 10);
},
},
{
icon: RotateCwIcon,
tooltip: "rotation_forward",
fn: () => setRotation((r) => r + 10),
fn: () => {
setRotation((r) => r + 10);
},
},
],
},
{
label: () => `${transZoom}: ${Math.round((1 + zoom) * 100)}%`,
label: () => `${transZoom}: ${String(Math.round((1 + zoom) * 100))}%`,
tooltip: "zoom",
slider: {
min: -0.99,
@ -681,12 +693,16 @@ export default function ImageCropper({
const otherOptions = [
{
icon: FlipHorizontalIcon,
fn: () => setFlipX((prev) => !prev),
fn: () => {
setFlipX((prev) => !prev);
},
tooltip: "horizontal_flip",
},
{
icon: FlipVerticalIcon,
fn: () => setFlipY((prev) => !prev),
fn: () => {
setFlipY((prev) => !prev);
},
tooltip: "vertical_flip",
},
{
@ -735,7 +751,9 @@ export default function ImageCropper({
>
<ReactCrop
crop={cropZone}
onChange={(_, percentCrop) => setCropZone(percentCrop)}
onChange={(_, percentCrop) => {
setCropZone(percentCrop);
}}
aspect={aspect}
className="w-full"
locked
@ -761,18 +779,18 @@ export default function ImageCropper({
)}
style={{
position: "absolute",
left: `${imagePosition.x}px`,
top: `${imagePosition.y}px`,
left: `${String(imagePosition.x)}px`,
top: `${String(imagePosition.y)}px`,
width:
originalDimensions.width > 0
? `${originalDimensions.width * scaleFactor}px`
? `${String(originalDimensions.width * scaleFactor)}px`
: "auto",
height:
originalDimensions.height > 0
? `${originalDimensions.height * scaleFactor}px`
? `${String(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}%)`,
transform: `scale(${String(1 + zoom)}) rotate(${String(rotation)}deg) scaleX(${String(flipX ? -1 : 1)}) scaleY(${String(flipY ? -1 : 1)})`,
filter: `brightness(${String(brightness)}%) contrast(${String(contrast)}%) saturate(${String(saturation)}%) sepia(${String(sepia)}%) grayscale(${String(grayscale)}%)`,
transformOrigin: "center center",
transition: !isDragging
? "transform 0.2s ease, filter 0.2s ease"
@ -794,7 +812,10 @@ export default function ImageCropper({
)}
</DialogDescription>
{mainOptions.map((option) => (
<div className="flex items-center gap-2 w-full mb-4">
<div
key="option"
className="flex items-center gap-2 w-full mb-4"
>
<div className="flex flex-col w-full items-start">
<label htmlFor="rotation" className="mb-2 text-sm">
{option.label()}
@ -822,7 +843,7 @@ export default function ImageCropper({
</div>
<div className="flex items-center gap-1">
{option.buttons.map((currentOption) => (
<Tooltip>
<Tooltip key="currentOption">
<TooltipTrigger asChild>
<Button
variant="outline"
@ -871,7 +892,10 @@ export default function ImageCropper({
<CollapsibleContent className="space-y-4 pt-4">
<div className="grid grid-cols-2 gap-4">
{imageFilterOptions.map((option) => (
<div className="flex flex-col items-start">
<div
key="filterOption"
className="flex flex-col items-start"
>
<label
htmlFor={str(option.label()).slug().value()}
className="mb-2 text-sm"
@ -908,7 +932,7 @@ export default function ImageCropper({
<div className="flex flex-row justify-center gap-2 mb-4">
{otherOptions.map((option) => {
return (
<Tooltip>
<Tooltip key="otherOption">
<TooltipTrigger asChild>
<Button variant="outline" size="sm" onClick={option.fn}>
<option.icon />

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,25 +1,23 @@
// * Packages
import { useState, useEffect, useRef, ReactNode } from "react";
import { usePage } from "@inertiajs/react";
import { SketchPicker, ColorResult } from "react-color";
import { RefreshCwIcon, TrashIcon, ShuffleIcon } from "lucide-react";
import { PresetColor } from "react-color/lib/components/sketch/Sketch";
// * Components shadcn
import { Label } from "@/components/ui/label";
import { useState, type ReactNode } from "react";
import { SketchPicker, type ColorResult } from "react-color";
import { type PresetColor } from "react-color/lib/components/sketch/Sketch";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "@/components/ui/popover";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import InputError from "@/back/Components/InputError";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
type SimpleColorPickerProps = {
interface SimpleColorPickerProps {
className?: string;
name: string;
id?: string;
@ -31,16 +29,15 @@ type SimpleColorPickerProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
/* eslint-disable no-unused-vars */
setData: (name: string, value: string | null) => void;
};
}
export default function SimpleColorPicker({
className,
name,
id = name,
label,
value = null,
value,
placeholder = "#ffffffff",
presetColors = [
"#000000", // Black
@ -65,7 +62,14 @@ export default function SimpleColorPicker({
// Colors.
const [color, setColor] = useState<string | null>(value);
const initialColor = useRef<string | null>(value ?? "#ffffffff");
const [initialColor] = useState<string>(value ?? "#ffffffff");
const [prevValue, setPrevValue] = useState<string | null>(value);
// Compare old value.
if (value !== prevValue) {
setPrevValue(value);
setColor(value);
}
// Popover status.
const [open, setOpen] = useState(false);
@ -95,10 +99,9 @@ export default function SimpleColorPicker({
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";
const a = Math.round((targetColor.rgb.a ?? 1) * 255)
.toString(16)
.padStart(2, "0");
return `#${r}${g}${b}${a}`;
}
@ -159,8 +162,8 @@ export default function SimpleColorPicker({
* @return void
*/
function handleReset(): void {
setColor(initialColor.current);
setData(name, initialColor.current);
setColor(initialColor);
setData(name, initialColor);
}
/**
@ -194,11 +197,6 @@ export default function SimpleColorPicker({
}
}
useEffect(() => {
if (value !== color) setColor(value);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
return (
<div className={cn("flex flex-col gap-2", className)}>
<Label htmlFor={id} className="flex items-center gap-1.5">
@ -218,7 +216,7 @@ export default function SimpleColorPicker({
className="w-10 h-10 border-0"
disabled={disabled}
style={{
background: color || "transparent",
background: color ?? "transparent",
outline: "1px solid hsl(var(--input))",
}}
/>
@ -227,7 +225,9 @@ export default function SimpleColorPicker({
<Input
id={id}
value={color ?? ""}
onChange={(e) => handleInput(e.target.value)}
onChange={(e) => {
handleInput(e.target.value);
}}
placeholder={placeholder}
disabled={disabled}
className="flex-1"
@ -235,11 +235,13 @@ export default function SimpleColorPicker({
{/* POPUP CONTENT */}
<PopoverContent className="p-2">
<SketchPicker
color={String(color || initialColor.current)}
onChange={(newColor) => handleChange(newColor)}
onChangeComplete={(newCompleteColor) =>
handleChangeComplete(newCompleteColor)
}
color={color ?? initialColor}
onChange={(newColor) => {
handleChange(newColor);
}}
onChangeComplete={(newCompleteColor) => {
handleChangeComplete(newCompleteColor);
}}
disableAlpha={false}
presetColors={presetColors}
/>
@ -253,7 +255,9 @@ export default function SimpleColorPicker({
type="button"
variant="secondary"
size="icon"
onClick={() => handleRandom()}
onClick={() => {
handleRandom();
}}
disabled={disabled}
/>
)}
@ -264,7 +268,9 @@ export default function SimpleColorPicker({
type="button"
variant="secondary"
size="icon"
onClick={() => handleReset()}
onClick={() => {
handleReset();
}}
disabled={disabled}
/>
{!required && (
@ -274,12 +280,14 @@ export default function SimpleColorPicker({
type="button"
variant="destructive"
size="icon"
onClick={() => handleClear()}
onClick={() => {
handleClear();
}}
disabled={disabled}
/>
)}
</div>
<InputError message={localErrors?.[name]} />
<InputError message={localErrors[name]} />
</div>
);
}

View file

@ -1,27 +1,25 @@
// * Other
import { fr, enUS } from "date-fns/locale";
import { usePage } from "@inertiajs/react";
import { fr, enUS } from "date-fns/locale";
import { CalendarIcon, RefreshCcw } from "lucide-react";
import { ReactNode } from "react";
// * Components shadcn
import { type ReactNode } from "react";
import InputError from "@/back/Components/InputError";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Label } from "@/components/ui/label";
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 { Separator } from "@/components/ui/separator";
import str from "@/hooks/use-string";
import useLocale from "@/store/use-locale-store";
import useTrans from "@/hooks/use-translations";
import { cn, GetFormatedDate } from "@/lib/utils";
import useLocale from "@/store/use-locale-store";
type SimpleDatePickerProps = {
interface SimpleDatePickerProps {
name: string;
placeholder?: string;
date?: Date | null;
@ -31,9 +29,9 @@ type SimpleDatePickerProps = {
label: ReactNode | string;
hasTime?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: Date | null) => void;
};
}
export default function SimpleDatePicker({
name,
@ -74,12 +72,12 @@ export default function SimpleDatePicker({
};
function handleTimeChange(type: "hour" | "minute", value: string) {
const currentDate = parsedDate || new Date();
const currentDate = parsedDate ?? new Date();
const newDate = new Date(currentDate);
if (type === "hour") {
const hour = parseInt(value, 10);
newDate.setHours(hour);
} else if (type === "minute") {
} else {
newDate.setMinutes(parseInt(value, 10));
}
setData(name, newDate);
@ -106,9 +104,9 @@ export default function SimpleDatePicker({
disabled={disabled}
>
<span>
{date && date !== undefined
{date
? GetFormatedDate(
date?.toString(),
date.toString(),
useLocale.use.timezone(),
hasTime,
)
@ -140,18 +138,16 @@ export default function SimpleDatePicker({
key={hour}
size="icon"
variant={
parsedDate && parsedDate.getHours() === hour
? "default"
: "ghost"
parsedDate?.getHours() === hour ? "default" : "ghost"
}
className="sm:w-full shrink-0 aspect-square"
onClick={() =>
handleTimeChange("hour", hour.toString())
}
onClick={() => {
handleTimeChange("hour", hour.toString());
}}
>
<p
className={cn(
parsedDate && parsedDate.getHours() === hour
parsedDate?.getHours() === hour
? "text-primary-foreground"
: "",
)}
@ -170,18 +166,18 @@ export default function SimpleDatePicker({
key={minute}
size="icon"
variant={
parsedDate && parsedDate.getMinutes() === minute
parsedDate?.getMinutes() === minute
? "default"
: "ghost"
}
className="sm:w-full shrink-0 aspect-square"
onClick={() =>
handleTimeChange("minute", minute.toString())
}
onClick={() => {
handleTimeChange("minute", minute.toString());
}}
>
<p
className={cn(
parsedDate && parsedDate.getMinutes() === minute
parsedDate?.getMinutes() === minute
? "text-primary-foreground"
: "",
)}

View file

@ -108,7 +108,7 @@ export default function SimpleInputFile(props: Readonly<SimpleInputFileProps>) {
? Array.isArray(value) && value.every((v) => typeof v === "string")
: value != null && typeof value === "string";
const localErrors = parentErrors ?? errors;
const localErrors = { ...errors, ...parentErrors };
const localMaxFileSize = maxFileSize
? Number.parseInt(maxFileSize, 10) * 1024

View file

@ -1,29 +1,27 @@
// * Packages
import { useState, useEffect, ReactNode } from "react";
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { useState, type ReactNode } from "react";
import InputError from "@/back/Components/InputError";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
// * Other
import InputError from "@/back/Components/InputError";
import { cn } from "@/lib/utils";
import { type MinMax } from "@/hooks/use-laravel-validation";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
type SimpleNumberProps = {
interface SimpleNumberProps {
className?: string;
name: string;
label: ReactNode | string;
value?: number;
id?: string;
step?: number;
limits?: Record<string, number>;
limits?: MinMax;
placeholder?: string;
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
}
export default function SimpleNumber({
className,
@ -43,21 +41,15 @@ export default function SimpleNumber({
const localErrors = parentErrors ?? errors;
const localLimits = {
min: limits?.min ? limits.min : 1,
max: limits?.max ? limits.max : 1000,
min: limits?.min ?? 1,
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]);
const [inputValue, setInputValue] = useState<number>(safeValue);
return (
<div className={cn("flex flex-col w-full gap-1.5", className)}>
@ -76,7 +68,12 @@ export default function SimpleNumber({
max={localLimits.max}
step={step}
onChange={(e) => {
setInputValue(Number(e.target.value));
const num = Number(e.target.value);
const clamped = Math.min(
localLimits.max,
Math.max(localLimits.min, num),
);
setInputValue(clamped);
setData(name, e.target.value);
}}
required={required}

View file

@ -1,18 +1,16 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { EyeIcon, EyeOffIcon } from "lucide-react";
import { ReactNode, useEffect, useRef, useState } from "react";
// * Components shadcn
import { useState, useEffect, useRef, type ReactNode } from "react";
import InputError from "@/back/Components/InputError";
import WordCounter from "@/back/Components/WordCounter";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
// * Other
import InputError from "@/back/Components/InputError";
import WordCounter from "@/back/Components/WordCounter";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
type SimpleStringProps = {
interface SimpleStringProps {
className?: string;
name: string;
label: ReactNode | string;
@ -29,7 +27,7 @@ type SimpleStringProps = {
parentErrors?: Record<string, string> | null;
onBlur?: () => void;
setData: (name: string, value: string) => void;
};
}
export default function SimpleString({
className,
@ -51,7 +49,7 @@ export default function SimpleString({
const [isVisible, setIsVisible] = useState(checkVisibility);
const inputRef = useRef<HTMLInputElement>(null);
const { errors } = usePage().props;
const localErrors = parentErrors ?? errors;
const localErrors = { ...errors, ...parentErrors };
useEffect(() => {
if (inputRef.current && inputRef.current.value !== value) {

View file

@ -1,14 +1,13 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { ReactNode } from "react";
// * Components shadcn
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
// * Other
import { type ReactNode } from "react";
import InputError from "@/back/Components/InputError";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
type SimpleSwitchProps = {
interface SimpleSwitchProps {
id?: string;
name: string;
checked?: boolean;
label?: ReactNode | string;
@ -18,12 +17,12 @@ type SimpleSwitchProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: boolean) => void;
};
}
export default function SimpleSwitch({
name,
id = name,
checked,
label,
leftHelper,
@ -48,9 +47,11 @@ export default function SimpleSwitch({
<div className="flex items-center gap-3">
{leftHelper && <small>{leftHelper}</small>}
<Switch
id={name}
id={id}
name={name}
onCheckedChange={(value) => setData(name, value)}
onCheckedChange={(value) => {
setData(name, value);
}}
required={required}
checked={checked}
disabled={disabled}

View file

@ -1,15 +1,13 @@
// * Packages
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
// * Other
import InputError from "@/back/Components/InputError";
import WordCounter from "@/back/Components/WordCounter";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
type SimpleTextareaProps = {
interface SimpleTextareaProps {
className?: string;
name: string;
label: string;
@ -22,7 +20,7 @@ type SimpleTextareaProps = {
parentErrors?: Record<string, string> | null;
onBlur?: () => void;
setData: (name: string, value: string) => void;
};
}
export default function SimpleTextarea({
className,
@ -39,7 +37,7 @@ export default function SimpleTextarea({
setData,
}: SimpleTextareaProps) {
const { errors } = usePage().props;
const localErrors = parentErrors ?? errors;
const localErrors = { ...errors, ...parentErrors };
return (
<div

View file

@ -1,9 +1,8 @@
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
type SimpleVimeoIdProps = {
interface SimpleVimeoIdProps {
className?: string;
name: string;
value?: string;
@ -11,9 +10,8 @@ type SimpleVimeoIdProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
}
export default function SimpleVimeoId(props: SimpleVimeoIdProps) {
const pattern = "^[0-9]{8,10}$";
@ -21,6 +19,5 @@ export default function SimpleVimeoId(props: SimpleVimeoIdProps) {
.ucFirst()
.value();
// eslint-disable-next-line react/jsx-props-no-spreading
return <SimpleString pattern={pattern} label={label} {...props} />;
}

View file

@ -1,9 +1,8 @@
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
type SimpleYoutubeIdProps = {
interface SimpleYoutubeIdProps {
className?: string;
name: string;
value?: string;
@ -11,9 +10,8 @@ type SimpleYoutubeIdProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
}
export default function SimpleYoutubeId(props: SimpleYoutubeIdProps) {
const pattern = "^[0-9A-Za-z_\\-]{10}[048AEIMQUYcgkosw]$";
@ -21,6 +19,5 @@ export default function SimpleYoutubeId(props: SimpleYoutubeIdProps) {
.ucFirst()
.value();
// eslint-disable-next-line react/jsx-props-no-spreading
return <SimpleString pattern={pattern} label={label} {...props} />;
}

View file

@ -1,8 +1,7 @@
// * Packages
import { GavelIcon } from "lucide-react";
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
@ -11,7 +10,6 @@ interface SlugifycatorProps {
targetValue: string;
wordCounter?: boolean;
disabled?: boolean;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
}
@ -50,7 +48,9 @@ export default function Slugifycator(props: SlugifycatorProps) {
.value()}
type="button"
variant="secondary"
onClick={() => setData("slug", str(targetValue).slug().value())}
onClick={() => {
setData("slug", str(targetValue).slug().value());
}}
disabled={disabled}
/>
</div>

View file

@ -1,18 +1,15 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { useEffect } from "react";
// * Other
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { LaravelEnumMap } from "@/types/global";
interface Props {
name: string;
selected: number;
required: boolean;
label: string;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: number | null) => void;
}
@ -20,7 +17,7 @@ export default function StaticRouteSelect(props: Props) {
const { name, selected, required, label, setData } = props;
const enumStaticRoutesEnum = usePage().props
.enumStaticRoutesEnum as LaravelEnumMap | null;
.enumStaticRoutesEnum as LaravelEnum | null;
const transSelectValue = str(
useTrans("uwil-backend::back.static_route.select_value"),
@ -51,7 +48,16 @@ export default function StaticRouteSelect(props: Props) {
placeholder={transSelectValue}
selected={selected}
options={enumStaticRoutesEnum}
setData={setData}
setData={(fieldName, value) => {
setData(
fieldName,
typeof value === "number"
? value
: value !== null
? Number(value)
: null,
);
}}
required={required}
/>
);

View file

@ -1,10 +1,9 @@
// * Packages
import { Image as TiptapImage } from "@tiptap/extension-image";
import { ReactNodeViewRenderer } from "@tiptap/react";
// * Other
import ImageNodeView, {
FLOAT_STYLES,
FloatOption,
type FloatOption,
} from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageNodeView";
import { imageDetails } from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils";
@ -38,19 +37,23 @@ 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");
const figcaption = element.querySelector("figcaption");
if (!img) {
throw new Error("Missing tag img.");
}
return {
src: img.src,
alt: img.getAttribute("alt"),
title: img.getAttribute("title"),
width: parseInt(
img.getAttribute("width") || imageDetails.width,
img.getAttribute("width") ?? imageDetails.width,
10,
),
height: parseInt(
img.getAttribute("height") || imageDetails.height,
img.getAttribute("height") ?? imageDetails.height,
10,
),
style: null,
@ -67,9 +70,10 @@ const Image = TiptapImage.extend({
// Define the structure of the render.
// Use for render html in front files.
renderHTML({ node, HTMLAttributes }) {
const src = HTMLAttributes.src as string;
const attrsCopy: AttrsType = {
...HTMLAttributes,
src: HTMLAttributes.src.replace(/^https?:\/\/[^/]+/, ""),
src: src.replace(/^https?:\/\/[^/]+/, ""),
};
delete attrsCopy.caption;

View file

@ -1,11 +1,16 @@
// * Packages
import { useEffect, useState } from "react";
import axios from "axios";
import { route } from "ziggy-js";
import { type Editor } from "@tiptap/react";
import { ImageUpIcon } from "lucide-react";
import { Editor } from "@tiptap/react";
import { useState } from "react";
import { z } from "zod";
// * Components shadcn
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile";
import ImageInputs from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs";
import {
imageTextSchema,
imageDetails,
} from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogDescription,
@ -16,44 +21,43 @@ import {
DialogFooter,
} from "@/components/ui/dialog";
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,
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 useTrans from "@/hooks/use-translations";
import { GetTranslation } from "@/lib/utils";
type ImageProps = {
/** Wysiwyg editor instance. */
editor: Editor;
/** Disable trigger button. */
disabled: boolean;
};
type ImageFormat = "landscape" | "portrait" | "square";
type ImageType = {
interface ImageType {
name: ImageFormat;
style: string;
width: number;
height: number;
};
}
export default function ImageButton({ editor, disabled }: ImageProps) {
interface ImageProps {
/** Wysiwyg editor instance. */
editor: Editor;
/** Route name prefix. */
routeName: string;
/** Disable trigger button. */
disabled: boolean;
}
export default function ImageButton({
editor,
routeName,
disabled,
}: ImageProps) {
// Get all editor options define with customOptions in the parent SimpleWysiwyg.
const editorOptions = editor.options.editorProps?.attributes as {
[name: string]: string;
};
const editorOptions = editor.options.editorProps.attributes as Record<
string,
string
>;
// State of the plugin modal.
const [open, setOpen] = useState(false);
// Value of the input file image.
const [inputFile, setFile] = useState<string | File | null>(null);
const [inputFile, setInputFile] = useState<string | File | null>(null);
// Values of inputs text.
const [inputText, setInputText] = useState<{
alt: string;
@ -216,7 +220,7 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
* @return void
*/
const resetComponent = () => {
setFile(null);
setInputFile(null);
setInputText({
alt: "",
title: "",
@ -235,24 +239,31 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
* @return Promise<void>
*/
const uploadImage = async (file: File): Promise<string | null> => {
// Get the csrf token value.
const csrfToken =
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") ?? "";
// Prepare the form data.
const data = new FormData();
data.append("upload", file);
data.append("tableName", editorOptions.tableName);
// Get wysiwyg image route upload.
const uploadRoute = route("back.wysiwyg.upload");
const uploadRoute = route(`${routeName}wysiwyg.upload`);
try {
const response = await axios.post(uploadRoute, data, {
const response = await window.axios.post(uploadRoute, data, {
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-Inertia": "false",
"X-CSRF-TOKEN": csrfToken,
},
});
return response.data.url;
return (response.data as { url: string }).url;
} catch (error: unknown) {
setNewErrors(error);
return null;
@ -298,7 +309,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
height: String(inputType.height),
});
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
}
} catch (error: unknown) {
setNewErrors(error);
@ -314,7 +327,7 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
*/
const handleSetImage = (name: string, value: string | File | null): void => {
setErrors((prev) => ({ ...prev, [name]: "" }));
setFile(value);
setInputFile(value);
};
/**
@ -324,26 +337,20 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
*/
const handleCancelImage = (): void => {
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
};
// Set default value to the caption.
useEffect(() => {
setInputText({
alt: inputText.alt,
title: inputText.title,
caption: inputText.hasCaption ? inputText.caption : null,
hasCaption: inputText.hasCaption,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inputText.hasCaption]);
return (
<Dialog
open={open}
onOpenChange={(status) => {
setOpen(status);
if (!status) setTimeout(() => resetComponent(), animationTime);
if (!status)
setTimeout(() => {
resetComponent();
}, animationTime);
}}
>
{/* Button trigger in wysiwyg navigation. */}
@ -377,7 +384,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
{Object.values(ImageTypes).map((type) => (
<Button
key={type.name}
onClick={() => setInputType(type)}
onClick={() => {
setInputType(type);
}}
className="flex flex-col items-center gap-1.5 w-full h-fit"
variant={
inputType.name === type.name ? "default" : "secondary"
@ -411,7 +420,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
.ucFirst()
.value()}
setData={handleSetImage}
reset={() => {}}
reset={() => {
/* empty */
}}
value={null}
required
maxFileSize="5120"
@ -424,7 +435,12 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
/>
<ImageInputs
value={inputText}
onChange={setInputText}
onChange={(newValue) => {
setInputText({
...newValue,
caption: newValue.hasCaption ? newValue.caption : null,
});
}}
disabled={disabled || loading}
errors={errors}
/>
@ -443,7 +459,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
type="button"
size="default"
disabled={loading}
onClick={handleCancelImage}
onClick={() => {
handleCancelImage();
}}
/>
{/* Save button. */}
<BtnOptionnalLinkWithTooltip
@ -457,7 +475,9 @@ export default function ImageButton({ editor, disabled }: ImageProps) {
type="button"
size="default"
disabled={loading}
onClick={handleAddImage}
onClick={() => {
void handleAddImage();
}}
/>
</DialogFooter>
</DialogContent>

View file

@ -1,22 +1,20 @@
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
type ImageInputsProps = {
interface ImageInputsProps {
value: {
alt: string;
title: string;
caption: string | null;
hasCaption: boolean;
};
// eslint-disable-next-line no-unused-vars
onChange: (value: ImageInputsProps["value"]) => void;
errors?: Record<string, string>;
loading?: boolean;
disabled?: boolean;
};
}
export default function ImageInputs({
value,
@ -40,7 +38,9 @@ export default function ImageInputs({
placeholder="ex: John Doe"
required
value={value.alt}
setData={(_, currentValue) => onChange({ ...value, alt: currentValue })}
setData={(_, currentValue) => {
onChange({ ...value, alt: currentValue });
}}
disabled={disabled || loading}
parentErrors={errors}
/>
@ -53,9 +53,9 @@ export default function ImageInputs({
placeholder="ex: John Doe"
required
value={value.title}
setData={(_, currentValue) =>
onChange({ ...value, title: currentValue })
}
setData={(_, currentValue) => {
onChange({ ...value, title: currentValue });
}}
disabled={disabled || loading}
parentErrors={errors}
/>
@ -72,13 +72,13 @@ export default function ImageInputs({
name="hasCaption"
checked={value.hasCaption}
className="justify-center"
setData={(_, currentValue) =>
setData={(_, currentValue) => {
onChange({
...value,
hasCaption: currentValue,
caption: currentValue ? value.caption : null,
})
}
});
}}
/>
{/* Input caption of the image. */}
{value.hasCaption && (
@ -88,9 +88,9 @@ export default function ImageInputs({
placeholder="ex: John Doe"
required={false}
value={value.caption ?? ""}
setData={(_, currentValue) =>
onChange({ ...value, caption: currentValue })
}
setData={(_, currentValue) => {
onChange({ ...value, caption: currentValue });
}}
disabled={disabled || loading}
parentErrors={errors}
/>

View file

@ -1,5 +1,5 @@
// * Packages
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { usePage } from "@inertiajs/react";
import { type NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import {
MoveDiagonal2Icon,
AlignLeftIcon,
@ -10,11 +10,16 @@ import {
LayoutIcon,
ChevronsLeftRightEllipsisIcon,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { MouseEvent as ReactMouseEvent } from "react";
import z from "zod";
import { usePage } from "@inertiajs/react";
// * Components shadcn
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import ImageInputs from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs";
import {
imageDetails,
imageTextSchema,
} from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageUtils";
import { Button } from "@/components/ui/button";
import {
Dialog,
@ -30,18 +35,10 @@ import {
SelectItem,
SelectTrigger,
} from "@/components/ui/select";
// * Other
import ImageInputs from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageInputs";
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, GetTranslation } from "@/lib/utils";
import { parseStyleString } from "@/hooks/use-inline-style";
import { AppEnv } from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
export type AllowedAligns = "left" | "center" | "right";
@ -77,7 +74,7 @@ const PLACEMENT_STYLES: Record<PlacementValue, string> = {
"float-right": FLOAT_STYLES.right,
};
type ImageAttrs = {
interface ImageAttrs {
src: string;
alt: string;
title: string;
@ -86,7 +83,7 @@ type ImageAttrs = {
caption: string | null;
style: string;
float: FloatOption;
};
}
export default function ImageNodeView(props: NodeViewProps) {
const { node, updateAttributes, editor, selected } = props;
@ -94,13 +91,13 @@ export default function ImageNodeView(props: NodeViewProps) {
const attrs = node.attrs as ImageAttrs;
const imgRef = useRef<HTMLImageElement>(null);
const resizeState = useRef<{
const resizeStateRef = useRef<{
startX: number;
startWidth: number;
ratio: number;
} | null>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const isInteractingWithChildren = useRef<boolean>(false);
const isInteractingWithChildrenRef = useRef<boolean>(false);
const [editorFocused, setEditorFocused] = useState<boolean>(false);
const [isResizing, setIsResizing] = useState<boolean>(false);
@ -120,7 +117,13 @@ export default function ImageNodeView(props: NodeViewProps) {
hasCaption: !!attrs.caption,
});
// Value of the height of header + @tiptap toolbar editor.
const [topSticky, setTopSticky] = useState<number>(0);
const [topSticky, setTopSticky] = useState<number>(() => {
const header = document.querySelector("header");
const firstToolbar = document.querySelectorAll(
".tiptap-toolbar",
)[0] as HTMLElement | null;
return (header?.clientHeight ?? 0) + (firstToolbar?.clientHeight ?? 0);
});
// Translations.
const transAlt = useTrans("uwil-backend::back.wysiwyg.image.attribute_alt");
@ -151,9 +154,9 @@ export default function ImageNodeView(props: NodeViewProps) {
* @return void
*/
const handleClickOnChildren = (): void => {
isInteractingWithChildren.current = true;
isInteractingWithChildrenRef.current = true;
requestAnimationFrame(() => {
isInteractingWithChildren.current = false;
isInteractingWithChildrenRef.current = false;
});
};
@ -164,10 +167,13 @@ export default function ImageNodeView(props: NodeViewProps) {
*/
const getCurrentPlacement = (): PlacementValue | null => {
if (attrs.float === "left") return "float-left";
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (attrs.float === "right") return "float-right";
if (attrs.style?.includes(ALIGN_STYLES.left)) return "align-left";
if (attrs.style?.includes(ALIGN_STYLES.center)) return "align-center";
if (attrs.style?.includes(ALIGN_STYLES.right)) return "align-right";
if (attrs.style) {
if (attrs.style.includes(ALIGN_STYLES.left)) return "align-left";
if (attrs.style.includes(ALIGN_STYLES.center)) return "align-center";
if (attrs.style.includes(ALIGN_STYLES.right)) return "align-right";
}
return null;
};
@ -200,7 +206,7 @@ export default function ImageNodeView(props: NodeViewProps) {
const img = imgRef.current;
if (!img) return;
resizeState.current = {
resizeStateRef.current = {
startX: event.clientX,
startWidth: img.offsetWidth,
ratio: img.offsetWidth / img.offsetHeight,
@ -215,9 +221,9 @@ export default function ImageNodeView(props: NodeViewProps) {
* @return void
*/
const onMouseMove = (event: MouseEvent): void => {
if (!isResizing || !resizeState.current) return;
if (!isResizing || !resizeStateRef.current) return;
const { startX, startWidth, ratio } = resizeState.current;
const { startX, startWidth, ratio } = resizeStateRef.current;
let newWidth = startWidth + (event.clientX - startX);
let newHeight = newWidth / ratio;
@ -251,7 +257,7 @@ export default function ImageNodeView(props: NodeViewProps) {
*/
const onMouseUp = (): void => {
setIsResizing(false);
resizeState.current = null;
resizeStateRef.current = null;
};
/**
@ -319,7 +325,7 @@ export default function ImageNodeView(props: NodeViewProps) {
* @param status boolean
* @return void
*/
const closeModal = (status: boolean = false): void => {
const closeModal = (status = false): void => {
setOpen(status);
setEditorFocused(false);
};
@ -339,7 +345,7 @@ export default function ImageNodeView(props: NodeViewProps) {
* @return void
*/
const handleBlur = ({ event }: { event?: FocusEvent }): void => {
if (isInteractingWithChildren.current) {
if (isInteractingWithChildrenRef.current) {
return;
}
@ -353,8 +359,6 @@ export default function ImageNodeView(props: NodeViewProps) {
// Update the focus on @tiptap editor.
useEffect(() => {
if (!editor) return undefined;
editor.on("focus", handleFocus);
editor.on("blur", handleBlur);
@ -378,31 +382,26 @@ export default function ImageNodeView(props: NodeViewProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isResizing]);
// Set default value to the caption.
useEffect(() => {
setInputText({
alt: inputText.alt,
title: inputText.title,
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.
useEffect(() => {
const handleResize = () => {
const currentHeaderHeight =
document.querySelector("header")?.clientHeight ?? 0;
const currentToolbarHeight =
document.querySelectorAll(".tiptap-toolbar")[0].clientHeight ?? 0;
useLayoutEffect(() => {
const header = document.querySelector("header");
const firstToolbar = document.querySelectorAll(
".tiptap-toolbar",
)[0] as HTMLElement | null;
const updateTopSticky = () => {
const currentHeaderHeight = header?.clientHeight ?? 0;
const currentToolbarHeight = firstToolbar?.clientHeight ?? 0;
setTopSticky(currentHeaderHeight + currentToolbarHeight);
};
window.addEventListener("resize", handleResize);
handleResize();
const observer = new ResizeObserver(updateTopSticky);
if (header) observer.observe(header);
if (firstToolbar) observer.observe(firstToolbar);
return () => window.removeEventListener("resize", handleResize);
return () => {
observer.disconnect();
};
}, []);
return (
@ -422,8 +421,8 @@ export default function ImageNodeView(props: NodeViewProps) {
top: topSticky,
}}
>
<span className="absolute top-2 left-2 bg-background backdrop-blur-sm rounded-md border shadow-md m-0 p-1">
{`${attrs.width || imageDetails.width}x${attrs.height || imageDetails.height}`}
<span className="absolute top-2 left-2 bg-background backdrop-blur-xs rounded-md border shadow-md m-0 p-1">
{`${String(attrs.width || imageDetails.width)}x${String(attrs.height || imageDetails.height)}`}
</span>
</div>
)}
@ -437,10 +436,10 @@ export default function ImageNodeView(props: NodeViewProps) {
draggable={false}
/>
{editorFocused && selected && (
<div className="absolute bottom-2 right-2 flex flex-col gap-1 bg-background backdrop-blur-sm rounded-md border shadow-md p-1">
<div className="absolute bottom-2 right-2 flex flex-col gap-1 bg-background backdrop-blur-xs rounded-md border shadow-md p-1">
{/* Placement dropdown */}
<Select
value={getCurrentPlacement() || "default"}
value={getCurrentPlacement() ?? "default"}
onValueChange={handlePlacementChange}
>
<SelectTrigger
@ -506,7 +505,9 @@ export default function ImageNodeView(props: NodeViewProps) {
variant="outline"
size="icon"
onMouseDown={onMouseDown}
onClick={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
}}
className={cn("cursor-nw-resize", {
"bg-accent text-accent-foreground": isResizing,
})}
@ -526,7 +527,12 @@ export default function ImageNodeView(props: NodeViewProps) {
</figcaption>
)}
{/* Dialog Shadcn */}
<Dialog open={open} onOpenChange={(status) => closeModal(status)}>
<Dialog
open={open}
onOpenChange={(status) => {
closeModal(status);
}}
>
<DialogContent className="p-4">
<DialogHeader className="px-2 pt-2">
<DialogTitle>
@ -539,7 +545,12 @@ export default function ImageNodeView(props: NodeViewProps) {
<div className="overflow-y-scroll max-h-[70vh] flex flex-col gap-4 px-2">
<ImageInputs
value={inputText}
onChange={setInputText}
onChange={(newValue) => {
setInputText({
...newValue,
caption: newValue.hasCaption ? newValue.caption : null,
});
}}
errors={errors}
/>
</div>
@ -554,7 +565,9 @@ export default function ImageNodeView(props: NodeViewProps) {
)
.ucFirst()
.value()}
onClick={() => closeModal()}
onClick={() => {
closeModal();
}}
type="button"
variant="secondary"
size="default"
@ -566,7 +579,9 @@ export default function ImageNodeView(props: NodeViewProps) {
)
.ucFirst()
.value()}
onClick={saveDialog}
onClick={() => {
saveDialog();
}}
type="button"
variant="default"
size="default"

View file

@ -1,4 +1,3 @@
// * Packages
import { z } from "zod";
// Set image details.

View file

@ -1,11 +1,9 @@
// * Packages
import "@tiptap/core";
// Set custom function attributes.
declare module "@tiptap/core" {
interface Commands<ReturnType> {
Image: {
// eslint-disable-next-line no-unused-vars
setImage: (attrs: {
src: string;
alt: string;

View file

@ -1,14 +1,14 @@
// * Packages
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";
import { mergeAttributes, getMarkRange } from "@tiptap/react";
import { type Mark } from "prosemirror-model";
import { Plugin, PluginKey, TextSelection } from "prosemirror-state";
export type LinkAttrs = {
export interface LinkAttrs {
text: string;
blank: boolean;
modelToken: string | null;
};
}
export const Link = TiptapLink.extend<TiptapLinkOptions>({
addCommands() {
@ -20,25 +20,23 @@ export const Link = TiptapLink.extend<TiptapLinkOptions>({
const { from, to } = state.selection;
// Check if there is a selected link.
let linkFound = false;
let linkFound = false as boolean;
state.doc.nodesBetween(from, to, (node) => {
if (node.marks) {
const found = node.marks.find((m) => m.type.name === this.name);
if (found) linkFound = true;
}
const found: Mark | undefined = node.marks.find(
(m) => m.type.name === this.name,
);
if (found) linkFound = true;
});
if (linkFound) {
return commands.command(({ tr, state: editorState, dispatch }) => {
// Get the existing mark.
let existingMark = null;
let existingMark = null as Mark | 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;
}
const found: Mark | undefined = node.marks.find(
(m) => m.type.name === this.name,
);
if (found) existingMark = found;
});
if (!existingMark) return false;
@ -104,7 +102,7 @@ export const Link = TiptapLink.extend<TiptapLinkOptions>({
modelToken: {
default: null,
parseHTML: (el) => el.getAttribute("data-model") ?? null,
renderHTML: (attrs) =>
renderHTML: (attrs: { modelToken: string }) =>
attrs.modelToken ? { "data-model": attrs.modelToken } : {},
},
};
@ -127,7 +125,7 @@ export const Link = TiptapLink.extend<TiptapLinkOptions>({
"a",
mergeAttributes(
{
"data-model": HTMLAttributes.modelToken,
"data-model": HTMLAttributes.modelToken as string,
},
HTMLAttributes,
),
@ -146,7 +144,7 @@ export const Link = TiptapLink.extend<TiptapLinkOptions>({
const link = target.closest("a");
if (!link) return false;
// Find the exact position of the gat <a>.
// Find the exact position of the tag <a>.
const { state } = view;
const $pos = state.doc.resolve(pos);
@ -164,7 +162,7 @@ export const Link = TiptapLink.extend<TiptapLinkOptions>({
this.editor.emit("open-link-editor", {
href: link.getAttribute("href") ?? "",
blank: link.getAttribute("target") === "_blank",
text: link.textContent ?? "",
text: link.textContent,
modelToken: link.getAttribute("data-model") ?? null,
});

View file

@ -1,33 +1,34 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { Editor } from "@tiptap/react";
import axios, { isAxiosError } from "axios";
import { type Editor } from "@tiptap/react";
import { ExternalLinkIcon, LinkIcon, TrashIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { route } from "ziggy-js";
import { z } from "zod";
// * Components shadcn
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import GoToFrontView from "@/back/Components/GoToFrontView";
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
import { ModelSelect } from "@/back/Components/Inputs/ModelSelect";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import type { ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogDescription,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from "@/components/ui/dialog";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
import { AppEnv, LaravelEnumMap } from "@/types/global";
// Custom type for axios error.
interface AxiosErrorResponse {
errors: Record<string, string>;
}
// Custom type with field entry.
type AddFieldToRecord<T extends Record<string, object>> = {
@ -39,23 +40,23 @@ type AddFieldToRecord<T extends Record<string, object>> = {
};
// LaravelEnum with a specific field.
type LaravelEnumWithField = AddFieldToRecord<LaravelEnumMap>;
type LaravelEnumWithField = AddFieldToRecord<LaravelEnum>;
// Return type of model access response.
type ModelAccessResponse = {
interface ModelAccessResponse {
/** Url to access a specific model. */
url: string;
/** Crypted token for model id and model name. */
token: string;
};
}
// Return type of retrieve from token response.
type RetrieveFromTokenResponse = {
interface RetrieveFromTokenResponse {
/** Name of the selected model. */
modelName: string;
/** Id of the selected model. */
modelId: number;
};
}
// All link types.
const LinkType = {
@ -66,25 +67,28 @@ const LinkType = {
type LinkTypeValue = (typeof LinkType)[keyof typeof LinkType];
// Component props.
type LinkProps = {
interface LinkProps {
/** Wysiwyg editor instance. */
editor: Editor;
/** Disable trigger button. */
disabled: boolean;
};
}
export default function LinkButton({ editor, disabled }: LinkProps) {
// Current domain of the projet.
const { url } = usePage().props.appEnv as AppEnv;
// Backend configuration.
const { routes } = usePage().props.configBackend as ConfigBackend;
// All models from global enum.
const enumModelsList = usePage().props.enumModelsList as LaravelEnumWithField;
const enumModelsList = usePage().props
.enumModelsList as LaravelEnumWithField | null;
// State of the plugin modal.
const [open, setOpen] = useState(false);
const [open, setOpen] = useState<boolean>(false);
// State of editing link.
const [editingLink, setEditingLink] = useState(false);
const [editingLink, setEditingLink] = useState<boolean>(false);
// Hack to actualize states.
const [resetState, setResetState] = useState(1);
const [resetState, setResetState] = useState<number>(1);
// Token of the selected link.
const [modelToken, setModelToken] = useState<string | null>(null);
@ -109,7 +113,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
const [inputBlank, setInputBlank] = useState<boolean>(false);
// State of the loader.
const [loading, setLoading] = useState(false);
const [loading, setLoading] = useState<boolean>(false);
// Value of errors.
const [errors, setErrors] = useState<Record<string, string>>({});
@ -193,8 +197,14 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
routeName: string,
options: object = {},
): Promise<ModelAccessResponse | RetrieveFromTokenResponse> => {
// Get the csrf token value.
const csrfToken =
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") ?? "";
// Base ajax call.
const response = await axios.post(
const response = await window.axios.post(
route(routeName),
options,
// Headers for a good Laravel/Inertia request.
@ -203,10 +213,11 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
"Content-Type": "application/json",
Accept: "application/json",
"X-Inertia": "false",
"X-CSRF-TOKEN": csrfToken,
},
},
);
return response.data;
return response.data as ModelAccessResponse | RetrieveFromTokenResponse;
};
/**
@ -278,6 +289,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
blank: parsed.inputBlank,
modelToken: modelToken ?? null,
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if (selectedType === LinkType.external) {
const parsed = externalLinkSchema.parse({
inputText,
@ -293,7 +305,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
}
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
} catch (err) {
// Get zod error validations.
if (err instanceof z.ZodError) {
@ -325,7 +339,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
const handleDeleteLink = (): void => {
editor.commands.unsetLink();
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
};
/**
@ -352,7 +368,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
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(`${routes.name}wysiwyg.model-access`, {
selectedEntry: value,
modelName: selectedEnum?.name,
})) as ModelAccessResponse;
@ -360,7 +376,10 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
setModelToken(data.token);
} catch (err: unknown) {
console.error(err);
if (isAxiosError(err) && err.response?.data?.errors) {
if (
window.axios.isAxiosError<AxiosErrorResponse>(err) &&
err.response?.data.errors
) {
setErrors((prev) => ({
...prev,
...err.response?.data.errors,
@ -409,7 +428,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
*/
const handleCancelLink = (): void => {
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
};
/**
@ -424,7 +445,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
const handler = async ({
href,
text,
modelToken, // eslint-disable-line no-shadow
modelToken,
blank,
}: {
href: string;
@ -440,7 +461,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
try {
// Retrieve data from decrypted token.
const data = (await fetchOptions(
"back.wysiwyg.retrieve-data-from-token",
`${routes.name}wysiwyg.retrieve-data-from-token`,
{
token: modelToken,
},
@ -464,7 +485,10 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
setModelToken(modelToken);
} catch (err: unknown) {
console.error(err);
if (isAxiosError(err) && err.response?.data?.errors) {
if (
window.axios.isAxiosError<AxiosErrorResponse>(err) &&
err.response?.data.errors
) {
setErrors((prev) => ({
...prev,
...err.response?.data.errors,
@ -502,7 +526,10 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
open={open}
onOpenChange={(status) => {
setOpen(status);
if (!status) setTimeout(() => resetComponent(), animationTime);
if (!status)
setTimeout(() => {
resetComponent();
}, animationTime);
}}
>
{/* Button trigger in wysiwyg navigation. */}
@ -531,7 +558,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
<Button
type="button"
variant="ghost"
onClick={() => setSelectedType(LinkType.external)}
onClick={() => {
setSelectedType(LinkType.external);
}}
className={cn(
"w-1/2",
selectedType === LinkType.external
@ -544,7 +573,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
<Button
type="button"
variant="ghost"
onClick={() => setSelectedType(LinkType.internal)}
onClick={() => {
setSelectedType(LinkType.internal);
}}
className={cn(
"w-1/2",
selectedType === LinkType.internal
@ -574,11 +605,17 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
)}
placeholder="ex: page dynamique"
selected={selectedEnumValue}
options={enumModelsList}
options={enumModelsList ?? undefined}
required
disabled={loading}
setData={() => {}}
onSelectValue={(value) => handleSelectEnum(value)}
setData={(_name: string, _value: number | string | null) =>
undefined
}
onSelectValue={(value) => {
handleSelectEnum(
typeof value === "number" ? value : Number(value),
);
}}
parentErrors={errors}
/>
{/* Selected entry. */}
@ -604,7 +641,7 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
required
disabled={selectedEnumValue === null || loading}
setData={(_, value) =>
handleSelectEntry(
void handleSelectEntry(
Array.isArray(value) ? (value[0] ?? null) : value,
)
}
@ -635,7 +672,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
value={inputUrl}
type="url"
disabled={loading}
setData={(_, value) => handleUpdateUrl(value)}
setData={(_, value) => {
handleUpdateUrl(value);
}}
pattern="https?://.+"
placeholder="ex: https://example.com"
parentErrors={errors}
@ -662,7 +701,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
label={GetTranslation("uwil-backend::back.wysiwyg.link.text")}
value={inputText}
disabled={loading}
setData={(_, value) => handleUpdateText(value)}
setData={(_, value) => {
handleUpdateText(value);
}}
parentErrors={errors}
/>
{/* Boolean input. */}
@ -671,7 +712,9 @@ export default function LinkButton({ editor, disabled }: LinkProps) {
name="link-blank"
checked={inputBlank}
disabled={loading}
setData={(_, value) => handleUpdateBlank(value)}
setData={(_, value) => {
handleUpdateBlank(value);
}}
/>
</div>
</div>

View file

@ -1,10 +1,8 @@
// * Packages
import "@tiptap/core";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
Link: {
// eslint-disable-next-line no-unused-vars
setLink: (attrs: {
href: string;
text: string;

View file

@ -1,4 +1,3 @@
// * Packages
import "@tiptap/core";
declare module "@tiptap/core" {

View file

@ -1,8 +1,10 @@
// * Packages
import { useState } from "react";
import { Editor } from "@tiptap/react";
import { type Editor } from "@tiptap/react";
import { ReplaceIcon } from "lucide-react";
// * Components shadcn
import { useState } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
@ -12,13 +14,9 @@ import {
DialogTrigger,
DialogFooter,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
// * Other
import SimpleString from "@/back/Components/Inputs/SimpleString";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
export default function FindReplaceButton({ editor }: { editor: Editor }) {
const [open, setOpen] = useState(false);
@ -46,9 +44,11 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
* @param status boolean
* @return void
*/
const closeModal = (status: boolean = false): void => {
const closeModal = (status = false): void => {
setOpen(status);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
};
/**
@ -57,7 +57,7 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
* @return void
*/
const handleReplaceAll = (): void => {
if (!editor || !searchText) return;
if (!searchText) return;
// Get all editor content.
const html = editor.getHTML();
@ -76,7 +76,12 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
};
return (
<Dialog open={open} onOpenChange={(status) => closeModal(status)}>
<Dialog
open={open}
onOpenChange={(status) => {
closeModal(status);
}}
>
<DialogTrigger asChild>
<BtnOptionnalLinkWithTooltip
content={<ReplaceIcon className="w-4 h-4 m-auto" />}
@ -106,7 +111,9 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
placeholder="ex: John Doe"
required
value={searchText}
setData={(_, value) => setSearchText(value)}
setData={(_, value) => {
setSearchText(value);
}}
/>
<SimpleString
name="value"
@ -114,13 +121,17 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
placeholder="ex: John Doe"
required
value={replaceText}
setData={(_, value) => setReplaceText(value)}
setData={(_, value) => {
setReplaceText(value);
}}
/>
<div className="flex items-center gap-2 pb-1">
<Checkbox
id="match-case"
checked={matchCase}
onCheckedChange={(val) => setMatchCase(Boolean(val))}
onCheckedChange={(val) => {
setMatchCase(Boolean(val));
}}
/>
<Label htmlFor="match-case">
{useTrans("uwil-backend::back.wysiwyg.replace.match_case")}
@ -136,7 +147,9 @@ export default function FindReplaceButton({ editor }: { editor: Editor }) {
)
.ucFirst()
.value()}
onClick={() => closeModal()}
onClick={() => {
closeModal();
}}
type="button"
variant="secondary"
size="default"

View file

@ -1,4 +1,3 @@
// * Packages
import { Extension } from "@tiptap/core";
import { Plugin } from "prosemirror-state";

View file

@ -1,8 +1,9 @@
// * Packages
import { useEffect, useState } from "react";
import { Editor } from "@tiptap/react";
import { type Editor } from "@tiptap/react";
import { TableIcon } from "lucide-react";
// * Components shadcn
import { useEffect, useState } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
@ -13,30 +14,25 @@ import {
DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
const BASE = 5;
const MAX = 12;
type TableProps = {
interface TableProps {
editor: Editor;
disabled: boolean;
};
}
export default function TableButton({ editor, disabled }: TableProps) {
const [rows, setRows] = useState(3);
const [cols, setCols] = useState(3);
const [hover, setHover] = useState<{
row: number;
column: number;
} | null>(null);
const [header, setHeader] = useState(true);
const [open, setOpen] = useState(false);
const [rows, setRows] = useState<number>(3);
const [cols, setCols] = useState<number>(3);
const [header, setHeader] = useState<boolean>(true);
const [open, setOpen] = useState<boolean>(false);
const hover = { row: rows, column: cols };
// Duration of modal closing animation.
const animationTime = 200;
@ -48,15 +44,12 @@ export default function TableButton({ editor, disabled }: TableProps) {
BASE,
rows + 1,
cols + 1,
hover?.row ? hover.row + 1 : 0,
hover?.column ? hover.column + 1 : 0,
hover.row ? hover.row + 1 : 0,
hover.column ? hover.column + 1 : 0,
),
);
const insert = (
expectedRows: number | undefined = undefined,
expectedCols: number | undefined = undefined,
): void => {
const insert = (expectedRows?: number, expectedCols?: number): void => {
if (!editor.can().insertTable()) return;
// Insert the expected table in the editor.
@ -82,7 +75,6 @@ export default function TableButton({ editor, disabled }: TableProps) {
const resetComponent = (): void => {
setRows(3);
setCols(3);
setHover({ row: 3, column: 3 });
setHeader(true);
};
@ -93,7 +85,9 @@ export default function TableButton({ editor, disabled }: TableProps) {
*/
const closeModal = (): void => {
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
setTimeout(() => {
resetComponent();
}, animationTime);
};
/**
@ -106,17 +100,12 @@ export default function TableButton({ editor, disabled }: TableProps) {
closeModal();
};
// Set size of the current table on hover.
useEffect(() => {
setHover({ row: rows, column: cols });
}, [rows, cols]);
// Press the key event to use the arrow keys to set the table size.
useEffect(() => {
if (!open) return undefined;
const onKeyDown = (event: KeyboardEvent) => {
const active = document.activeElement as HTMLInputElement;
const active = document.activeElement as HTMLInputElement | null;
// Check if the focus is on inputs to get the basic behavior.
if (active?.tagName === "INPUT" && active.type === "number") {
@ -171,7 +160,9 @@ export default function TableButton({ editor, disabled }: TableProps) {
// Redefine the keydown event due to table resize.
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
@ -180,7 +171,10 @@ export default function TableButton({ editor, disabled }: TableProps) {
open={open}
onOpenChange={(status) => {
setOpen(status);
if (!status) setTimeout(() => resetComponent(), animationTime);
if (!status)
setTimeout(() => {
resetComponent();
}, animationTime);
}}
>
<DialogTrigger asChild>
@ -215,7 +209,9 @@ export default function TableButton({ editor, disabled }: TableProps) {
min={1}
max={MAX}
value={rows}
onChange={(event) => setRows(Number(event.target.value) || 1)}
onChange={(event) => {
setRows(Number(event.target.value) || 1);
}}
/>
</div>
<div className="flex-1">
@ -228,14 +224,18 @@ export default function TableButton({ editor, disabled }: TableProps) {
min={1}
max={MAX}
value={cols}
onChange={(event) => setCols(Number(event.target.value) || 1)}
onChange={(event) => {
setCols(Number(event.target.value) || 1);
}}
/>
</div>
<div className="flex-1 flex justify-center items-center gap-1.5">
<Checkbox
id="header-input"
checked={header}
onCheckedChange={(event) => setHeader(Boolean(event))}
onCheckedChange={(event) => {
setHeader(Boolean(event));
}}
/>
<Label htmlFor="header-input">
{useTrans("uwil-backend::back.wysiwyg.table.show_header")}
@ -255,27 +255,27 @@ export default function TableButton({ editor, disabled }: TableProps) {
<div
className="grid gap-1"
style={{
gridTemplateColumns: `repeat(${gridSize}, 1fr)`,
gridTemplateColumns: `repeat(${String(gridSize)}, 1fr)`,
}}
>
{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;
const active = row <= hover.row && column <= hover.column;
return (
<button
key={`${row}-${column}`}
key={`${String(row)}-${String(column)}`}
type="button"
aria-label={`${row} x ${column}`}
aria-label={`${String(row)} x ${String(column)}`}
onMouseEnter={() => {
setHover({ row, column });
setRows(row);
setCols(column);
}}
onClick={() => insert(row, column)}
onClick={() => {
insert(row, column);
}}
className={[
"aspect-square border cursor-pointer",
active ? "bg-primary/30 border-primary" : "bg-muted",

View file

@ -1,4 +1,3 @@
// * Packages
import { usePage } from "@inertiajs/react";
import InvisibleCharacters from "@tiptap/extension-invisible-characters";
import { TaskItem } from "@tiptap/extension-list/task-item";
@ -13,20 +12,19 @@ import TableRow from "@tiptap/extension-table-row";
import TextAlign from "@tiptap/extension-text-align";
import { Editor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { ReactNode, useEffect, useMemo, useState } from "react";
// * Components shadcn
import { Label } from "@/components/ui/label";
// * Other
import { type ReactNode, useEffect, useMemo, useState } from "react";
import InputError from "@/back/Components/InputError";
import Image from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/Image";
import { Link } from "@/back/Components/Inputs/Wysiwyg/Extensions/Link/Link";
import ShortcutBoundary from "@/back/Components/Inputs/Wysiwyg/Extensions/ShortCuts/ShortcutBoundary";
import Toolbar from "@/back/Components/Inputs/Wysiwyg/Toolbar";
import WordCounter from "@/back/Components/WordCounter";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
import type { ConfigBackend } from "@/back/types/global";
import { Label } from "@/components/ui/label";
import { cn, GetTranslation } from "@/lib/utils";
type SimpleWysiwygProps = {
interface SimpleWysiwygProps {
className?: string;
name: string;
tableName: string;
@ -38,13 +36,12 @@ type SimpleWysiwygProps = {
required?: boolean;
disabled?: boolean;
parentErrors?: Record<string, string> | null;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
}
export default function SimpleWysiwyg({
className,
value = undefined,
value,
tableName,
name,
label,
@ -55,13 +52,13 @@ export default function SimpleWysiwyg({
disabled = false,
parentErrors = null,
setData,
}: Readonly<SimpleWysiwygProps>) {
}: SimpleWysiwygProps) {
const routeName = (usePage().props.configBackend as ConfigBackend).routes
.name;
const { errors } = usePage().props;
const localErrors = parentErrors ?? errors;
const [editor, setEditor] = useState<Editor | null>(null);
const [content, setContent] = useState(value);
const transPlaceholder = useTrans(placeholder);
/**
* Remove html tags from content string.
@ -108,7 +105,7 @@ export default function SimpleWysiwyg({
TableHeader,
TableCell,
Placeholder.configure({
placeholder: transPlaceholder,
placeholder: GetTranslation(placeholder),
}),
TextAlign.configure({
types: ["heading", "paragraph"],
@ -122,24 +119,29 @@ export default function SimpleWysiwyg({
Link,
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[transPlaceholder],
[],
);
const [editor] = useState<Editor | null>(
() =>
new Editor({
content: value ?? undefined,
extensions,
editable: !disabled,
editorProps: {
attributes: { id, required: String(required), tableName },
},
onUpdate: ({ editor: currentEditor }) => {
onChangeContent(currentEditor.getHTML());
},
}),
);
// Init editor only once.
useEffect(() => {
const e = new Editor({
content: value || undefined,
extensions,
editable: !disabled,
editorProps: {
attributes: { id, required: String(required), tableName },
},
onUpdate: ({ editor: currentEditor }) =>
onChangeContent(currentEditor.getHTML()),
});
setEditor(e);
return () => e.destroy();
return () => {
editor?.destroy();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@ -173,7 +175,7 @@ export default function SimpleWysiwyg({
"border-destructive/50": localErrors[name],
})}
>
<Toolbar editor={editor} />
<Toolbar editor={editor} routeName={routeName} />
<EditorContent
id={id}
editor={editor}

View file

@ -1,6 +1,4 @@
// * Packages
import { Editor } from "@tiptap/react";
import { ElementType, useEffect, useState } from "react";
import { type Editor } from "@tiptap/react";
import {
AlignCenterIcon,
AlignJustifyIcon,
@ -25,13 +23,13 @@ import {
UnderlineIcon,
UndoIcon,
} from "lucide-react";
// * Components shadcn
import { Separator } from "@/components/ui/separator";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { type ElementType, useEffect, useState } from "react";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import ImageButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton";
import LinkButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton";
import FindReplaceButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Replace/FindReplaceButton";
import TableButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Table/TableButton";
import {
Select,
SelectContent,
@ -39,12 +37,12 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
// * Other
import ImageButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Image/ImageButton";
import LinkButton from "@/back/Components/Inputs/Wysiwyg/Extensions/Link/LinkButton";
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 { Separator } from "@/components/ui/separator";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import str from "@/hooks/use-string";
import { cn, GetTranslation } from "@/lib/utils";
@ -52,14 +50,17 @@ type AllowedHeadings = 1 | 2 | 3 | 4 | 5 | 6;
type AllowedAlignements = "left" | "center" | "right" | "justify";
type ToolbarProps = {
interface ToolbarProps {
editor: Editor;
};
routeName: string;
}
export default function Toolbar({ editor }: ToolbarProps) {
const [, forceUpdate] = useState<number>(0);
export default function Toolbar({ editor, routeName }: ToolbarProps) {
const [_forceUpdate, setForceUpdate] = useState<number>(0);
const [docSelected, setDocSelected] = useState<boolean>(false);
const [headerHeight, setHeaderHeight] = useState<number>(0);
const [headerHeight, setHeaderHeight] = useState(
() => document.querySelector("header")?.clientHeight ?? 0,
);
const headingLevels: AllowedHeadings[] = [1, 2, 3, 4, 5, 6];
const currentHeadingLevel =
@ -107,9 +108,9 @@ export default function Toolbar({ editor }: ToolbarProps) {
// Force re-render editor on select to update activated extensions.
useEffect(() => {
if (!editor) return undefined;
const update = () => forceUpdate((value) => value + 1);
const update = () => {
setForceUpdate((value) => value + 1);
};
editor.on("selectionUpdate", () => {
update();
@ -126,11 +127,10 @@ export default function Toolbar({ editor }: ToolbarProps) {
const handleResize = () => {
setHeaderHeight(document.querySelector("header")?.clientHeight ?? 0);
};
window.addEventListener("resize", handleResize);
handleResize();
return () => window.removeEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return (
@ -168,7 +168,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
variant="ghost"
size="icon"
/>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<BtnOptionnalLinkWithTooltip
content={<BoldIcon className="w-4 h-4 m-auto" />}
tooltipContent={str(GetTranslation("uwil-backend::back.wysiwyg.bold"))
@ -248,10 +248,12 @@ export default function Toolbar({ editor }: ToolbarProps) {
variant="ghost"
size="icon"
/>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<Select
value={currentHeadingLevel.toString()}
onValueChange={(value) => handleHeadingChange(value)}
onValueChange={(value) => {
handleHeadingChange(value);
}}
disabled={docSelected}
>
<Tooltip>
@ -267,7 +269,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
>
<HeadingIcon className="w-4 h-4" />
{currentHeadingLevel && (
<SelectValue>{currentHeadingLevel?.toString()}</SelectValue>
<SelectValue>{currentHeadingLevel.toString()}</SelectValue>
)}
</SelectTrigger>
</TooltipTrigger>
@ -290,7 +292,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
))}
</SelectContent>
</Select>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<BtnOptionnalLinkWithTooltip
content={<ListIcon className="w-4 h-4 m-auto" />}
tooltipContent={str(
@ -342,9 +344,9 @@ export default function Toolbar({ editor }: ToolbarProps) {
variant="ghost"
size="icon"
/>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<Select
value={currentTextAlign.value.toString()}
value={currentTextAlign.value}
onValueChange={(value) => {
const align = value as AllowedAlignements;
editor.chain().focus().setTextAlign(align).run();
@ -371,7 +373,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
</Tooltip>
<SelectContent>
{textAligns.map((align) => (
<SelectItem key={align.value} value={align.value.toString()}>
<SelectItem key={align.value} value={align.value}>
<div className="flex flex-row jsutify-center items-center gap-1.5">
<align.icon className="w-4 h-4" />
{GetTranslation(
@ -382,7 +384,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
))}
</SelectContent>
</Select>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<BtnOptionnalLinkWithTooltip
content={<SubscriptIcon className="w-4 h-4 m-auto" />}
tooltipContent={str(
@ -417,7 +419,7 @@ export default function Toolbar({ editor }: ToolbarProps) {
variant="ghost"
size="icon"
/>
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<BtnOptionnalLinkWithTooltip
content={<MinusIcon className="w-4 h-4 m-auto" />}
tooltipContent={str(
@ -435,9 +437,13 @@ export default function Toolbar({ editor }: ToolbarProps) {
size="icon"
/>
<TableButton editor={editor} disabled={docSelected} />
<ImageButton editor={editor} disabled={docSelected} />
<ImageButton
editor={editor}
routeName={routeName}
disabled={docSelected}
/>
<LinkButton editor={editor} disabled={docSelected} />
<Separator orientation="vertical" className="!h-auto" />
<Separator orientation="vertical" className="h-auto!" />
<BtnOptionnalLinkWithTooltip
content={<PilcrowIcon className="w-4 h-4 m-auto" />}
tooltipContent={str(

View file

@ -1,4 +1,3 @@
// * Packages
import "@tiptap/core";
declare module "@tiptap/core" {

View file

@ -1,22 +1,20 @@
// * Packages
import { Link, usePage } from "@inertiajs/react";
// * Components shadcn
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbList,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
// * Other
import { cn } from "@/lib/utils";
export default function AppBreadcrumbs({ className }: { className: string }) {
const breadcrumbs = usePage().props.breadcrumbs as Array<{
const breadcrumbs = usePage().props.breadcrumbs as {
title: string;
url: string;
}>;
}[];
return (
breadcrumbs && (
breadcrumbs.length && (
<Breadcrumb className={cn("md:border-s md:ms-1 px-4", className)}>
<BreadcrumbList>
{breadcrumbs.map((breadcrumb, breadcrumbIndex) => (
@ -30,7 +28,7 @@ export default function AppBreadcrumbs({ className }: { className: string }) {
breadcrumb.url ? (
<Link
href={breadcrumb.url}
className="rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
className="rounded-md focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{breadcrumb.title}
</Link>

View file

@ -1,18 +1,17 @@
// * Packages
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { Separator } from "@/components/ui/separator";
// * Other
import { AppEnv } from "@/types/global";
import str from "@/hooks/use-string";
const date = new Date();
export default function AppFooter() {
const appName = (usePage().props.appEnv as AppEnv).name;
const year = new Date().getFullYear();
const year = date.getFullYear();
return (
<section className="relative flex flex-col justify-center items-center w-full pt-4 z-2">
<section className="relative flex flex-col justify-center items-center w-full py-4 z-2">
<Separator />
<p className="text-sm pt-4">
<p className="text-sm text-muted-foreground pt-4">
uwil/{str(appName).slug().value()} - UWIL © {year}
</p>
</section>

View file

@ -1,8 +1,11 @@
// * Packages
import { Link, usePage } from "@inertiajs/react";
import { CircleUserRoundIcon, LogOutIcon, UserIcon } from "lucide-react";
import { route } from "ziggy-js";
// * Components shadcn
import CustomSidebarTrigger from "@/back/Components/CustomSidebarTrigger";
import AppBreadcrumbs from "@/back/Components/Layout/AppBreadcrumbs";
import AppSettings from "@/back/Components/Layout/Settings/AppSettings";
import type { AuthProp, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
@ -10,17 +13,11 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
// * Other
import AppBreadcrumbs from "@/back/Components/Layout/AppBreadcrumbs";
import AppSettings from "@/back/Components/Layout/Settings/AppSettings";
import CustomSidebarTrigger from "@/back/Components/CustomSidebarTrigger";
import { Button } from "@/components/ui/button";
import { AuthProp } from "@/back/types/global";
import useTrans from "@/hooks/use-translations";
export default function AppHeader() {
const auth = usePage().props.auth as AuthProp;
const { user } = auth;
const { user } = usePage().props.auth as AuthProp;
const { routes } = usePage().props.configBackend as ConfigBackend;
return (
<header className="sticky top-0 flex flex-col justify-between items-center bg-background border-b z-20">
<div className="sticky top-0 flex flex-row justify-between items-center w-full py-4">
@ -43,7 +40,7 @@ export default function AppHeader() {
<DropdownMenuItem className="p-0">
<Button variant="ghost" asChild>
<Link
href={route("back.users.show", user.id)}
href={route(`${routes.name}users.show`, user.id)}
className="w-full"
>
<UserIcon />
@ -54,7 +51,7 @@ export default function AppHeader() {
<DropdownMenuSeparator />
<DropdownMenuItem className="p-0">
<Button variant="ghost" asChild>
<a href={route("back.logout")} className="w-full">
<a href={route(`${routes.name}logout`)} className="w-full">
<LogOutIcon />
{useTrans("uwil-backend::back.disconnect")}
</a>

View file

@ -1,7 +1,8 @@
// * Packages
import { SettingsIcon } from "lucide-react";
import { usePage } from "@inertiajs/react";
// * Components shadcn
import { SettingsIcon } from "lucide-react";
import SettingRegistry from "@/back/Components/Layout/Settings/SettingRegistry";
import type { ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@ -9,17 +10,17 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
// * Other
import SettingRegistry from "@/back/Components/Layout/Settings/SettingRegistry";
import { cn, GetTranslation } from "@/lib/utils";
import { AppEnv } from "@/types/global";
type AppSettingsProps = {
interface AppSettingsProps {
className?: string;
};
}
export default function AppSettings({ className = "" }: AppSettingsProps) {
const appEnv = usePage().props.appEnv as AppEnv;
const { appEnv, configBackend } = usePage().props as unknown as {
appEnv: AppEnv;
configBackend: ConfigBackend;
};
return (
<div className={cn(className)}>
<DropdownMenu>
@ -32,12 +33,14 @@ export default function AppSettings({ className = "" }: AppSettingsProps) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" className="w-fit me-1">
{SettingRegistry.getAll(appEnv).map((Section, index, arr) => (
<>
{Section}
{Section && index < arr.length - 1 && <DropdownMenuSeparator />}
</>
))}
{SettingRegistry.getAll(appEnv, configBackend).map(
(Section, index, arr) => (
<div key="section">
{Section}
{Section && index < arr.length - 1 && <DropdownMenuSeparator />}
</div>
),
)}
</DropdownMenuContent>
</DropdownMenu>
</div>

View file

@ -1,24 +1,25 @@
// * Packages
import { route } from "ziggy-js";
import { FormEvent } from "react";
import { useForm } from "@inertiajs/react";
// * Components shadcn
import { type SubmitEvent } from "react";
import type { ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import { AppEnv } from "@/types/global";
import useTrans from "@/hooks/use-translations";
import { cn } from "@/lib/utils";
export default function Languages(appEnv: AppEnv) {
export default function Languages(
appEnv: AppEnv,
configBackend: ConfigBackend,
) {
const { locales, locale } = appEnv;
const { routes } = configBackend;
const { post, setData } = useForm({
lang: "system",
});
const transLanguage = useTrans("uwil-i18n::trans.languages");
const submit = (e: FormEvent<HTMLFormElement>) => {
const transLanguage = useTrans("uwil-backend::back.languages");
const submit = (e: SubmitEvent) => {
e.preventDefault();
post(route("back.lang.set"));
post(route(`${routes.name}lang.set`));
};
const languages = [
{
@ -70,7 +71,9 @@ export default function Languages(appEnv: AppEnv) {
<DropdownMenuItem
key={language.name}
className="p-0"
onSelect={(e) => e.preventDefault()}
onSelect={(e) => {
e.preventDefault();
}}
>
<Button
className={cn("w-full", {

View file

@ -1,11 +1,9 @@
// * Packages
import { MoonIcon, SunIcon } from "lucide-react";
// * Components shadcn
import { useTheme } from "@/back/providers/ThemeProvider";
import type { Theme } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import { Theme } from "@/back/types/global";
import { useTheme } from "@/back/providers/ThemeProvider";
import useTrans from "@/hooks/use-translations";
import { cn, GetTranslation } from "@/lib/utils";
@ -36,14 +34,18 @@ export default function Themes() {
<DropdownMenuItem
key={mod.name}
className="p-0"
onSelect={(e) => e.preventDefault()}
onSelect={(e) => {
e.preventDefault();
}}
>
<Button
className={cn("w-full", {
"bg-secondary": theme === mod.theme,
})}
variant="ghost"
onClick={() => setTheme(mod.theme as Theme)}
onClick={() => {
setTheme(mod.theme as Theme);
}}
>
<mod.icon />
{GetTranslation(mod.name)}

View file

@ -1,37 +1,35 @@
// * Packages
import { ReactNode } from "react";
// * Other
import { AppEnv } from "@/types/global";
import { type ReactNode } from "react";
// eslint-disable-next-line no-unused-vars
type SettingResolver = (appEnv: AppEnv) => ReactNode;
import type { ConfigBackend } from "@/back/types/global";
export default class SettingRegistry {
private static resolvers: SettingResolver[] = [];
type SettingResolver = (
appEnv: AppEnv,
configBackend: ConfigBackend,
) => ReactNode;
static add(resolver: SettingResolver) {
this.resolvers.push(resolver);
}
const resolvers: SettingResolver[] = [];
static getAll(appEnv: AppEnv): ReactNode[] {
return this.resolvers.map((resolver) => resolver(appEnv));
}
}
const SettingRegistry = {
add(resolver: SettingResolver) {
resolvers.push(resolver);
},
getAll(appEnv: AppEnv, configBackend: ConfigBackend): ReactNode[] {
return resolvers.map((resolver) => resolver(appEnv, configBackend));
},
};
// Add all sections presents in files to the registry.
// @ts-expect-error Glob error.
const modules = import.meta.glob("./Sections/*.tsx", {
eager: true,
}) as Record<
string,
const modules = import.meta.glob<{ default: SettingResolver }>(
"./Sections/*.tsx",
{
// eslint-disable-next-line no-unused-vars
default: (appEnv: AppEnv) => ReactNode;
}
>;
eager: true,
},
);
Object.entries(modules)
.sort(([pathA], [pathB]) => pathA.localeCompare(pathB))
.forEach(([, module]) => {
SettingRegistry.add(module.default);
});
export default SettingRegistry;

View file

@ -1,20 +1,22 @@
// * Packages
import { Link, usePage } from "@inertiajs/react";
import {
ChevronDownIcon,
HomeIcon,
MoreHorizontalIcon,
HomeIcon,
SquareArrowOutUpRightIcon,
TelescopeIcon,
} from "lucide-react";
import { ElementType, ReactNode, useEffect, useRef } from "react";
import { route } from "ziggy-js";
// * Components shadcn
import { type ElementType, type ReactNode, useEffect, useRef } from "react";
import ApplicationLogo from "@/back/Components/ApplicationLogo";
import { SidebarRegistry } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import type { AuthProp, UserModel, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
CollapsibleContent,
} from "@/components/ui/collapsible";
import {
DropdownMenu,
@ -24,15 +26,15 @@ import {
} from "@/components/ui/dropdown-menu";
import {
Sidebar,
SidebarHeader,
SidebarContent,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuAction,
useSidebar,
} from "@/components/ui/sidebar";
import {
@ -40,19 +42,11 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
// * Other
import ApplicationLogo from "@/back/Components/ApplicationLogo";
import { SidebarRegistry } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import { AuthProp } from "@/back/types/global";
import usePermissions from "@/hooks/use-permissions";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { GetTranslation } from "@/lib/utils";
import container from "@/services/container";
import { AppEnv, LaravelEnumMap } from "@/types/global";
export type NavListLinksProps = {
export interface NavListLinksProps {
/** Title of the button. */
title: string;
/** Main model of the button (used for route checking). */
@ -66,18 +60,17 @@ export type NavListLinksProps = {
/** Lucide icon of the button. */
icon: ElementType;
/** Define some actions in side popover (like create/trash). */
// eslint-disable-next-line no-unused-vars
actions?: (model: string) => ReactNode;
};
}
export type NavListProps = Array<{
export type NavListProps = {
/** Title of the group. */
title: string;
/** Condition to set the visibility of the group. */
show: boolean;
/** Links presents in the group. */
links: Array<NavListLinksProps>;
}>;
links: NavListLinksProps[];
}[];
/**
* Get sidenav actions.
@ -87,9 +80,13 @@ export type NavListProps = Array<{
* @return
*/
export const filterActions = ({
auth,
configBackend,
items,
model,
}: {
auth: AuthProp;
configBackend: ConfigBackend;
items?: ReactNode[];
model?: string;
}): ReactNode => {
@ -101,18 +98,15 @@ export const filterActions = ({
.value();
// Set create action by default.
if (!computedItems && model) {
const authService = container.resolve("authService");
// Default FQCN heuristic: App\Models\Model (can be overridden if passed specifically)
const modelFQCN = String.raw`App\Models\\${str(model).singular().pascalCase().value()}`;
const canCreate = authService.can("create", modelFQCN);
const modelCamelCase = str(model).camelCase().value();
computedItems = [
canCreate && (
auth.policies[modelCamelCase].create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Link
href={route(`${configBackend.routes.name}${model}.create`)}
className="w-full"
>
<Views.CREATION.icon />
{transDefaultSideAction}
</Link>
@ -126,16 +120,16 @@ export const filterActions = ({
};
export default function AppSidebar() {
const { appEnv, auth, enumUserRole } = usePage().props as unknown as {
const { appEnv, auth, configBackend, enumUserRole } = usePage()
.props as unknown as {
appEnv: AppEnv;
auth: AuthProp;
enumUserRole: LaravelEnumMap;
configBackend: ConfigBackend;
enumUserRole: UserModel["role"][];
};
usePermissions();
const { state } = useSidebar();
const prevStateRef = useRef(state);
const isConceptor = enumUserRole.find((role) => role.name === "conceptor");
const isCollapsed = state === "collapsed";
// Translations.
@ -163,19 +157,19 @@ export default function AppSidebar() {
show: true,
icon: SquareArrowOutUpRightIcon,
},
...SidebarRegistry.getAll("pages"),
...SidebarRegistry.getAll(auth, configBackend, "pages"),
],
},
{
title: transModules,
show: SidebarRegistry.getAll("modules").length > 0,
links: SidebarRegistry.getAll("modules"),
show: SidebarRegistry.getAll(auth, configBackend, "modules").length > 0,
links: SidebarRegistry.getAll(auth, configBackend, "modules"),
},
{
title: str(transAdmin).plural().value(),
show: auth.user.role === enumUserRole.conceptor.value,
show: auth.user.role.value === isConceptor?.value,
links: [
...SidebarRegistry.getAll("admin"),
...SidebarRegistry.getAll(auth, configBackend, "admin"),
{
title: transTelescope,
link: route().has("telescope") ? route("telescope") : undefined,
@ -189,13 +183,22 @@ export default function AppSidebar() {
useEffect(() => {
if (prevStateRef.current !== state) {
const elmts = document.querySelectorAll(".sidebar-transition");
const timeoutIds: NodeJS.Timeout[] = [];
elmts.forEach((element) => {
element.classList.add("animation-transition");
setTimeout(() => {
const id = setTimeout(() => {
element.classList.remove("animation-transition");
}, 400);
timeoutIds.push(id);
});
prevStateRef.current = state;
return () => {
timeoutIds.forEach((id) => {
clearTimeout(id);
});
};
}
}, [state]);
@ -230,9 +233,11 @@ export default function AppSidebar() {
{navGroup.links
.filter((navLink) => navLink.show)
.map((navLink) => {
const isActive =
route().current(`back.${navLink.model}.*`) ||
navLink.activeCondition?.some(Boolean);
const isActive = navLink.model
? route().current(
`${configBackend.routes.name}${navLink.model}.*`,
)
: navLink.activeCondition?.some(Boolean);
const sidebarButton = (
<SidebarMenuButton
className={
@ -246,14 +251,20 @@ export default function AppSidebar() {
<a
href={navLink.link}
target="_blank"
rel="noopener noreferrer"
rel="noreferrer"
>
<navLink.icon />
{navLink.title}
</a>
) : (
<Link
href={route(`back.${navLink.model}.index`)}
href={
navLink.model
? route(
`${configBackend.routes.name}${navLink.model}.index`,
)
: "#"
}
className="bg-transparent"
>
<navLink.icon />
@ -265,7 +276,7 @@ export default function AppSidebar() {
return (
<SidebarMenuItem
key={navLink.title}
className={`transition-colors rounded-md ${isActive ? "bg-secondary text-secondary-foreground" : "bg-opacity-0"}`}
className={`transition-colors rounded-md ${isActive ? "bg-secondary text-secondary-foreground" : "bg-secondary/0"}`}
>
{isCollapsed ? (
<Tooltip>
@ -284,7 +295,7 @@ export default function AppSidebar() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
className={`${isActive ? "text-secondary-foreground" : ""} !top-0 !right-0 px-4 h-full`}
className={`${isActive ? "text-secondary-foreground" : ""} top-0! right-0! cursor-pointer px-4 h-full`}
>
<MoreHorizontalIcon />
</SidebarMenuAction>

View file

@ -1,19 +1,15 @@
// * Packages
import { HistoryIcon } from "lucide-react";
// * Other
import { NavListLinksProps } from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { type NavListLinksProps } from "@/back/Components/Layout/Sidebar/AppSidebar";
import { type SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import type { AuthProp } from "@/back/types/global";
import str from "@/hooks/use-string";
import { GetTranslation } from "@/lib/utils";
import container from "@/services/container";
export default function ActivityLogs(): SidebarGroupLink {
const authService = container.resolve("authService");
export default function ActivityLogs(auth: AuthProp): SidebarGroupLink {
const modelName = "activity-logs";
const transActivityLogs = GetTranslation(
`uwil-activity-logs::models.classes.${modelName}`,
`uwil-backend::models.classes.${modelName}`,
{
choice: 2,
},
@ -23,10 +19,7 @@ export default function ActivityLogs(): SidebarGroupLink {
title: str(transActivityLogs).ucFirst().value(),
model: modelName,
icon: HistoryIcon,
show: authService.canGlobal(
"viewAny",
String.raw`Uwil\LaravelActivityLogs\Models\ActivityLog`,
),
show: auth.policies.activityLogs.viewAny,
};
return { link, group: "admin" };

View file

@ -1,26 +1,23 @@
// * Packages
import { Link } from "@inertiajs/react";
import { StickyNoteIcon } from "lucide-react";
import { route } from "ziggy-js";
// * Components shadcn
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import {
filterActions,
NavListLinksProps,
type NavListLinksProps,
} from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { type SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import type { AuthProp, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { GetTranslation } from "@/lib/utils";
import container from "@/services/container";
export default function DynamicPages(): SidebarGroupLink {
const authService = container.resolve("authService");
export default function DynamicPages(
auth: AuthProp,
configBackend: ConfigBackend,
): SidebarGroupLink {
const modelName = "dynamic-pages";
// Translations.
@ -43,36 +40,35 @@ export default function DynamicPages(): SidebarGroupLink {
title: str(transDynamicPages).ucFirst().value(),
model: modelName,
icon: StickyNoteIcon,
show: authService.canGlobal(
"viewAny",
String.raw`Uwil\LaravelDynamicPages\Models\DynamicPage`,
),
show: auth.policies.dynamicPages.viewAny,
actions: (model: string) =>
filterActions({
auth,
configBackend,
model,
items: [
authService.canGlobal(
"create",
String.raw`Uwil\LaravelDynamicPages\Models\DynamicPage`,
) && (
auth.policies.dynamicPages.create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Link
href={route(`${configBackend.routes.name}${model}.create`)}
className="w-full"
>
{}
<Views.CREATION.icon />
{transCreate}
</Link>
</Button>
</DropdownMenuItem>
),
authService.canGlobal(
"viewTrash",
String.raw`Uwil\LaravelDynamicPages\Models\DynamicPage`,
) && (
<DropdownMenuItem className="p-0">
auth.policies.dynamicPages.viewTrash && (
<DropdownMenuItem key="trash" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.trash`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Link
href={route(`${configBackend.routes.name}${model}.trash`)}
className="w-full"
>
{}
<Views.ARCHIVATION.icon />
{transArchives}
</Link>

View file

@ -1,26 +1,23 @@
// * Packages
import { Link } from "@inertiajs/react";
import { CogIcon } from "lucide-react";
import { route } from "ziggy-js";
// * Components shadcn
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import {
filterActions,
NavListLinksProps,
type NavListLinksProps,
} from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { type SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import type { AuthProp, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { GetTranslation } from "@/lib/utils";
import container from "@/services/container";
export default function PageConfigs(): SidebarGroupLink {
const authService = container.resolve("authService");
export default function PageConfigs(
auth: AuthProp,
configBackend: ConfigBackend,
): SidebarGroupLink {
const modelName = "page-configs";
// Translations.
@ -43,36 +40,35 @@ export default function PageConfigs(): SidebarGroupLink {
title: str(transPageConfigs).ucFirst().value(),
model: modelName,
icon: CogIcon,
show: authService.canGlobal(
"viewAny",
String.raw`Uwil\LaravelDynamicPages\Models\PageConfig`,
),
show: auth.policies.pageConfigs.viewAny,
actions: (model: string) =>
filterActions({
auth,
configBackend,
model,
items: [
authService.canGlobal(
"create",
String.raw`Uwil\LaravelDynamicPages\Models\PageConfig`,
) && (
auth.policies.pageConfigs.create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Link
href={route(`${configBackend.routes.name}${model}.create`)}
className="w-full"
>
{}
<Views.CREATION.icon />
{transCreate}
</Link>
</Button>
</DropdownMenuItem>
),
authService.canGlobal(
"viewTrash",
String.raw`Uwil\LaravelDynamicPages\Models\PageConfig`,
) && (
<DropdownMenuItem className="p-0">
auth.policies.pageConfigs.viewTrash && (
<DropdownMenuItem key="trash" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.trash`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Link
href={route(`${configBackend.routes.name}${model}.trash`)}
className="w-full"
>
{}
<Views.ARCHIVATION.icon />
{transArchives}
</Link>

View file

@ -1,25 +1,22 @@
// * Packages
import { Link } from "@inertiajs/react";
import { EggIcon } from "lucide-react";
import { route } from "ziggy-js";
// * Components shadcn
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import {
filterActions,
NavListLinksProps,
type NavListLinksProps,
} from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { type SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import type { AuthProp, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import container from "@/services/container";
export default function Products(): SidebarGroupLink {
const authService = container.resolve("authService");
export default function Products(
auth: AuthProp,
configBackend: ConfigBackend,
): SidebarGroupLink {
const modelName = "products";
// Translations.
@ -34,36 +31,39 @@ export default function Products(): SidebarGroupLink {
const transArchives = str(useTrans("uwil-backend::back.archives"))
.ucFirst()
.value();
const CreationIcon = Views.CREATION.icon;
const ArchivationIcon = Views.ARCHIVATION.icon;
const link: NavListLinksProps = {
title: str(transProducts).ucFirst().value(),
model: modelName,
icon: EggIcon,
show: authService.canGlobal("viewAny", String.raw`App\Models\Product`),
show: auth.policies.products?.viewAny ?? false,
actions: (model: string) =>
filterActions({
auth,
configBackend,
model,
items: [
authService.canGlobal("create", String.raw`App\Models\Product`) && (
auth.policies.products?.create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
<CreationIcon />
<Link
href={route(`${configBackend.routes.name}${model}.create`)}
className="w-full"
>
<Views.CREATION.icon />
{transCreate}
</Link>
</Button>
</DropdownMenuItem>
),
authService.canGlobal(
"viewTrash",
String.raw`App\Models\Product`,
) && (
auth.policies.products?.viewTrash && (
<DropdownMenuItem key="archives" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.trash`)} className="w-full">
<ArchivationIcon />
<Link
href={route(`${configBackend.routes.name}${model}.trash`)}
className="w-full"
>
<Views.ARCHIVATION.icon />
{transArchives}
</Link>
</Button>

View file

@ -1,25 +1,22 @@
// * Packages
import { Link } from "@inertiajs/react";
import { CookingPotIcon } from "lucide-react";
import { route } from "ziggy-js";
// * Components shadcn
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
// * Other
import {
filterActions,
NavListLinksProps,
type NavListLinksProps,
} from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { type SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import Views from "@/back/lib/actions";
import type { AuthProp, ConfigBackend } from "@/back/types/global";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import container from "@/services/container";
export default function Recipes(): SidebarGroupLink {
const authService = container.resolve("authService");
export default function Recipes(
auth: AuthProp,
configBackend: ConfigBackend,
): SidebarGroupLink {
const modelName = "recipes";
// Translations.
@ -32,33 +29,39 @@ export default function Recipes(): SidebarGroupLink {
const transArchives = str(useTrans("uwil-backend::back.archives"))
.ucFirst()
.value();
const CreationIcon = Views.CREATION.icon;
const ArchivationIcon = Views.ARCHIVATION.icon;
const link: NavListLinksProps = {
title: str(transRecipes).ucFirst().value(),
model: modelName,
icon: CookingPotIcon,
show: authService.canGlobal("viewAny", String.raw`App\Models\Recipe`),
show: auth.policies.recipes?.viewAny ?? false,
actions: (model: string) =>
filterActions({
auth,
configBackend,
model,
items: [
authService.canGlobal("create", String.raw`App\Models\Recipe`) && (
auth.policies.recipes?.create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
<CreationIcon />
<Link
href={route(`${configBackend.routes.name}${model}.create`)}
className="w-full"
>
<Views.CREATION.icon />
{transCreate}
</Link>
</Button>
</DropdownMenuItem>
),
authService.canGlobal("viewTrash", String.raw`App\Models\Recipe`) && (
auth.policies.recipes?.viewTrash && (
<DropdownMenuItem key="archives" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.trash`)} className="w-full">
<ArchivationIcon />
<Link
href={route(`${configBackend.routes.name}${model}.trash`)}
className="w-full"
>
<Views.ARCHIVATION.icon />
{transArchives}
</Link>
</Button>

Some files were not shown because too many files have changed in this diff Show more