feat: ✨ add news job to publish models on range dates

This commit is contained in:
Alexis Gousseau 2025-11-12 15:57:33 +01:00
parent 3875f06ec9
commit 682e77f309
27 changed files with 441 additions and 266 deletions

View file

@ -3,6 +3,7 @@
namespace App\Console;
use App\Jobs\CleanTrashModels;
use App\Jobs\NewsStatusUpdate;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
@ -17,5 +18,6 @@ class Kernel extends ConsoleKernel
protected function schedule(Schedule $schedule): void
{
$schedule->job(CleanTrashModels::class)->daily();
$schedule->job(NewsStatusUpdate::class)->everyMinute();
}
}

View file

@ -17,7 +17,7 @@ enum NewsStatusEnum: int
* @phpstan-ignore-next-line
*/
private const LABELS = [
self::unpublished->name => 'enums.news-status.unpublished',
self::published->name => 'enums.news-status.published',
self::unpublished->name => 'enums.news-status.unpublished',
self::published->name => 'enums.news-status.published',
];
}

View file

@ -39,19 +39,19 @@ class StoreNewsRequest extends FormRequest
public function rules(): array
{
return [
'titleSeo' => 'nullable|string|max:60',
'descriptionSeo' => 'nullable|string|max:255',
'title' => 'required|string|max:255',
'slug' => 'required|string|max:255',
'content' => 'required|string',
'status' => ['required', new Enum(NewsStatusEnum::class)],
'picture' => $this->pictureRules("nullable|file|mimes:jpg,jpeg,png|max:5120|dimensions:width=525,height=295"),
'picture_alt' => 'nullable|string|max:60',
'picture_title' => 'nullable|string|max:60',
'categories' => 'nullable|array',
'categories.*' => ['integer', new Enum(NewsCategoryEnum::class)],
'published_at' => 'nullable|date',
'unpublished_at' => 'nullable|date|after:published_at',
'seo_title' => 'required|string|between:3,255',
'seo_description' => 'required|string|between:3,255',
'title' => 'required|string|between:3,255',
'slug' => 'required|string|between:3,255',
'picture' => $this->pictureRules("nullable|file|mimes:jpg,jpeg,png|max:5120|dimensions:width=525,height=295"),
'picture_alt' => 'nullable|string|between:3,60',
'picture_title' => 'nullable|string|between:3,60',
'content' => 'required|string',
'status' => ['required', new Enum(NewsStatusEnum::class)],
'categories' => 'nullable|array',
'categories.*' => ['integer', new Enum(NewsCategoryEnum::class)],
'published_at' => 'nullable|date',
'unpublished_at' => 'nullable|date|after:published_at',
];
}
@ -63,18 +63,18 @@ class StoreNewsRequest extends FormRequest
public function attributes(): array
{
return [
'title' => trans('validation.attributes.title'),
'slug' => trans('validation.custom.slug'),
'status' => trans('validation.custom.status'),
'titleSeo' => trans('validation.custom.titleSeo'),
'descriptionSeo' => trans('validation.custom.descriptionSeo'),
'categories' => trans('validation.custom.categories'),
'content' => trans('validation.attributes.content'),
'picture' => trans('validation.attributes.image'),
'picture_alt' => trans('validation.custom.attribute_alt'),
'picture_title' => trans('validation.custom.attribute_title'),
'published_at' => trans('validation.custom.published_at'),
'unpublished_at' => trans('validation.custom.unpublished_at'),
'seo_title' => trans('validation.custom.seo.title'),
'seo_description' => trans('validation.custom.seo.description'),
'title' => trans('validation.attributes.title'),
'slug' => trans('validation.custom.slug'),
'categories' => trans('validation.custom.categories'),
'picture' => trans('validation.attributes.image'),
'picture_alt' => trans('validation.custom.image_alt'),
'picture_title' => trans('validation.custom.image_title'),
'status' => trans('validation.custom.status'),
'content' => trans('validation.attributes.content'),
'published_at' => trans('validation.custom.published_at'),
'unpublished_at' => trans('validation.custom.unpublished_at'),
];
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace App\Jobs;
use App\Enums\News\NewsStatusEnum;
use App\Models\News;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
/**
* Update status attribute reading its
* published_at and unpublished_at attributes.
*/
class NewsStatusUpdate
{
/**
* Called when the job will be executed.
*
* @return void
*/
public function handle(): void
{
// Publish all unpublish models if the published_at date has passed.
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\News> */
$newsListToPublish = News::query()
->where('published_at', '<=', Carbon::now())
->whereNotNull('published_at')
->where('status', NewsStatusEnum::unpublished)
->get();
Log::debug(__CLASS__ . " news to publish " . $newsListToPublish->count());
foreach ($newsListToPublish as $news) {
$news->status = NewsStatusEnum::published;
$news->saveQuietly();
}
// Unpublish all publish models if the unpublished_at date has passed.
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\News> */
$newsListToUnPublish = News::query()
->where('unpublished_at', '<=', Carbon::now())
->whereNotNull('unpublished_at')
->where('status', NewsStatusEnum::published)->get();
Log::debug(__CLASS__ . " news to unpublish " . $newsListToPublish->count());
foreach ($newsListToUnPublish as $news) {
$news->status = NewsStatusEnum::unpublished;
$news->saveQuietly();
}
}
}

View file

@ -11,26 +11,24 @@ use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
/**
* @property string $title Title of the news.
* @property string $slug Slug of the news.
* @property string $titleSeo Title of the news.
* @property string $descriptionSeo Slug of the news.
* @property string $content Content of the news.
* @property \App\Enums\News\NewsStatusEnum $status Status of the news.
* @property string $picture Main img of the news.
* @property string $picture_alt Alt text for the picture.
* @property string $picture_title Title for the picture.
* @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date on which the news was updated.
* @property string $seo_title SEO title of the news.
* @property string $seo_description SEO description of the news.
* @property string $title Title of the news.
* @property string $slug Slug of the news.
* @property string $picture Main img of the news.
* @property string $picture_alt Alt text for the picture.
* @property string $picture_title Title for the picture.
* @property string $content Content of the news.
* @property \App\Enums\News\NewsStatusEnum $status Status of the news.
* @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date on which the news was updated.
*/
class News extends Model implements TranslatableModel
{
@ -60,15 +58,14 @@ class News extends Model implements TranslatableModel
'content'
];
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'titleSeo',
'descriptionSeo',
'seo_title',
'seo_description',
'title',
'slug',
'content',
@ -80,15 +77,14 @@ class News extends Model implements TranslatableModel
'unpublished_at',
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'titleSeo',
'descriptionSeo',
'seo_title',
'seo_description',
'title',
'slug',
'content',
@ -96,14 +92,13 @@ class News extends Model implements TranslatableModel
'picture_title',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'status' => NewsStatusEnum::class,
'status' => NewsStatusEnum::class,
'published_at' => 'datetime',
'unpublished_at' => 'datetime',
];
@ -139,30 +134,101 @@ class News extends Model implements TranslatableModel
});
}
// * METHODS
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
// Check unique fields.
$slug = Str::slug($model->title);
TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title');
TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'title');
$model->setAttribute('slug', $slug);
// Check translations.
self::validateFallbackTranslations($model);
// Set status.
self::makeStatusSense($model);
}
public function inertiaFill(array $attributes)
{
$attributes = Arr::except($attributes, ['categories']);
$this->traitInertiaFill($attributes);
}
/**
* Adjusts model status using current status and publish dates.
* Case 1: publish model when all null -> set published_at date.
* Case 2: unpublish model when all null -> nothing to do.
* Case 3: publish model when published_at is already set -> only change status.
* Case 4: unpublish model when published_at is already set -> can't update model.
* Case 5: publish model when unpublished_at is already set -> can't update model.
* Case 6: unpublish model when unpublished_at is already set -> only change status.
*
* @param self $model
* @return void
*/
private static function makeStatusSense(self $model): void
{
/** @var \Carbon\Carbon|null */
$published_at = $model->published_at;
/** @var \Carbon\Carbon|null */
$unpublished_at = $model->unpublished_at;
$wantedStatus = $model->status;
// Check if dates are already set.
if ($published_at or $unpublished_at) {
$model->status = $model->planificated_status;
}
// If there is a diff, no update.
if ($wantedStatus !== $model->status) {
session()->flash('error', \trans(
'La publication est modifiée en concordance avec les dates enregistrées.
Pour modifier l\'état de publication, veuillez modifier ou enlever les dates correspondantes.'
));
} else {
// Set default published_at date when publishing model.
if ($model->status->equals(NewsStatusEnum::published)) {
$model->published_at = Carbon::now();
}
}
}
/**
* Getter the current status following planification dates planificated_status.
*
* @return boolean
* @return \App\Enums\News\NewsStatusEnum
*/
public function getPlanificatedStatusAttribute(): bool
protected function getPlanificatedStatusAttribute(): \App\Enums\News\NewsStatusEnum
{
/** @var \Carbon\Carbon|null */
$published_at = $this->published_at;
/** @var \Carbon\Carbon|null */
$unpublished_at = $this->unpublished_at;
if ($published_at and $unpublished_at) {
return $unpublished_at->greaterThanOrEqualTo(now()) and $published_at->lessThan(now());
return ($unpublished_at->greaterThanOrEqualTo(now()) and $published_at->lessThan(now()))
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
if ($published_at) {
return $published_at->lessThan(now());
return $published_at->lessThan(now())
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
if ($unpublished_at) {
return $unpublished_at->greaterThanOrEqualTo(now());
return $unpublished_at->greaterThanOrEqualTo(now())
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
return false;
return NewsStatusEnum::unpublished;
}
/**
* Reset all cache elements related to this model.
*
@ -175,7 +241,7 @@ class News extends Model implements TranslatableModel
}
/**
* Get all published dynamic pages.
* Get all published news.
*
* @return \Illuminate\Database\Eloquent\Collection<int,self>
*/
@ -189,22 +255,16 @@ class News extends Model implements TranslatableModel
});
}
public function publishedAtFormatted()
/**
* Get formated published_at date.
*
* @return string
*/
public function publishedAtFormatted(): string
{
return Carbon::parse($this->published_at)->format('d/m/Y');
}
/**
* The relation with NewsCategory.
*
* @return HasMany
*/
public function categories(): HasMany
{
return $this->hasMany(NewsCategory::class, 'news_id');
}
/**
* Get a comma-separated list of all category labels for this news item.
*
@ -244,32 +304,6 @@ class News extends Model implements TranslatableModel
];
}
public function inertiaFill(array $attributes)
{
$attributes = Arr::except($attributes, ['categories']);
$this->traitInertiaFill($attributes);
}
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
// Check unique fields.
$slug = Str::slug($model->title);
TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title');
TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'title');
$model->setAttribute('slug', $slug);
// Check translations.
self::validateFallbackTranslations($model);
}
/**
* Assert fallback locale translation is present.
*
@ -284,4 +318,16 @@ class News extends Model implements TranslatableModel
}
TranslationHelper::validateFallbackTranslations($model);
}
// * RELATIONSHIPS
/**
* The relation with NewsCategory.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(NewsCategory::class, 'news_id');
}
}

View file

@ -28,6 +28,7 @@ class DynamicPageRouteServiceProvider extends ServiceProvider
], function () {
$dynamicPageModels = DynamicPage::getPublishedDynamicPages();
DynamicPage::getPublishedDynamicPages()
->load('parentPage')
->map(function (DynamicPage $dynamicPageModel) use ($dynamicPageModels) {
$locale = app()->getLocale();
$slug = $dynamicPageModel->getTranslation("slug", $locale);

View file

@ -30,8 +30,8 @@ class IndexNewsComponent extends Component
->map(fn($category) => NewsCategoryEnum::make((int) $category->value))
->filter(fn($categoryLocal) => $categoryLocal->categoriesWithLocal())
->map(fn($categoryLocal) => [
'title' => __($categoryLocal->label()),
'tag' => Str::slug($categoryLocal->value),
'title' => trans($categoryLocal->label()),
'tag' => Str::slug($categoryLocal->value),
'category' => 'news',
])
->values()
@ -41,7 +41,7 @@ class IndexNewsComponent extends Component
->map(fn($year) => NewsYearsEnum::make((int) $year->value))
->filter(fn($yearLocal) => $yearLocal->yearsWithLocal())
->map(fn($yearLocal) => [
'title' => __($yearLocal->label()),
'title' => trans($yearLocal->label()),
'tag' => Str::slug($yearLocal->value),
'category' => 'news',
])
@ -50,8 +50,10 @@ class IndexNewsComponent extends Component
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */
$query = News::query()->with('categories');
/** Sort columns with a query */
$bladeHelper->runSortQuery($query);
/** Custom pagination */
$this->newsModels = $bladeHelper->runPaginate($query);
@ -105,9 +107,9 @@ class IndexNewsComponent extends Component
public function render(): View|Closure|string
{
return view('components.front.news.index-news-component', [
'categories' => $this->categories,
'years' => $this->years,
'newsModels' => $this->newsModels,
'categories' => $this->categories,
'years' => $this->years,
'newsModels' => $this->newsModels,
'postContainer' => $this->postContainer
]);
}

View file

@ -20,15 +20,14 @@ class NewsFactory extends Factory
public function definition(): array
{
return [
'titleSeo' => fake()->sentence(6, true),
'descriptionSeo' => fake()->paragraph(2, true),
'title' => fake()->sentence(4),
'slug' => fake()->unique()->slug(),
'content' => fake()->paragraphs(5, true),
'status' => collect(NewsStatusEnum::cases())->random(),
'picture' => fake()->imageUrl(1200, 800, 'news', true, 'headline'),
'picture_alt' => fake()->sentence(6, true),
'picture_title' => fake()->sentence(6, true),
'seo_title' => fake()->sentence(6, true),
'seo_description' => fake()->paragraph(2, true),
'title' => fake()->sentence(4),
'slug' => fake()->unique()->slug(),
'content' => fake()->paragraphs(5, true),
'status' => collect(NewsStatusEnum::cases())->random(),
'picture_alt' => fake()->sentence(6, true),
'picture_title' => fake()->sentence(6, true),
];
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

View file

@ -8,6 +8,8 @@ return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
@ -21,6 +23,8 @@ return new class extends Migration
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{

View file

@ -8,6 +8,8 @@ return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
@ -17,11 +19,11 @@ return new class extends Migration
$table->string('descriptionSeo')->nullable()->comment('Seo description of the news');
$table->string('title')->comment('Required title for the news');
$table->string('slug')->unique()->comment('Required and unique slug for the news.show');
$table->text('content')->comment('Body of the news, wysiwyg to be more specific, from Seattle');
$table->unsignedTinyInteger('status')->comment('Status of the news');
$table->string('picture')->nullable()->comment('Banner and thumbnail of the news');
$table->string('picture_alt')->nullable()->comment('Alt of the picture of the news');
$table->string('picture_title')->nullable()->comment('Title of the picture of the news');
$table->text('content')->comment('Body of the news, wysiwyg to be more specific');
$table->unsignedTinyInteger('status')->comment('Status of the news');
$table->timestamp('published_at')->nullable()->comment('News corporate publishment date.');
$table->timestamp('unpublished_at')->nullable()->comment('News corporate unpublishment date.');
$table->softDeletes();
@ -31,6 +33,8 @@ return new class extends Migration
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{

View file

@ -8,6 +8,8 @@ return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
@ -21,6 +23,8 @@ return new class extends Migration
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{

View file

@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('news', function (Blueprint $table) {
$table->renameColumn('titleSeo', 'seo_title');
$table->renameColumn('descriptionSeo', 'seo_description');
});
Schema::table('news', function (Blueprint $table) {
$table->string('seo_title')->nullable(false)->comment('Seo title for the news')->change();
$table->string('seo_description')->nullable(false)->comment('Seo description of the news')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('news', function (Blueprint $table) {
$table->renameColumn('seo_title', 'titleSeo');
$table->renameColumn('seo_description', 'descriptionSeo');
});
Schema::table('news', function (Blueprint $table) {
$table->string('titleSeo')->nullable(true)->comment('Seo title for the news')->change();
$table->string('descriptionSeo')->nullable(true)->comment('Seo description of the news')->change();
});
}
};

View file

@ -4,6 +4,7 @@ namespace Database\Seeders;
use App\Models\News;
use Illuminate\Database\Seeder;
use Uwil\LaravelCommon\Helpers\FileHelper;
class NewsSeeder extends Seeder
{
@ -14,6 +15,15 @@ class NewsSeeder extends Seeder
*/
public function run(): void
{
News::factory(100)->create();
News::factory(100)->make()
->each(function ($model) {
$model->picture = FileHelper::storeFile(
$model,
new \SplFileInfo(\resource_path(
'../database/factories/assets/news/525x295.jpg'
))
);
$model->saveOrFail();
});
}
}

View file

@ -28,8 +28,8 @@ return [
in search engines (<title> tag).",
"seo_description" => "Must precisely describe page content (<meta> description tag).",
"visibility_with_dates" => "This field will only have an effect if no date is entered.",
"publish_at" => ":model will be published from this date.",
"unpublish_at" => ":model will be unpublished from this date.",
"published_at" => ":model will be published from this date.",
"unpublished_at" => ":model will be unpublished from this date.",
"year" => "Must be a year between :yearStart and :yearEnd.",
],

View file

@ -240,9 +240,11 @@ return [
"locked" => "locked",
"field" => "field",
"key" => "unique key",
"slug" => "slug",
"titleSeo" => "seo title",
"descriptionSeo" => "seo description",
"slug" => "slug",
"seo" => [
"title" => "seo title",
"description" => "seo description",
],
"category" => "category|categories",
"picture" => [
"picture" => "image",

View file

@ -28,8 +28,8 @@ return [
optimal dans les moteurs de recherche (balise <title>).",
"seo_description" => "Doit décrire précisément le contenu de la page (balise <meta> description).",
"visibility_with_dates" => "Ce champ n'aura d'effet que si aucune date n'est renseignée.",
"publish_at" => ":model sera publié à partir de cette date.",
"unpublish_at" => ":model sera dépublié à partir de cette date.",
"published_at" => ":model sera publié à partir de cette date.",
"unpublished_at" => ":model sera dépublié à partir de cette date.",
"year" => "Doît être une année comprise entre :yearStart et :yearEnd.",
],

View file

@ -241,15 +241,14 @@ return [
"field" => "champs",
"key" => "clé",
"slug" => "chemin d'accès",
"titleSeo" => "titre SEO",
"parent_page" => "page parente",
"descriptionSeo" => "description SEO",
"category" => "catégorie|catégories",
"picture" => [
"picture" => "image",
"picture_alt" => "texte alternatif de l'image",
"picture_title" => "titre de l'image"
"seo" => [
"title" => "titre SEO",
"description" => "description SEO",
],
"category" => "catégorie|catégories",
"image_alt" => "texte alternatif de l'image",
"image_title" => "titre de l'image",
"content" => "contenu",
"contactCount" => [
"type" => "type de formulaire",

View file

@ -1,4 +1,3 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import {
CheckIcon,
@ -7,7 +6,6 @@ import {
XIcon,
WandSparkles,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
@ -31,6 +29,7 @@ import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import InputError from "@/back/Components/InputError";
import { usePage } from "@inertiajs/react";
import { ButtonHTMLAttributes, ComponentType, CSSProperties, forwardRef, KeyboardEvent, ReactNode, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
/**
* Animation types and configurations
@ -86,7 +85,7 @@ interface MultiSelectOption {
/** The unique value associated with the option. */
value: string;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
icon?: ComponentType<{ className?: string }>;
/** Whether this option is disabled */
disabled?: boolean;
/** Custom styling for the option */
@ -115,7 +114,7 @@ interface MultiSelectGroup {
*/
interface MultiSelectProps
extends Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
ButtonHTMLAttributes<HTMLButtonElement>,
"animationConfig"
>,
VariantProps<typeof multiSelectVariants> {
@ -127,7 +126,7 @@ interface MultiSelectProps
* Callback function triggered when the selected values change.
* Receives an array of the new selected values.
*/
onValueChange: (value: string[]) => void;
onValueChange?: (value: string[]) => void;
/** The default selected values when the component mounts. */
defaultValue?: string[];
@ -192,7 +191,7 @@ interface MultiSelectProps
* Custom empty state message when no options match search.
* Optional, defaults to "No results found."
*/
emptyIndicator?: React.ReactNode;
emptyIndicator?: ReactNode;
/**
* If true, allows the component to grow and shrink with its content.
@ -352,7 +351,7 @@ export interface MultiSelectRef {
focus: () => void;
}
export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
export const MultiSelect = forwardRef<MultiSelectRef, MultiSelectProps>(
(
{
name,
@ -391,21 +390,20 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
},
ref
) => {
const [selectedValues, setSelectedValues] =
React.useState<string[]>(defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
const [isAnimating, setIsAnimating] = React.useState(false);
const [searchValue, setSearchValue] = React.useState("");
const [selectedValues, setSelectedValues] = useState<string[]>(defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const [isAnimating, setIsAnimating] = useState(false);
const [searchValue, setSearchValue] = useState("");
const [politeMessage, setPoliteMessage] = React.useState("");
const [assertiveMessage, setAssertiveMessage] = React.useState("");
const prevSelectedCount = React.useRef(selectedValues.length);
const prevIsOpen = React.useRef(isPopoverOpen);
const prevSearchValue = React.useRef(searchValue);
const [politeMessage, setPoliteMessage] = useState("");
const [assertiveMessage, setAssertiveMessage] = useState("");
const prevSelectedCount = useRef(selectedValues.length);
const prevIsOpen = useRef(isPopoverOpen);
const prevSearchValue = useRef(searchValue);
const { errors } = usePage().props;
const announce = React.useCallback(
const announce = useCallback(
(message: string, priority: "polite" | "assertive" = "polite") => {
if (priority === "assertive") {
setAssertiveMessage(message);
@ -418,14 +416,14 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
[]
);
const multiSelectId = React.useId();
const multiSelectId = useId();
const listboxId = `${multiSelectId}-listbox`;
const triggerDescriptionId = `${multiSelectId}-description`;
const selectedCountId = `${multiSelectId}-count`;
const prevDefaultValueRef = React.useRef<string[]>(defaultValue);
const prevDefaultValueRef = useRef<string[]>(defaultValue);
const isGroupedOptions = React.useCallback(
const isGroupedOptions = useCallback(
(
opts: MultiSelectOption[] | MultiSelectGroup[]
): opts is MultiSelectGroup[] => {
@ -434,7 +432,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
[]
);
const arraysEqual = React.useCallback(
const arraysEqual = useCallback(
(a: string[], b: string[]): boolean => {
if (a.length !== b.length) return false;
const sortedA = [...a].sort();
@ -444,29 +442,35 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
[]
);
const resetToDefault = React.useCallback(() => {
const resetToDefault = useCallback(() => {
setSelectedValues(defaultValue);
setIsPopoverOpen(false);
setSearchValue("");
onValueChange(defaultValue);
if (onValueChange) {
onValueChange(defaultValue);
}
setData(name, defaultValue);
}, [defaultValue, onValueChange]);
const buttonRef = React.useRef<HTMLButtonElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
React.useImperativeHandle(
useImperativeHandle(
ref,
() => ({
reset: resetToDefault,
getSelectedValues: () => selectedValues,
setSelectedValues: (values: string[]) => {
setSelectedValues(values);
onValueChange(values);
if (onValueChange) {
onValueChange(values);
}
setData(name, values);
},
clear: () => {
setSelectedValues([]);
onValueChange([]);
if (onValueChange) {
onValueChange([]);
}
setData(name, []);
},
focus: () => {
@ -488,11 +492,11 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
[resetToDefault, selectedValues, onValueChange]
);
const [screenSize, setScreenSize] = React.useState<
const [screenSize, setScreenSize] = useState<
"mobile" | "tablet" | "desktop"
>("desktop");
React.useEffect(() => {
useEffect(() => {
if (typeof window === "undefined") return;
const handleResize = () => {
const width = window.innerWidth;
@ -588,7 +592,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
return "";
};
const getAllOptions = React.useCallback((): MultiSelectOption[] => {
const getAllOptions = useCallback((): MultiSelectOption[] => {
if (options.length === 0) return [];
let allOptions: MultiSelectOption[];
if (isGroupedOptions(options)) {
@ -627,7 +631,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
return deduplicateOptions ? uniqueOptions : allOptions;
}, [options, deduplicateOptions, isGroupedOptions]);
const getOptionByValue = React.useCallback(
const getOptionByValue = useCallback(
(value: string): MultiSelectOption | undefined => {
const option = getAllOptions().find((option) => option.value === value);
if (!option && process.env.NODE_ENV === "development") {
@ -640,7 +644,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
[getAllOptions]
);
const filteredOptions = React.useMemo(() => {
const filteredOptions = useMemo(() => {
if (!searchable || !searchValue) return options;
if (options.length === 0) return [];
if (isGroupedOptions(options)) {
@ -665,7 +669,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}, [options, searchValue, searchable, isGroupedOptions]);
const handleInputKeyDown = (
event: React.KeyboardEvent<HTMLInputElement>
event: KeyboardEvent<HTMLInputElement>
) => {
if (event.key === "Enter") {
setIsPopoverOpen(true);
@ -673,7 +677,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
if (onValueChange) {
onValueChange(newSelectedValues);
}
setData(name, newSelectedValues);
}
};
@ -687,7 +693,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
if (!multiple) {
const newSelectedValues = selectedValues.includes(optionValue) ? [] : [optionValue];
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
if (onValueChange) {
onValueChange(newSelectedValues);
}
setData(name, newSelectedValues);
if (closeOnSelect) {
setIsPopoverOpen(false);
@ -705,7 +713,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}
const newSelectedValues = selectedValues.filter((value) => value !== optionValue);
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
if (onValueChange) {
onValueChange(newSelectedValues);
}
setData(name, newSelectedValues);
} else {
if (maxSelection && selectedValues.length >= maxSelection) {
@ -714,7 +724,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}
const newSelectedValues = [...selectedValues, optionValue];
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
if (onValueChange) {
onValueChange(newSelectedValues);
}
setData(name, newSelectedValues);
}
@ -730,7 +742,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
return;
}
setSelectedValues([]);
onValueChange([]);
if (onValueChange) {
onValueChange([]);
}
setData(name, []);
};
@ -746,7 +760,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
responsiveSettings.maxCount
);
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
if (onValueChange) {
onValueChange(newSelectedValues);
}
setData(name, newSelectedValues);
};
@ -767,7 +783,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
return;
}
setSelectedValues(allValues);
onValueChange(allValues);
if (onValueChange) {
onValueChange(allValues);
}
setData(name, allValues);
}
@ -776,7 +794,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}
};
React.useEffect(() => {
useEffect(() => {
if (!resetOnDefaultValueChange) return;
const prevDefaultValue = prevDefaultValueRef.current;
if (!arraysEqual(prevDefaultValue, defaultValue)) {
@ -800,13 +818,13 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
const widthConstraints = getWidthConstraints();
React.useEffect(() => {
useEffect(() => {
if (!isPopoverOpen) {
setSearchValue("");
}
}, [isPopoverOpen]);
React.useEffect(() => {
useEffect(() => {
const selectedCount = selectedValues.length;
const allOptions = getAllOptions();
const totalOptions = allOptions.filter((opt) => !opt.disabled).length;
@ -868,7 +886,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}
}, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]);
React.useEffect(() => {
useEffect(() => {
if (minSelection !== undefined && maxSelection !== undefined && minSelection > maxSelection) {
console.error('MultiSelect: minSelection cannot be greater than maxSelection');
}
@ -884,7 +902,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
}, [minSelection, maxSelection, multiple]);
return (
<>
<div>
<div className="sr-only">
<div aria-live="polite" aria-atomic="true" role="status">
{politeMessage}
@ -963,7 +981,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
if (!option) {
return null;
}
const badgeStyle: React.CSSProperties = {
const badgeStyle: CSSProperties = {
animationDuration: `${animation}s`,
...(customStyle?.badgeColor && {
backgroundColor: customStyle.badgeColor,
@ -1316,7 +1334,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
</Popover>
{helper && (<small className="text-muted-foreground">{helper}</small>)}
<InputError message={errors[name]} />
</>
</div>
);
}
);

View file

@ -58,7 +58,7 @@ export default function SimpleDatePicker({
};
const resetDate = () => {
setData(name, undefined);
setData(name, null);
}
function handleTimeChange(type: "hour" | "minute", value: string) {
@ -81,7 +81,7 @@ export default function SimpleDatePicker({
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn("w-full font-normal text-muted-foreground", className)}
className={cn("w-full font-normal", { "text-muted-foreground hover:text-muted-foreground": !date }, className)}
disabled={disabled}
>
<span>

View file

@ -25,7 +25,7 @@ type SimpleStringProps = {
disabled?: boolean;
pattern?: string;
checkVisibility?: boolean;
parentErrors?: Record<string, string>,
parentErrors?: Record<string, string> | null,
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
@ -43,7 +43,7 @@ export default function SimpleString({
disabled = false,
pattern,
checkVisibility = false,
parentErrors = {},
parentErrors = null,
setData,
}: SimpleStringProps) {
const [isVisible, setIsVisible] = useState(checkVisibility);

View file

@ -30,7 +30,7 @@ import InputError from "@/back/Components/InputError";
import str from "@/hooks/use-string";
import { useToast } from "@/hooks/use-toast";
import { Methods } from "@/lib/enums";
import { AppEnv, AuthProp, DynamicField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global";
import { AppEnv, AuthProp, ConfigField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global";
import {
Tooltip,
TooltipContent,
@ -162,7 +162,7 @@ export default function Form({
const getConfig = (id: number) =>
configOptions.find((objet) => objet.id == id)?.config[
locale
] as DynamicField[];
] as ConfigField[];
const { toast } = useToast();
/** Form section */

View file

@ -62,8 +62,8 @@ export default function Form({
/** Form section */
const { post, setData, data, reset } = useForm({
_method: method === Methods.POST ? 'post' : 'put',
titleSeo: model?.titleSeo ? model?.titleSeo[locale] : "",
descriptionSeo: model?.descriptionSeo ? model?.descriptionSeo[locale] : "",
seo_title: model?.seo_title ? model?.seo_title[locale] : "",
seo_description: model?.seo_description ? model?.seo_description[locale] : "",
title: model?.title ? model?.title[locale] : "",
slug: model?.slug ? model?.slug[locale] : "",
content: model?.content ? model?.content[locale] : "",
@ -125,33 +125,33 @@ export default function Form({
className="sm:grid-cols-2 gap-4"
>
<SimpleString
name="titleSeo"
name="seo_title"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.titleSeo"),
attribute: useTrans("validation.custom.seo.title"),
},
choice: 1,
}),
).ucFirst().value()}
required={false}
required={true}
placeholder="ex: John Doe"
value={data.titleSeo ?? ""}
value={data.seo_title ?? ""}
setData={setData}
/>
<SimpleString
name="descriptionSeo"
name="seo_description"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.descriptionSeo"),
attribute: useTrans("validation.custom.seo.description"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder="ex: John Doe"
required={false}
value={data.descriptionSeo ?? ""}
required={true}
value={data.seo_description ?? ""}
setData={setData}
/>
</FieldsetWrapper>
@ -189,21 +189,6 @@ export default function Form({
value={data.slug}
setData={setData}
/>
<EnumSelect
name="status"
options={enumNewsStatus}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.status"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder={"ex: " + enumNewsStatus.unpublished.label}
selected={String(data.status)}
setData={setData}
/>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_configuration")}
@ -239,6 +224,21 @@ export default function Form({
}),
).ucFirst().value()}
/>
<EnumSelect
name="status"
options={enumNewsStatus}
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.status"),
},
choice: 1,
}),
).ucFirst().value()}
placeholder={"ex: " + enumNewsStatus.unpublished.label}
selected={String(data.status)}
setData={setData}
/>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_files")}
@ -252,7 +252,7 @@ export default function Form({
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.picture.picture_alt"),
attribute: useTrans("validation.custom.image_alt"),
},
choice: 1,
}),
@ -267,7 +267,7 @@ export default function Form({
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.picture.picture_title"),
attribute: useTrans("validation.custom.image_title"),
},
choice: 1,
}),
@ -283,7 +283,7 @@ export default function Form({
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.picture.picture"),
attribute: useTrans("validation.attributes.image"),
},
choice: 1,
}),
@ -306,46 +306,41 @@ export default function Form({
description={useTrans("back.form_subtitle_content")}
className="gap-4"
>
<div>
<SimpleWysiwyg
name={"content"}
model="News"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.content"),
},
choice: 1
}),
).ucFirst().value()}
value={data.content}
setData={setData}
/>
</div>
<div>
<MultiSelect
label={str(
useTrans("back.form_associate_to_plural", {
params: {
attribute: useTrans("validation.custom.category", { choice: 2 }),
},
choice: 2
}),
).ucFirst().value()}
multiple={true}
name="categories"
required={false}
variant={"inverted"}
placeholder={str(
useTrans("back.news.categories.placeholder")
).ucFirst().value()}
badgeAnimation={"wiggle"}
singleLine={true}
setData={setData}
defaultValue={data.categories}
options={options}
onValueChange={() => { }} />
</div>
<SimpleWysiwyg
name={"content"}
model="News"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.content"),
},
choice: 1
}),
).ucFirst().value()}
value={data.content}
setData={setData}
/>
<MultiSelect
label={str(
useTrans("back.form_associate_to_plural", {
params: {
attribute: useTrans("validation.custom.category", { choice: 2 }),
},
choice: 2
}),
).ucFirst().value()}
multiple={true}
name="categories"
required={false}
variant="inverted"
placeholder={str(
useTrans("back.news.categories.placeholder")
).ucFirst().value()}
singleLine={true}
setData={setData}
defaultValue={data.categories}
options={options}
/>
</FieldsetWrapper>
<div className="text-center">
<SubmitButton />

View file

@ -41,15 +41,15 @@ export default function Show({ data }: { data: SingleResource }) {
console.log(useLocale.use.timezone());
const columns = [
{
accessorKey: "titleSeo",
header: str(useTrans("validation.custom.titleSeo")).ucFirst().value(),
accessorKey: "seo_title",
header: str(useTrans("validation.custom.seo.title")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => value[appEnv.locale]
? value[appEnv.locale]
: (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>),
},
{
accessorKey: "descriptionSeo",
header: str(useTrans("validation.custom.descriptionSeo")).ucFirst().value(),
accessorKey: "seo_description",
header: str(useTrans("validation.custom.seo.description")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => value[appEnv.locale]
? value[appEnv.locale]
: (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>),
@ -110,21 +110,21 @@ export default function Show({ data }: { data: SingleResource }) {
},
{
accessorKey: "picture",
header: str(useTrans("validation.custom.picture.picture")).ucFirst().value(),
header: str(useTrans("validation.attributes.image")).ucFirst().value(),
cell: ({ value }: { value: string }) => (
<img src={`${appEnv.url}/${value}`} />
),
},
{
accessorKey: "picture_alt",
header: str(useTrans("validation.custom.picture.picture_alt")).ucFirst().value(),
header: str(useTrans("validation.custom.image_alt")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => value[appEnv.locale]
? value[appEnv.locale]
: (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>),
},
{
accessorKey: "picture_title",
header: str(useTrans("validation.custom.picture.picture_title")).ucFirst().value(),
header: str(useTrans("validation.custom.image_title")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => value[appEnv.locale]
? value[appEnv.locale]
: (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>),

View file

@ -107,8 +107,8 @@ type ConfigInternalField = Omit<DynamicField, "children"> & {
type NewsModel = {
policies: ModelPolicy;
id: number;
titleSeo: TranslationField | null;
descriptionSeo: TranslationField | null;
seo_title: TranslationField | null;
seo_description: TranslationField | null;
title: TranslationField;
slug: TranslationField;
content: TranslationField;

View file

@ -21,11 +21,9 @@
</div>
@endif
<div class="list-item__title posts-list__item-title subtitle">{{ $news['title'] }}</div>
@if (isset($news->created_at))
<div class="list-item__date date {{ $news->first_category_data['date_classes'] ?? 'date_no-tags' }}">
{{ $news->created_at }}
</div>
@endif
<div class="list-item__date date {{ $news->first_category_data['date_classes'] ?? 'date_no-tags' }}">
{{ $news->publishedAtFormatted() }}
</div>
<div class="list-item__text ellipsis description"></div>
@if ($isButtonStyle)
<x-front.cta title="Lire l'article" class="list-item__readmore"

View file

@ -1,6 +1,6 @@
@extends('front.layouts.layout')
@section('title', $model['titleSeo'])
@section('description', $model['descriptionSeo'])
@section('title', $model['seo_title'])
@section('description', $model['seo_description'])
@section('content')
<div class="single-news fw">
@ -18,7 +18,8 @@
{{ $model['title'] }}
</h1>
<div class="single-news__date date {{ $model->first_category_data['date_classes'] ?? '' }}">
{{ $model['created_at'] }}</div>
{{ $model->publishedAtFormatted() }}
</div>
<div class="textblock__container">
<div class="textblock__image textblock__block image-border-wrap">
<x-front.borders :borders="[