Rework admin panel and other

This commit is contained in:
F4ilji
2025-04-02 18:37:20 +05:00
parent 49072e50c7
commit 5cd6ff11b5
198 changed files with 9715 additions and 6664 deletions
+156 -27
View File
@@ -13,6 +13,7 @@ use App\Models\Page;
use App\Models\Post;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor;
@@ -36,52 +37,180 @@ class CustomFormForm
{
return $form
->schema([
Section::make()
Section::make('Настройки формы')
->description('Конфигурация пользовательской формы')
->collapsible()
->schema([
Tabs::make('Tabs')
Tabs::make('Конфигурация формы')
->persistTabInQueryString()
->columnSpanFull()
->tabs([
Tabs\Tab::make('Основная информация')
->icon('heroicon-o-information-circle')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('title')->label('Заголовок')->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('form_id', Str::slug($state) . Carbon::now()->timestamp);
}),
TextInput::make('form_id')->label('ID формы')->unique(ignoreRecord: true)->required(),
]),
Forms\Components\Textarea::make('description')->label('Описание формы')->required(),
Select::make('status')->label('Статус формы')->required()
Forms\Components\Grid::make(2)
->schema([
TextInput::make('title')
->label('Название формы')
->placeholder('Введите название формы')
->helperText('Это название будет видно пользователям')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('form_id', Str::slug($state) . Carbon::now()->timestamp);
}),
TextInput::make('form_id')
->label('Уникальный ID формы')
->helperText('Автоматически генерируется из названия')
->required()
->unique(ignoreRecord: true)
->maxLength(255),
]),
Forms\Components\Textarea::make('description')
->label('Описание формы')
->placeholder('Опишите назначение этой формы')
->helperText('Это описание будет видно пользователям')
->required()
->maxLength(2000)
->columnSpanFull(),
Select::make('status')
->label('Статус формы')
->options(CustomFormStatus::class)
->required()
->native(false)
->helperText('Определяет видимость формы на сайте')
->columnSpanFull(),
]),
Tabs\Tab::make('Колонки')
Tabs\Tab::make('Поля формы')
->icon('heroicon-o-view-columns')
->schema([
FormBuilderItem::getItem(),
FormBuilderItem::getItem()
->columnSpanFull(),
]),
Tabs\Tab::make('Кнопка отправки')
->icon('heroicon-o-paper-airplane')
->schema([
TextInput::make('button')->label('Текст кнопки отправки')->required(),
Forms\Components\Textarea::make('send_message')->label('Текст после отправления письма')->required(),
TextInput::make('button')
->label('Текст кнопки отправки')
->placeholder('Например: Отправить заявку')
->helperText('Текст, который будет отображаться на кнопке отправки формы')
->required()
->maxLength(255),
Forms\Components\Textarea::make('send_message')
->label('Сообщение после отправки')
->placeholder('Спасибо! Ваша заявка принята.')
->helperText('Это сообщение увидят пользователи после успешной отправки формы')
->required()
->maxLength(1000)
->columnSpanFull(),
]),
Tabs\Tab::make('Настройка интеграции с почтой')
Tabs\Tab::make('Настройки')
->icon('heroicon-o-cog')
->schema([
Toggle::make('settings.personal_data')
->label('Согласие на обработку данных')
->helperText('Показывать checkbox для согласия на обработку персональных данных')
->inline(false)
->onColor('success')
->offColor('gray'),
Toggle::make('settings.captcha')
->label('Защита CAPTCHA')
->helperText('Включить защиту от спама с помощью CAPTCHA')
->inline(false)
->onColor('success')
->offColor('gray'),
Section::make('Ограничение по времени')
->collapsible()
->schema([
Toggle::make('is_time_period')
->label('Ограничить период работы формы')
->helperText('Форма будет активна только в указанный период')
->dehydrated(false)
->live(true)
->inline(false),
Forms\Components\Grid::make(2)
->schema([
DateTimePicker::make('settings.period.start_time')
->label('Дата начала')
->native(false)
->displayFormat('d/m/Y H:i')
->seconds(false)
->helperText('Когда форма станет доступна')
->default(Carbon::now())
->minDate(Carbon::now()),
DateTimePicker::make('settings.period.end_time')
->label('Дата окончания')
->native(false)
->displayFormat('d/m/Y H:i')
->seconds(false)
->helperText('Когда форма перестанет быть доступна')
->default(Carbon::now()->addWeeks(2))
->minDate(Carbon::now()),
])
->hidden(fn(Forms\Get $get): bool => $get('is_time_period') !== true),
]),
]),
Tabs\Tab::make('Настройки почты')
->icon('heroicon-o-envelope')
->schema([
Forms\Components\Repeater::make('mail_settings')
->label('')
->label('Настройки уведомлений')
->addActionLabel('Добавить получателя')
->helperText('Укажите, кому и какие уведомления отправлять')
->collapsed()
->itemLabel(fn (array $state): ?string => $state['target'] ?? 'Новый получатель')
->schema([
TextInput::make('target')->label('Кому')->email()->required(),
TextInput::make('topic')->label('Тема')->required(),
Builder::make('data')->schema([
Builder\Block::make('text')->schema([
RichEditor::make('content')->required(),
TextInput::make('target')
->label('Email получателя')
->placeholder('email@example.com')
->email()
->required()
->maxLength(255),
TextInput::make('topic')
->label('Тема письма')
->placeholder('Новая заявка с формы')
->required()
->maxLength(255),
Builder::make('data')
->label('Содержимое письма')
->blockNumbers(false)
->collapsible()
->schema([
Builder\Block::make('text')
->label('Текст письма')
->schema([
RichEditor::make('content')
->label('')
->required()
->toolbarButtons([
'bold', 'italic', 'link',
'orderedList', 'bulletList'
]),
]),
Builder\Block::make('answers')
->label('Ответы формы')
->schema([]),
]),
Builder\Block::make('answers')->schema([]),
])->required(),
])
->collapsed(),
->grid(2),
]),
]),
])
]),
]);
}
}
@@ -0,0 +1,8 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
interface BlockSchema
{
public static function schema(): array;
}
@@ -0,0 +1,31 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use App\Models\ContactWidget;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class ContactBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('contact')
->label('Виджет контактов')
->options(ContactWidget::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный виджет контактов'),
];
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Enums\CustomFormStatus;
use App\Models\CustomForm;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
class CustomFormBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('form')
->label('Форма')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required()
->helperText('Выберите опубликованную форму'),
Section::make()->schema([
Toggle::make('settings.in_modal')->label('Открывать в модальном окне')->default(false),
]),
];
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class FilesBlock implements BlockSchema
{
public static function schema(): array
{
return [
Repeater::make('file')
->label('Файлы')
->helperText('Загрузите один или несколько файлов')
->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->label('Название файла')
->placeholder('Введите название файла')
->required()
->maxLength(255)
->autofocus()
->helperText('Это название будет отображаться пользователям'),
FileUpload::make('path')
->label('Файл')
->required()
->helperText('Поддерживаются PDF, Word, Excel, PowerPoint и ZIP файлы (макс. 500KB)')
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
->preserveFilenames()
])
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
->collapsible()
->cloneable()
->grid(2),
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use Filament\Forms\Components\TextInput;
class HeadingBlock implements BlockSchema
{
public static function schema(): array
{
return [
TextInput::make('id')
->hidden()
->integer()
->default(rand(2335235, 324634264263426)),
TextInput::make('content')
->label('Текст заголовка')
->placeholder('Введите текст заголовка')
->helperText('Основной заголовок раздела')
->live(onBlur: true)
->required()
->maxLength(255),
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class ImageBlock implements BlockSchema
{
public static function schema(): array
{
return [
FileUpload::make('url')
->label('Изображение')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required()
->helperText('Можно загрузить до 5 изображений'),
TextInput::make('alt')
->label('Альтернативный текст')
->placeholder('Необязательно')
->helperText('Описание изображения для SEO'),
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class ImagesBlock implements BlockSchema
{
public static function schema(): array
{
return [
FileUpload::make('url')
->label('Изображения')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required()
->helperText('Максимум 5 изображений. Можно перетаскивать для изменения порядка'),
TextInput::make('alt')
->label('Описание изображений')
->placeholder('Необязательно')
->helperText('Используется для SEO и доступности'),
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use App\Models\Page;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class PageItemBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('page')
->label('Страница')
->options(Page::query()->where('title', '!=', null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required()
->helperText('Выберите видимую страницу'),
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use App\Models\PageReferenceList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class PageResourceListBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('resource')
->label('Ресурс')
->options(PageReferenceList::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный ресурс'),
];
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Get;
use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
class ParagraphBlock implements BlockSchema
{
public static function schema(): array
{
return [
Toggle::make('seo_active')
->label('Использовать блок как SEO-текст')
->helperText('Этот текст будет использоваться для SEO-оптимизации')
->live(onBlur: true)
->required()
->disabled(function ($state, Get $get) {
$data = $get('../../');
return self::findSeoActive($data) && !$state;
})
->dehydrated(),
TinyEditor::make('content')
->label('Текст')
->placeholder('Начните вводить текст...')
->profile('test')
->required()
->helperText('Основное текстовое содержимое блока'),
];
}
private static function findSeoActive(array $data) : bool
{
$bool = false;
foreach ($data as $item) {
if ($item['type'] !== 'paragraph') {
continue;
}
if ($item['data']['seo_active'] === true) {
$bool = true;
break;
}
}
return $bool;
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class PersonBlock implements BlockSchema
{
public static function schema(): array
{
return [
TextInput::make('name')
->label('Имя персоны')
->placeholder('Введите имя')
->required()
->maxLength(255)
->helperText('Полное имя персоны'),
FileUpload::make('photo')
->label('Фотография')
->image()
->helperText('Рекомендуемый формат: WebP')
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor()
->required()
->downloadable()
->openable(),
Repeater::make('info')
->label('Дополнительная информация')
->helperText('Добавьте характеристики персоны')
->schema([
TextInput::make('column')
->label('Название характеристики')
->placeholder('Например: Должность')
->required()
->maxLength(255),
Textarea::make('content')
->label('Значение')
->placeholder('Например: Главный инженер')
->required()
->maxLength(1000)
->columnSpanFull(),
])
->minItems(1)
->grid(2)
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['column'] ?? null),
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Enums\PostStatus;
use App\Models\Post;
use Filament\Forms\Components\Select;
class PostItemBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('post')
->label('Новость')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required()
->helperText('Выберите опубликованную новость'),
];
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use App\Models\Category;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class PostListBlock implements BlockSchema
{
public static function schema(): array
{
return [
Grid::make(2)
->schema([
TextInput::make('count')
->label('Количество записей')
->integer()
->minValue(1)
->maxValue(20)
->default(5)
->helperText('От 1 до 20 записей'),
Select::make('category')
->label('Категория')
->options(Category::all()->pluck('title', 'id'))
->searchable()
->helperText('Выберите категорию или оставьте пустым для всех'),
]),
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use App\Models\Slider;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class SliderBlock implements BlockSchema
{
public static function schema(): array
{
return [
Select::make('slider')
->label('Слайдер')
->options(Slider::query()->whereHas('slides')->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный слайдер с изображениями'),
];
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class StepperBlock implements BlockSchema
{
public static function schema(): array
{
return [
TextInput::make('step_name')
->label('Название процесса')
->placeholder('Например: Процесс оформления')
->required()
->maxLength(255)
->helperText('Общее название для всех шагов'),
Repeater::make('steps')
->label('Шаги')
->helperText('Добавьте шаги процесса')
->schema([
TextInput::make('title')
->label('Название шага')
->placeholder('Например: Шаг 1')
->required()
->maxLength(255)
->columnSpanFull(),
RichEditor::make('content')
->label('Описание шага')
->required()
->toolbarButtons([
'bold',
'italic',
'link',
'orderedList',
'bulletList',
]),
])
->minItems(1)
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title'] ?? null),
];
}
}
@@ -0,0 +1,128 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Filament\Components\Forms\ItemForm\Defaults\TabBuilderItem;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class TabBlock implements BlockSchema
{
public static function schema(): array
{
return [
Repeater::make('tab')
->label('Вкладки')
->helperText('Добавьте вкладки с контентом')
->schema([
TextInput::make('title')
->label('Название вкладки')
->placeholder('Введите название вкладки')
->required()
->maxLength(255)
->columnSpanFull()
->helperText('Это название будет отображаться в табе'),
Builder::make('content')
->label('')
->blocks([
Builder\Block::make('heading')
->label('Заголовок')
->icon('heroicon-o-hashtag')
->schema(HeadingBlock::schema()),
Builder\Block::make('paragraph')
->label('Текст')
->icon('heroicon-o-document-text')
->schema(ParagraphBlock::schema()),
Builder\Block::make('files')
->label('Файлы')
->icon('heroicon-o-paper-clip')
->schema(FilesBlock::schema()),
Builder\Block::make('person')
->label('Персона')
->icon('heroicon-o-user')
->schema(PersonBlock::schema()),
Builder\Block::make('stepper')
->label('Этапы')
->icon('heroicon-o-list-bullet')
->schema(StepperBlock::schema()),
Builder\Block::make('images')
->label('Слайдер изображений')
->icon('heroicon-o-photo')
->schema(ImagesBlock::schema()),
Builder\Block::make('image')
->label('Изображение')
->icon('heroicon-o-photo')
->schema(ImagesBlock::schema()),
Builder\Block::make('video')
->label('Видео')
->icon('heroicon-o-film')
->schema(VideoBlock::schema()),
Builder\Block::make('postsList')
->label('Список новостей')
->icon('heroicon-o-newspaper')
->schema(PostListBlock::schema()),
Builder\Block::make('postItem')
->label('Конкретная новость')
->icon('heroicon-o-document-text')
->schema(PostItemBlock::schema()),
Builder\Block::make('pageItem')
->label('Конкретная страница')
->icon('heroicon-o-document')
->schema(PageItemBlock::schema()),
Builder\Block::make('customForm')
->label('Пользовательская форма')
->icon('heroicon-o-clipboard-document-list')
->schema(CustomFormBlock::schema()),
Builder\Block::make('pageResourceList')
->label('Ресурсы')
->icon('heroicon-o-archive-box')
->schema(PageResourceListBlock::schema()),
Builder\Block::make('contact')
->label('Контакты')
->icon('heroicon-o-phone')
->schema(ContactBlock::schema()),
Builder\Block::make('slider')
->label('Слайдер')
->icon('heroicon-o-presentation-chart-line')
->schema(SliderBlock::schema()),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок')
->cloneable()
->reorderableWithButtons(),
])
->minItems(1)
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title'] ?? null),
];
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Filament\Components\Forms\ItemForm\Blocks;
use App\Filament\Components\Forms\ItemForm\Blocks\BlockSchema;
use App\Helpers\ByteConverter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class VideoBlock implements BlockSchema
{
public static function schema(): array
{
return [
TextInput::make('mime')
->label('Тип видео')
->readOnly()
->helperText('Определяется автоматически'),
TextInput::make('title')
->label('Название видео')
->placeholder('Введите название видео')
->required()
->maxLength(255)
->autofocus()
->helperText('Это название будет отображаться перед видео'),
FileUpload::make('path')
->label('Видеофайл')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->helperText('Поддерживаются популярные видеоформаты (MP4, MOV, AVI и др.)')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
];
}
}
@@ -16,9 +16,11 @@ use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
@@ -29,23 +31,44 @@ use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
class FormBuilderItem
{
public static function getItem()
public static function getItem(): Builder
{
return Builder::make('columns')
->label('Конструктор полей формы')
->addActionLabel('Добавить новое поле')
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->collapsed()
->collapsible()
->cloneable()
->schema([
// Email поле
Builder\Block::make('email')
->label('Почта')
->icon('heroicon-o-envelope')
->label('Поле Email')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Ваш Email')
->helperText('Это название будет отображаться пользователям')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Введите действующий email')
->helperText('Необязательное пояснение для пользователей')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
@@ -54,18 +77,34 @@ class FormBuilderItem
RuleLengthLimitComponent::getComponent(),
]),
]),
// Phone поле
Builder\Block::make('phone')
->label('Телефон')
->icon('heroicon-o-phone')
->label('Поле Телефона')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Ваш телефон')
->helperText('Укажите контактный номер для связи')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: +7 (XXX) XXX-XX-XX')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
@@ -73,73 +112,135 @@ class FormBuilderItem
RuleLengthLimitComponent::getComponent(),
]),
]),
// Короткий текст
Builder\Block::make('text')
->icon('heroicon-o-pencil')
->label('Короткий текст')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Ваше имя')
->helperText('Краткий текст (до 255 символов)')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
RuleLengthLimitComponent::getComponent(),
]),
]),
Builder\Block::make('textarea')
->label('Длинный текст текст')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Введите ваше полное имя')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
RuleLengthLimitComponent::getComponent(),
]),
]),
// Длинный текст
Builder\Block::make('textarea')
->icon('heroicon-o-document-text')
->label('Длинный текст')
->schema([
TextInput::make('title_field')
->label('Название поля')
->placeholder('Например: Ваш комментарий')
->helperText('Расширенный текст (до 5000 символов)')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Опишите вашу проблему подробно')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
RuleLengthLimitComponent::getComponent(),
]),
]),
// Дата
Builder\Block::make('date')
->icon('heroicon-o-calendar')
->label('Дата')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Дата рождения')
->helperText('Выбор даты из календаря')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Укажите вашу дату рождения')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
]),
]),
// Ссылка
Builder\Block::make('url')
->icon('heroicon-o-link')
->label('Ссылка')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Ваш сайт')
->helperText('Введите корректный URL адрес')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: https://example.com')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
@@ -147,140 +248,178 @@ class FormBuilderItem
RuleLengthLimitComponent::getComponent(),
]),
]),
// Множественный выбор
Builder\Block::make('multiple_choice')
->label('Несколько вариантов')
->icon('heroicon-o-check-circle')
->label('Множественный выбор')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название группы')
->placeholder('Например: Ваши интересы')
->helperText('Несколько вариантов с возможностью выбора')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(), Forms\Components\Repeater::make('columns')->schema([
TextInput::make('title_field')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
])->collapsed(),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Repeater::make('columns')
->label('Варианты выбора')
->addActionLabel('Добавить вариант')
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title_field'] ?? 'Новый вариант')
->schema([
TextInput::make('title_field')
->label('Текст варианта')
->placeholder('Например: Спорт')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Описание варианта')
->placeholder('Необязательное описание')
->maxLength(500),
]),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
]),
]),
// Одиночный выбор
Builder\Block::make('single_choice')
->label('Один вариант')
->icon('heroicon-o-radio')
->label('Одиночный выбор')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название группы')
->placeholder('Например: Ваш пол')
->helperText('Один вариант из предложенных')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(), Forms\Components\Repeater::make('columns')->schema([
TextInput::make('title_field')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
])->collapsed(),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Repeater::make('columns')
->label('Варианты выбора')
->addActionLabel('Добавить вариант')
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title_field'] ?? 'Новый вариант')
->schema([
TextInput::make('title_field')
->label('Текст варианта')
->placeholder('Например: Мужской')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Описание варианта')
->placeholder('Необязательное описание')
->maxLength(500),
]),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
]),
]),
]),
// Дополнительное образование
Builder\Block::make('additional_education_choice')
->label('Выбрать дополнительное образование')
->icon('heroicon-o-academic-cap')
->label('Доп. образование')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Дополнительное образование')
->helperText('Выбор из списка доп. образования')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Выберите интересующую программу')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
// RuleRequiredComponent::getComponent(),
// RuleLengthLimitComponent::getComponent(),
]),
->schema([]),
])
->maxItems(1),
// Образовательная программа
Builder\Block::make('educational_program_choice')
->label('Выбрать Образовательную программу')
->icon('heroicon-o-book-open')
->label('Образовательная программа')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->label('Название поля')
->placeholder('Например: Основная программа')
->helperText('Выбор из списка образовательных программ')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
$set('name_field', Str::slug($state) . Carbon::now()->timestamp);
}),
Forms\Components\Hidden::make('name_field')->required(),
Forms\Components\Textarea::make('description')->label('Описание поля (опционально)'),
Section::make('Настройка')
Hidden::make('name_field')->required(),
Textarea::make('description')
->label('Подсказка для поля')
->placeholder('Например: Выберите основную программу обучения')
->maxLength(500)
->columnSpanFull(),
Section::make('Дополнительные настройки')
->collapsible()
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent(),
RuleLengthLimitComponent::getComponent(),
]),
])
->maxItems(1),
Builder\Block::make('captcha')
->label('reCaptcha')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->live(onBlur: true)
->default('Капча')
->disabled(true)
->dehydrated(true),
Forms\Components\Hidden::make('name_field')->required()->default(Str::slug('reCaptcha') . Carbon::now()->timestamp),
Section::make('Настройка')
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent()->default(true),
]),
]),
Builder\Block::make('personal_data')
->label('Соглашение на обработку персональных данных')
->schema([
TextInput::make('title_field')
->label('Заголовок поля')
->live(onBlur: true)
->default('Соглашение на обработку персональных данных')
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('name_field', Str::slug($state) . Carbon::now()->timestamp );
}),
Forms\Components\Hidden::make('name_field')->required()->default(Str::slug('Соглашение на обработку персональных данных') . Carbon::now()->timestamp),
Section::make('Настройка')
->collapsed()
->statePath('rules')
->schema([
RuleRequiredComponent::getComponent()->default(true),
]),
]),
])
->label('')
->addActionLabel('Добавить поле')
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->collapsed();
->maxItems(1)
]);
}
}
@@ -13,10 +13,13 @@ use App\Models\Post;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
@@ -29,202 +32,347 @@ class ContentBuilderItem
{
public static function getItem(string $name)
{
return
Builder::make($name)->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
return Builder::make($name)
->label('Конструктор содержимого')
->blocks([
// Заголовок
Builder\Block::make('heading')
->icon('heroicon-o-title')
->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('id')
->hidden()
->integer()
->default(rand(2335235, 324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
->label('Текст заголовка')
->placeholder('Введите заголовок H2-H4')
->hint('Рекомендуется 50-80 символов')
->helperText('Используйте для семантической структуры')
->minLength(10)
->maxLength(120)
->required()
->live(onBlur: true),
]),
// Текстовый блок
Builder\Block::make('paragraph')
->icon('heroicon-o-document-text')
->label('Текстовый блок')
->schema([
TinyEditor::make('content')
->label('')
->profile('test')
->required(),
])->label('Текст'),
Builder\Block::make('files')
->label('Файл(-ы)')
->schema([
Forms\Components\Repeater::make('file')->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
]),
->label('Содержимое')
->placeholder('Введите текст...')
->hint('Поддерживается форматирование')
->helperText('Для заголовков используйте стили H3-H4')
->required()
->columnSpanFull(),
]),
// Файлы
Builder\Block::make('files')
->icon('heroicon-o-paper-clip')
->label('Файлы для скачивания')
->schema([
Repeater::make('file')
->label('')
->hint('Максимум 10 файлов')
->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->label('Название файла')
->placeholder('Годовой отчет 2023.pdf')
->required()
->maxLength(255),
FileUpload::make('path')
->label('Выберите файл')
->helperText('Допустимы: PDF, DOCX, XLSX, PPTX, ZIP')
->hint('Макс. размер 500KB')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->preserveFilenames()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
}),
])
->maxItems(10)
->collapsible()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Новый файл'),
]),
// Карточка персоны
Builder\Block::make('person')
->label('Персона')
->icon('heroicon-o-user')
->label('Карточка сотрудника')
->schema([
TextInput::make('name')
->label('Имя')
->label('ФИО')
->placeholder('Иванов Иван Иванович')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->hint('Оптимальный размер 500x500px')
->helperText('Автоматическая конвертация в WebP')
->image()
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
->directory('personnel')
->imageEditor()
->required(),
Repeater::make('info')
->label('Характеристики')
->hint('Добавьте 3-5 ключевых пунктов')
->schema([
TextInput::make('column')
->label('Название колонки')
->label('Параметр')
->placeholder('Стаж работы')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->label('Содержание')
->maxLength(100),
Textarea::make('content')
->label('Значение')
->placeholder('10 лет')
->required()
->maxLength(1000),
])->minItems(1)->label('Информация о персоне'),
->maxLength(500),
])
->minItems(1)
->maxItems(10)
->collapsible()
->itemLabel(fn (array $state): string => $state['column'] ?? 'Новый параметр'),
]),
// Этапы
Builder\Block::make('stepper')
->label('Строитель этапов')
->icon('heroicon-o-list-bullet')
->label('Пошаговый процесс')
->schema([
TextInput::make('step_name')
->label('Название шага')
->label('Название процесса')
->placeholder('Процесс согласования')
->required()
->maxLength(100),
Repeater::make('steps')
->label('Этапы')
->hint('Добавьте последовательные шаги')
->schema([
TextInput::make('title')
->label('Шаг')
->placeholder('1. Подготовка документов')
->required()
->maxLength(100),
RichEditor::make('content')
->label('Описание')
->required()
->maxLength(2000),
])
->minItems(2)
->collapsible()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Новый этап'),
]),
// Табы
Builder\Block::make('tabs')
->icon('heroicon-o-rectangle-stack')
->label('Табы')
->schema([
Repeater::make('tabs')
->label('')
->hint('Оптимально 3-5 вкладок')
->schema([
TextInput::make('title')
->label('Название вкладки')
->placeholder('Характеристики')
->required()
->maxLength(50),
RichEditor::make('content')
->label('Содержимое')
->required(),
])
->minItems(2)
->maxItems(8)
->collapsible()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Новая вкладка'),
]),
// Слайдер изображений
Builder\Block::make('images')
->icon('heroicon-o-photo')
->label('Галерея изображений')
->schema([
FileUpload::make('url')
->label('Изображения')
->hint('Оптимально 3-5 изображений')
->helperText('Поддерживаются JPG, PNG, WEBP')
->image()
->multiple()
->reorderable()
->minFiles(1)
->maxFiles(10)
->disk('public')
->directory('gallery')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание для SEO')
->placeholder('Наш офис в Москве')
->hint('Краткое описание изображения')
->maxLength(255),
]),
// Одиночное изображение
Builder\Block::make('image')
->icon('heroicon-o-photo')
->label('Изображение')
->schema([
FileUpload::make('url')
->label('Выберите изображение')
->helperText('Рекомендуемое соотношение 16:9')
->image()
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('ALT-текст')
->placeholder('Описание изображения')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
TabBuilderItem::getItem(),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
// Видео
Builder\Block::make('video')
->label('Видео (Не стабильно)')
->icon('heroicon-o-film')
->label('Видео')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('mime')
->label('Формат')
->readOnly(),
TextInput::make('title')
->label('Название видео')
->placeholder('Обзор продукта')
->required()
->maxLength(255)
->autofocus(),
->maxLength(255),
FileUpload::make('path')
->label('Видеофайл')
->hint('MP4, WebM, до 50MB')
->helperText('Рекомендуемое разрешение 1080p')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->maxSize(51200)
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
->directory('videos'),
]),
// Список новостей
Builder\Block::make('postsList')
->icon('heroicon-o-newspaper')
->label('Лента новостей')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
Grid::make(2)
->schema([
TextInput::make('count')
->label('Количество')
->numeric()
->minValue(1)
->maxValue(20)
->default(5)
->required(),
Select::make('category')
->label('Категория')
->options(Category::all()->pluck('title', 'id'))
->searchable()
->placeholder('Все категории'),
]),
]),
// Отдельная новость
Builder\Block::make('postItem')
->icon('heroicon-o-document-text')
->label('Конкретная новость')
->schema([
Select::make('post')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->label('Выберите новость')
->options(Post::published()->pluck('title', 'id'))
->searchable()
->required(),
])->label('Новость'),
->required()
->placeholder('Начните вводить название'),
]),
// Страница
Builder\Block::make('pageItem')
->icon('heroicon-o-document')
->label('Ссылка на страницу')
->schema([
Select::make('page')
->options(Page::query()->where('title', '!=' , null)->where('is_visible', true)->pluck('title', 'id'))
->label('Страница')
->options(Page::visible()->pluck('title', 'id'))
->searchable()
->required(),
])->label('Страница'),
]),
// Форма
Builder\Block::make('customForm')
->icon('heroicon-o-clipboard-document')
->label('Форма')
->schema([
Select::make('form')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->label('Выберите форму')
->options(CustomForm::published()->pluck('title', 'form_id'))
->searchable()
->required(),
])->label('Форма'),
]),
// Ресурсы
Builder\Block::make('pageResourceList')
->icon('heroicon-o-archive-box')
->label('Список ресурсов')
->schema([
Select::make('resource')
->options(PageReferenceList::query()->where('is_active', true)->pluck('title', 'slug'))
->label('Ресурс')
->options(PageReferenceList::active()->pluck('title', 'slug'))
->searchable()
->required(),
])->label('Ресурсы'),
]),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок');
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить блок')
->addBetweenActionLabel('Вставить блок между')
->cloneActionLabel('Клонировать блок');
}
@@ -6,10 +6,12 @@ use App\Enums\CustomFormStatus;
use App\Enums\PostStatus;
use App\Helpers\ByteConverter;
use App\Models\Category;
use App\Models\ContactWidget;
use App\Models\CustomForm;
use App\Models\Page;
use App\Models\PageReferenceList;
use App\Models\Post;
use App\Models\Slider;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\FileUpload;
@@ -29,210 +31,356 @@ class TabBuilderItem
{
public static function getItem()
{
return
Builder\Block::make('tabs')
->label('Вкладки')
->schema([
Forms\Components\Repeater::make('tab')->schema([
TextInput::make('title')
return Builder::make('content')
->label('Содержимое вкладки')
->blocks([
Builder\Block::make('heading')
->label('Заголовок')
->icon('heroicon-o-hashtag')
->schema([
TextInput::make('id')
->hidden()
->integer()
->default(rand(2335235, 324634264263426)),
TextInput::make('content')
->label('Текст заголовка')
->placeholder('Введите текст заголовка')
->helperText('Основной заголовок раздела')
->live(onBlur: true)
->required()
->maxLength(255)->columnSpanFull(),
Builder::make('content')->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
]),
Builder\Block::make('paragraph')
->schema([
TinyEditor::make('content')
->label('')
->profile('test')
->required(),
])->label('Текст'),
Builder\Block::make('files')
->label('Файл(-ы)')
->schema([
Forms\Components\Repeater::make('file')->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
]),
]),
Builder\Block::make('person')
->label('Персона')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
TextInput::make('column')
->label('Название колонки')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->label('Содержание')
->required()
->maxLength(1000),
])->minItems(1)->label('Информация о персоне'),
]),
Builder\Block::make('stepper')
->label('Строитель этапов')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
Builder\Block::make('video')
->label('Видео (Не стабильно)')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
Builder\Block::make('postItem')
->schema([
Select::make('post')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Новость'),
Builder\Block::make('pageItem')
->schema([
Select::make('page')
->options(Page::query()->where('title', '!=' , null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Страница'),
Builder\Block::make('customForm')
->schema([
Select::make('form')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required(),
])->label('Форма'),
Builder\Block::make('pageResourceList')
->schema([
Select::make('resource')
->options(PageReferenceList::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required(),
])->label('Ресурсы'),
])
->collapsed()
->blockNumbers(false)
->maxLength(255),
]),
Builder\Block::make('paragraph')
->label('Текст')
->icon('heroicon-o-document-text')
->schema([
Toggle::make('seo_active')
->label('Использовать блок как SEO-текст')
->helperText('Этот текст будет использоваться для SEO-оптимизации')
->live(onBlur: true)
->required()
->disabled(function ($state, Forms\Get $get) {
$data = $get('../../');
return self::findSeoActive($data) && !$state;
})
->dehydrated(),
TinyEditor::make('content')
->label('Текст')
->placeholder('Начните вводить текст...')
->profile('test')
->required()
->helperText('Основное текстовое содержимое блока'),
]),
Builder\Block::make('files')
->label('Файлы')
->icon('heroicon-o-paper-clip')
->schema([
Forms\Components\Repeater::make('file')
->label('Файлы')
->helperText('Загрузите один или несколько файлов')
->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->label('Название файла')
->placeholder('Введите название файла')
->required()
->maxLength(255)
->autofocus()
->helperText('Это название будет отображаться пользователям'),
FileUpload::make('path')
->label('Файл')
->required()
->helperText('Поддерживаются PDF, Word, Excel, PowerPoint и ZIP файлы (макс. 500KB)')
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
->preserveFilenames()
])
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок'),
])->minItems(1),
]);
->cloneable()
->grid(2),
]),
Builder\Block::make('person')
->label('Персона')
->icon('heroicon-o-user')
->schema([
TextInput::make('name')
->label('Имя персоны')
->placeholder('Введите имя')
->required()
->maxLength(255)
->helperText('Полное имя персоны'),
FileUpload::make('photo')
->label('Фотография')
->image()
->helperText('Рекомендуемый формат: WebP')
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor()
->required()
->downloadable()
->openable(),
Forms\Components\Repeater::make('info')
->label('Дополнительная информация')
->helperText('Добавьте характеристики персоны')
->schema([
TextInput::make('column')
->label('Название характеристики')
->placeholder('Например: Должность')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->label('Значение')
->placeholder('Например: Главный инженер')
->required()
->maxLength(1000)
->columnSpanFull(),
])
->minItems(1)
->grid(2)
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['column'] ?? null),
]),
Builder\Block::make('stepper')
->label('Этапы')
->icon('heroicon-o-list-bullet')
->schema([
TextInput::make('step_name')
->label('Название процесса')
->placeholder('Например: Процесс оформления')
->required()
->maxLength(255)
->helperText('Общее название для всех шагов'),
Forms\Components\Repeater::make('steps')
->label('Шаги')
->helperText('Добавьте шаги процесса')
->schema([
TextInput::make('title')
->label('Название шага')
->placeholder('Например: Шаг 1')
->required()
->maxLength(255)
->columnSpanFull(),
RichEditor::make('content')
->label('Описание шага')
->required()
->toolbarButtons([
'bold',
'italic',
'link',
'orderedList',
'bulletList',
]),
])
->minItems(1)
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title'] ?? null),
]),
Builder\Block::make('images')
->label('Слайдер изображений')
->icon('heroicon-o-photo')
->schema([
FileUpload::make('url')
->label('Изображения')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required()
->helperText('Максимум 5 изображений. Можно перетаскивать для изменения порядка'),
TextInput::make('alt')
->label('Описание изображений')
->placeholder('Необязательно')
->helperText('Используется для SEO и доступности'),
]),
Builder\Block::make('image')
->label('Изображение')
->icon('heroicon-o-photo')
->schema([
FileUpload::make('url')
->label('Изображение')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required()
->helperText('Можно загрузить до 5 изображений'),
TextInput::make('alt')
->label('Альтернативный текст')
->placeholder('Необязательно')
->helperText('Описание изображения для SEO'),
]),
Builder\Block::make('video')
->label('Видео')
->icon('heroicon-o-film')
->schema([
TextInput::make('mime')
->label('Тип видео')
->readOnly()
->helperText('Определяется автоматически'),
TextInput::make('title')
->label('Название видео')
->placeholder('Введите название видео')
->required()
->maxLength(255)
->autofocus()
->helperText('Это название будет отображаться перед видео'),
FileUpload::make('path')
->label('Видеофайл')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->helperText('Поддерживаются популярные видеоформаты (MP4, MOV, AVI и др.)')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->label('Список новостей')
->icon('heroicon-o-newspaper')
->schema([
Forms\Components\Grid::make(2)
->schema([
TextInput::make('count')
->label('Количество записей')
->integer()
->minValue(1)
->maxValue(20)
->default(5)
->helperText('От 1 до 20 записей'),
Select::make('category')
->label('Категория')
->options(Category::all()->pluck('title', 'id'))
->searchable()
->helperText('Выберите категорию или оставьте пустым для всех'),
]),
]),
Builder\Block::make('postItem')
->label('Конкретная новость')
->icon('heroicon-o-document-text')
->schema([
Select::make('post')
->label('Новость')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required()
->helperText('Выберите опубликованную новость'),
]),
Builder\Block::make('pageItem')
->label('Конкретная страница')
->icon('heroicon-o-document')
->schema([
Select::make('page')
->label('Страница')
->options(Page::query()->where('title', '!=', null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required()
->helperText('Выберите видимую страницу'),
]),
Builder\Block::make('customForm')
->label('Пользовательская форма')
->icon('heroicon-o-clipboard-document-list')
->schema([
Select::make('form')
->label('Форма')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required()
->helperText('Выберите опубликованную форму'),
]),
Builder\Block::make('pageResourceList')
->label('Ресурсы')
->icon('heroicon-o-archive-box')
->schema([
Select::make('resource')
->label('Ресурс')
->options(PageReferenceList::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный ресурс'),
]),
Builder\Block::make('contact')
->label('Контакты')
->icon('heroicon-o-phone')
->schema([
Select::make('contact')
->label('Виджет контактов')
->options(ContactWidget::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный виджет контактов'),
]),
Builder\Block::make('slider')
->label('Слайдер')
->icon('heroicon-o-presentation-chart-line')
->schema([
Select::make('slider')
->label('Слайдер')
->options(Slider::query()->whereHas('slides')->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required()
->helperText('Выберите активный слайдер с изображениями'),
]),
])
->collapsed()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->blockNumbers(false)
->collapsible()
->addActionLabel('Добавить блок в вкладку');
}
@@ -4,6 +4,22 @@ namespace App\Filament\Components\Forms\ItemForm\Pages;
use App\Enums\CustomFormStatus;
use App\Enums\PostStatus;
use App\Filament\Components\Forms\ItemForm\Blocks\ContactBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\CustomFormBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\FilesBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\HeadingBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\ImagesBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\PageItemBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\PageResourceListBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\ParagraphBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\PersonBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\PostItemBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\PostListBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\SliderBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\StepperBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\TabBlock;
use App\Filament\Components\Forms\ItemForm\Blocks\VideoBlock;
use App\Filament\Components\Forms\ItemForm\Defaults\TabBuilderItem;
use App\Helpers\ByteConverter;
use App\Models\Category;
use App\Models\ContactWidget;
@@ -14,6 +30,7 @@ use App\Models\Post;
use App\Models\Slider;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Fieldset;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor;
@@ -29,407 +46,99 @@ use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
class ContentBuilderItem
{
private static function findSeoActive(array $data) : bool
public static function getItem(string $name): Builder
{
$bool = false;
return Builder::make($name)
->label('')
->blocks([
Builder\Block::make('heading')
->label('Заголовок')
->icon('heroicon-o-hashtag')
->schema(HeadingBlock::schema()),
foreach ($data as $item) {
if ($item['type'] !== 'paragraph') {
continue;
}
if ($item['data']['seo_active'] === true) {
$bool = true;
break;
}
}
return $bool;
}
public static function getItem(string $name)
{
return
Builder::make($name)->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
]),
Builder\Block::make('paragraph')
->schema([
Toggle::make('seo_active')->label('Использовать блок как seo')
->live(onBlur: true)
->required()
->disabled(function ($state, Forms\Get $get) {
$data = $get('../../');
return self::findSeoActive($data) && !$state;
})
->dehydrated(),
TinyEditor::make('content')
->label('')
->profile('test')
->required(),
])->label('Текст'),
->label('Текст')
->icon('heroicon-o-document-text')
->schema(ParagraphBlock::schema()),
Builder\Block::make('files')
->label('Файл(-ы)')
->schema([
Forms\Components\Repeater::make('file')->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
]),
]),
->label('Файлы')
->icon('heroicon-o-paper-clip')
->schema(FilesBlock::schema()),
Builder\Block::make('person')
->label('Персона')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
TextInput::make('column')
->label('Название колонки')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->label('Содержание')
->required()
->maxLength(1000),
])->minItems(1)->label('Информация о персоне'),
]),
->icon('heroicon-o-user')
->schema(PersonBlock::schema()),
Builder\Block::make('stepper')
->label('Строитель этапов')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
->label('Этапы')
->icon('heroicon-o-list-bullet')
->schema(StepperBlock::schema()),
Builder\Block::make('tabs')
->label('Вкладки')
->schema([
Forms\Components\Repeater::make('tab')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
\Filament\Forms\Components\Builder::make('content')->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
]),
Builder\Block::make('paragraph')
->schema([
RichEditor::make('content')
->toolbarButtons([
'blockquote',
'bold',
'bulletList',
'italic',
'link',
'orderedList',
'redo',
'strike',
'underline',
'undo',
])
->label(''),
])->label('Текст'),
Builder\Block::make('files')
->schema([
Forms\Components\Repeater::make('file')->schema([
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->visibility('public')
]),
]),
Builder\Block::make('person')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('column')
->required()
->maxLength(255),
TextInput::make('content')
->required()
->maxLength(255),
]),
])->minItems(1),
]),
Builder\Block::make('stepper')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
Builder\Block::make('video')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->addActionLabel('Добавить новый блок'),
])->minItems(1),
]),
->icon('heroicon-o-rectangle-stack')
->schema(TabBlock::schema()),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
->label('Слайдер изображений')
->icon('heroicon-o-photo')
->schema(ImagesBlock::schema()),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
->label('Изображение')
->icon('heroicon-o-photo')
->schema(ImagesBlock::schema()),
Builder\Block::make('video')
->label('Видео (Не стабильно)')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
->label('Видео')
->icon('heroicon-o-film')
->schema(VideoBlock::schema()),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
->label('Список новостей')
->icon('heroicon-o-newspaper')
->schema(PostListBlock::schema()),
Builder\Block::make('postItem')
->schema([
Select::make('post')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Новость'),
->label('Конкретная новость')
->icon('heroicon-o-document-text')
->schema(PostItemBlock::schema()),
Builder\Block::make('pageItem')
->schema([
Select::make('page')
->options(Page::query()->where('title', '!=' , null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Страница'),
->label('Конкретная страница')
->icon('heroicon-o-document')
->schema(PageItemBlock::schema()),
Builder\Block::make('customForm')
->schema([
Select::make('form')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required(),
])->label('Форма'),
->label('Пользовательская форма')
->icon('heroicon-o-clipboard-document-list')
->schema(CustomFormBlock::schema()),
Builder\Block::make('pageResourceList')
->schema([
Select::make('resource')
->options(PageReferenceList::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required(),
])->label('Ресурсы'),
->label('Ресурсы')
->icon('heroicon-o-archive-box')
->schema(PageResourceListBlock::schema()),
Builder\Block::make('contact')
->schema([
Select::make('contact')
->options(ContactWidget::query()->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required(),
])->label('Контакты'),
->label('Контакты')
->icon('heroicon-o-phone')
->schema(ContactBlock::schema()),
Builder\Block::make('slider')
->schema([
Select::make('slider')
->options(Slider::query()->whereHas('slides')->where('is_active', true)->pluck('title', 'slug'))
->searchable()
->required(),
])->label('Слайдеры'),
->label('Слайдер')
->icon('heroicon-o-presentation-chart-line')
->schema(SliderBlock::schema()),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок');
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок')
->cloneable()
->reorderableWithButtons();
}
+122 -61
View File
@@ -6,6 +6,7 @@ use App\Enums\CustomFormStatus;
use App\Enums\PostStatus;
use App\Filament\Components\Forms\ItemForm\Pages\ContentBuilderItem;
use Filament\Forms;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
@@ -22,69 +23,129 @@ class PageForm
->schema([
Section::make()
->schema([
Forms\Components\Tabs::make('')->schema([
Forms\Components\Tabs\Tab::make('Основная информация')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('title')->label('Заголовок')->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('slug', Str::slug($state));
$set('path', Str::slug($state));
}),
TextInput::make('slug')->label('Текстовый идентификатор страницы')->unique(ignoreRecord: true)->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
$set('path', Str::slug($state));
}),
]),
Select::make('sub_section_id')->label('Подраздел')
->relationship('section', 'title')
->createOptionForm([
Forms\Components\TextInput::make('title')->label('Название подраздела')->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('slug', Str::slug($state));
}),
TextInput::make('slug')->label('Slug')->unique(ignoreRecord: true)->readOnly()->required(),
Forms\Components\Tabs::make('Настройки страницы')
->persistTabInQueryString()
->columnSpanFull()
->tabs([
Forms\Components\Tabs\Tab::make('Основная информация')
->icon('heroicon-o-information-circle')
->schema([
Forms\Components\Grid::make(2)
->schema([
TextInput::make('title')
->label('Заголовок страницы')
->required()
->maxLength(255)
->placeholder('Введите название страницы')
->helperText('Этот заголовок будет отображаться в заголовке страницы и в навигации')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('slug', Str::slug($state));
$set('path', Str::slug($state));
}),
TextInput::make('slug')
->label('URL-адрес страницы')
->required()
->unique(ignoreRecord: true)
->maxLength(255)
->helperText('Человеко-понятный URL для страницы')
->placeholder('example-page')
// ->prefix(fn ($record) => url('/') . '/' . substr($record->path, 0, strrpos($record->path, '/')))
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
$set('path', Str::slug($state));
})
->suffixAction(
Action::make('copy')
->icon('heroicon-s-clipboard-document-check')
->action(function ($livewire, $state, $record) {
$livewire->js(
'window.navigator.clipboard.writeText("'. url('/') . '/' . substr($record->path, 0, strrpos($record->path, '/')) . '/' . $state.'");
$tooltip("'.__('Copied to clipboard').'", { timeout: 1500 });'
);
})),
]),
Select::make('sub_section_id')
->label('Родительский подраздел')
->relationship('section', 'title')
->preload()
->searchable()
->placeholder('Выберите подраздел')
->helperText('Выберите раздел, к которому принадлежит эта страница')
->createOptionForm([
Forms\Components\Grid::make(2)
->schema([
Forms\Components\TextInput::make('title')
->label('Название подраздела')
->required()
->maxLength(255)
->placeholder('Введите название подраздела')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('slug', Str::slug($state));
}),
TextInput::make('slug')
->label('URL подраздела')
->unique(ignoreRecord: true)
->readOnly()
->required()
->maxLength(255)
->helperText('Автоматически генерируется из названия'),
]),
]),
Select::make('code')
->label('HTTP статус страницы')
->options([
'200' => 'Обычная страница (200 OK)',
'404' => 'Страница не найдена (404 Not Found)',
'500' => 'Технические работы (500 Server Error)',
])
->required()
->default('200')
->helperText('Выберите HTTP статус, с которым будет отдаваться страница'),
Toggle::make('searchable')
->label('Индексировать в поиске')
->default(true)
->inline(false)
->helperText('Разрешить локальному поиску индексировать страницу'),
IconPicker::make('icon')
->label('Иконка страницы')
->default('heroicon-o-academic-cap')
->helperText('Выберите иконку для отображения в навигации')
->columns(6),
TextInput::make('search_data')
->hidden(),
]),
Forms\Components\Tabs\Tab::make('Содержание')
->icon('heroicon-o-document-text')
->schema([
ContentBuilderItem::getItem('content')
->helperText('Создайте содержимое страницы используя конструктор')
]),
Forms\Components\Tabs\Tab::make('Дополнительные настройки')
->icon('heroicon-o-cog')
->schema([
Section::make('Отображение элементов')
->description('Управление видимостью элементов на странице')
->collapsible()
->schema([
Toggle::make('settings.hide_page_sub_section_links')
->label('Скрыть боковую панель с ссылками на страницы раздела')
->helperText('Скрывает список страниц текущего раздела')
->columnSpan(1),
Toggle::make('settings.hide_page_navigate_links')
->label('Скрыть навигацию по странице')
->helperText('Скрывает навигацию по заголовкам')
->columnSpan(1),
Toggle::make('settings.hide_breadcrumbs')
->label('Скрыть хлебные крошки')
->helperText('Скрывает навигационную цепочку вверху страницы')
->columnSpan(1),
])
->columns(2),
]),
Select::make('code')->options([
'200' => 'Открытая страница',
'404' => 'Не найдено',
'500' => 'Ведутся технические работы',
])->label('Статус')->required()->default('200'),
Toggle::make('searchable')->default(true)->label('Индексируется поиском')->inline(false),
IconPicker::make('icon')
->default('heroicon-o-academic-cap')
->label('Icon'),
TextInput::make('search_data')->hidden(),
]),
Forms\Components\Tabs\Tab::make('Контент')->schema([
ContentBuilderItem::getItem('content')
]),
Forms\Components\Tabs\Tab::make('Настройки')->schema([
Section::make()->schema([
Toggle::make('settings.hide_page_sub_section_links')
->label('Скрыть сайдбар смежных страниц')
->columnSpan(1),
Toggle::make('settings.hide_page_navigate_links')
->label('Скрыть навигацию по страницу')
->columnSpan(1),
Toggle::make('settings.hide_breadcrumbs')
->label('Скрыть хлебные крошки')
->columnSpan(1),
//
// Toggle::make('settings.full_width_page')
// ->label('Страница на всю ширину')
// ->columnSpan(1)->default(true),
]),
]),
]),
])
]);
}
+210 -102
View File
@@ -11,6 +11,7 @@ use App\Models\CustomForm;
use App\Models\Page;
use App\Models\PageReferenceList;
use App\Models\Post;
use App\Models\Slider;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\ColorPicker;
@@ -38,8 +39,6 @@ use Symfony\Component\Finder\Finder;
class PostForm
{
public static function getForm(Form $form): Form
{
return $form
@@ -49,155 +48,264 @@ class PostForm
Tabs::make('Tabs')
->tabs([
Tabs\Tab::make('Основная информация')
->icon('heroicon-o-information-circle')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('title')->label('Заголовок')->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('slug', Str::slug($state));
$set('seo.title', $state);
}),
TextInput::make('slug')->label('Slug')->unique(ignoreRecord: true)->readOnly()->required(),
]),
Select::make('status')->options(PostStatus::class)
->label('Статус')->required()
Grid::make(2)
->schema([
TextInput::make('title')
->label('Заголовок')
->required()
->maxLength(255)
->placeholder('Введите заголовок новости')
->helperText('Этот заголовок будет отображаться на сайте')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('slug', Str::slug($state));
$set('seo.title', $state);
}),
TextInput::make('slug')
->label('URL-адрес')
->unique(ignoreRecord: true)
->readOnly()
->required()
->helperText('Этот URL будет использоваться для страницы новости')
->maxLength(255),
]),
Select::make('status')
->label('Статус публикации')
->options(PostStatus::class)
->required()
->default(PostStatus::VERIFICATION)
->helperText('Выберите статус публикации новости')
->disableOptionWhen(fn (string $value): bool =>
$value == PostStatus::PUBLISHED->value && !auth()->user()->can('publish_post')
)
->default(PostStatus::VERIFICATION),
),
Select::make('category_id')
->label('Категория')
->options(Category::all()->pluck('title', 'id'))
->searchable()
->preload()
->label('Категория'),
SpatieTagsInput::make('tags')->label('Тэги'),
->placeholder('Выберите категорию')
->helperText('Выберите категорию для новости'),
SpatieTagsInput::make('tags')
->label('Теги')
->placeholder('Добавьте теги')
->helperText('Добавьте теги для лучшей классификации'),
Forms\Components\TagsInput::make('authors')
->label('Авторы')->placeholder('Добавить автора'),
Section::make('Отложенная публикация')->schema([
Grid::make(2)->schema([
Toggle::make('publish_setting.publish_after')
->label('Включить')
->inline(false)
->default(false)
->live(),
DateTimePicker::make('publish_setting.publish_at')
->label('Дата публикации')
->native()
->displayFormat('d/m/Y')
->required(fn (Forms\Get $get) => $get('publish_setting.publish_after'))
->disabled(fn (Forms\Get $get) => !$get('publish_setting.publish_after'))
->minDate(Carbon::now()->subWeek())
->maxDate(Carbon::now()->addMonth()),
->label('Авторы')
->placeholder('Добавить автора')
->helperText('Укажите авторов новости')
->suggestions([
'Редакция',
'Администратор',
]),
]),
Section::make('Публикация в сервисах')->schema([
Forms\Components\Grid::make()->schema([
Toggle::make('publication.vk')->label('Публикация в VK')->default(true),
Toggle::make('publication.telegram')->label('Публикация в Telegram')->default(true),
Section::make('Отложенная публикация')
->description('Настройте автоматическую публикацию новости в указанное время')
->collapsible()
->schema([
Grid::make(2)
->schema([
Toggle::make('publish_setting.publish_after')
->label('Включить отложенную публикацию')
->inline(false)
->default(false)
->live()
->helperText('Активируйте для публикации в указанное время'),
DateTimePicker::make('publish_setting.publish_at')
->label('Дата и время публикации')
->native(false)
->displayFormat('d/m/Y H:i')
->seconds(false)
->minutesStep(15)
->helperText('Выберите дату и время публикации')
->required(fn (Forms\Get $get) => $get('publish_setting.publish_after'))
->disabled(fn (Forms\Get $get) => !$get('publish_setting.publish_after'))
->minDate(now())
->maxDate(now()->addMonth()),
]),
]),
Section::make('Публикация в соцсетях')
->description('Управление автоматической публикацией в социальных сетях')
->collapsible()
->schema([
Grid::make()
->schema([
Toggle::make('publication.vk')
->label('Опубликовать в VK')
->default(true)
->helperText('Новость будет автоматически опубликована в VK'),
Toggle::make('publication.telegram')
->label('Опубликовать в Telegram')
->default(true)
->helperText('Новость будет автоматически опубликована в Telegram'),
]),
]),
]),
]),
Tabs\Tab::make('Содержание новости')
Tabs\Tab::make('Содержание')
->icon('heroicon-o-document-text')
->schema([
ContentBuilderItem::getItem('content')->required(),
ContentBuilderItem::getItem('content')
->required()
->helperText('Создайте содержимое новости используя конструктор'),
]),
Tabs\Tab::make('Изображения')
Tabs\Tab::make('Медиа')
->icon('heroicon-o-photo')
->schema([
FileUpload::make('preview')->label('Превью новости')
FileUpload::make('preview')
->label('Главное изображение')
->image()
->directory('posts/previews')
->optimize('webp')
->resize(50)
->imageEditor()
->directory('images'),
FileUpload::make('images')->label('Альбом')
->helperText('Загрузите главное изображение для новости')
->maxSize(2048)
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->imagePreviewHeight('150')
->panelLayout('integrated'),
FileUpload::make('images')
->label('Галерея изображений')
->image()
->directory('posts/gallery')
->optimize('jpg')
->resize(30)
->imageEditor()
->panelLayout('grid')
->reorderable()
->imageEditor()
->multiple()
->directory('images'),
->reorderable()
->panelLayout('grid')
->helperText('Загрузите дополнительные изображения для галереи')
->maxFiles(10)
->maxSize(2048)
->acceptedFileTypes(['image/jpeg', 'image/png'])
->imagePreviewHeight('150'),
]),
Tabs\Tab::make('Добавление новости в слайдер')
Tabs\Tab::make('Слайдер')
->icon('heroicon-o-view-columns')
->schema([
Toggle::make('is_slider_enabled')
->label('Добавить новый слайд')
->label('Добавить в слайдер')
->live()
->hidden(fn (string $context): bool => $context === 'edit')
->helperText('Активируйте для добавления новости в слайдер')
->hidden(function (Forms\Get $get, string $context) {
if ($context === 'edit') {
return true;
}
return false;
})
->dehydrated(false)
->default(false),
Section::make()
Section::make('Настройки слайда')
->description('Настройте отображение новости в слайдере')
->collapsible()
->collapsed()
->schema([
Forms\Components\Section::make('Информация слайда')->schema([
Forms\Components\TextInput::make('slide.title')
->label('Заголовок слайда'),
Forms\Components\Textarea::make('slide.content')
->label('Текст слайда'),
Forms\Components\Grid::make()->schema([
Select::make('slide.slider_id')
->label('Выберите слайдер')
->options(Slider::where('is_active', true)->pluck('title', 'id'))
->required()
->helperText('Выберите слайдер для размещения'),
TextInput::make('slide.title')
->label('Заголовок слайда')
->maxLength(100)
->helperText('Короткий заголовок для слайда')
->placeholder('Введите заголовок'),
Forms\Components\Textarea::make('slide.content')
->label('Текст слайда')
->maxLength(255)
->helperText('Краткое описание для слайда')
->placeholder('Введите текст слайда'),
Grid::make()
->schema([
ColorPicker::make('slide.color_theme')
->label('Цвет текста')
->default('#ffffff')
->required(),
Forms\Components\ToggleButtons::make('slide.settings.text_position')
->required()
->helperText('Выберите цвет текста на слайде'),
ToggleButtons::make('slide.settings.text_position')
->label('Позиция текста')
->options([
'left' => 'Текст слева',
'center' => 'Текст по середине',
'right' => 'Текст справа'
'left' => 'Слева',
'center' => 'По центру',
'right' => 'Справа',
])
->inline()->default('left')->grouped()
->label('Позиция текста на слайде'),
->inline()
->grouped()
->default('left')
->helperText('Выберите расположение текста на слайде'),
]),
Forms\Components\Grid::make()->schema([
Grid::make()
->schema([
Toggle::make('active_button')
->label('Использовать кнопку для ссылки (Ссылка будет открываться при нажатии на слайд)')
->label('Добавить кнопку')
->inline(false)
->live()
->helperText('Добавить кнопку со ссылкой на новость')
->afterStateHydrated(function (Toggle $component, $state, $get) {
$component->state(true);
})
->dehydrated(false),
Forms\Components\TextInput::make('slide.settings.link_text')
->default('Читать')
TextInput::make('slide.settings.link_text')
->label('Текст кнопки')
->default('Читать')
->maxLength(20)
->disabled(fn (Forms\Get $get) => !$get('active_button'))
->helperText('Текст для кнопки перехода'),
]),
]),
Forms\Components\Section::make('Изображение')->schema([
FileUpload::make('slide.image.url')
->label('Изображение')
->image()
->optimize('webp')
->resize(50)
->disk('public')
->directory('images')
->imageEditor()
->required(),
ToggleButtons::make('slide.image.shading')->inline()->grouped()->label('Уровень затемнения изображения')->options([
'1' => 'Без затемнения',
'0.7' => 'Слабое затемнение',
'0.5' => 'Среднее затемнение',
'0.3' => 'Сильное затемнение',
Section::make('Изображение слайда')
->schema([
FileUpload::make('slide.image.url')
->label('Фоновое изображение')
->image()
->directory('sliders')
->optimize('webp')
->resize(50)
->imageEditor()
->required()
->maxSize(2048)
->helperText('Загрузите фоновое изображение для слайда')
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp']),
ToggleButtons::make('slide.image.shading')
->label('Затемнение фона')
->inline()
->grouped()
->options([
'1' => 'Нет',
'0.7' => 'Слабое',
'0.5' => 'Среднее',
'0.3' => 'Сильное',
])
->helperText('Выберите уровень затемнения фона'),
]),
]),
Forms\Components\Section::make('Общая часть')->schema([
Forms\Components\Grid::make()->schema([
Section::make('Время показа')
->schema([
DateTimePicker::make('slide.end_time')
->label('Слайд действует до')
->native()
->displayFormat('d/m/Y')
->minDate(Carbon::now())
->maxDate(Carbon::now()->addMonth()),
->label('Дата окончания показа')
->native(false)
->displayFormat('d/m/Y H:i')
->minDate(now())
->maxDate(now()->addMonth())
->helperText('Укажите до какого времени слайд будет активен'),
]),
]),
])
->hidden(fn(Forms\Get $get) => !$get('is_slider_enabled'))
]),
]),
])
->hidden(function (Forms\Get $get) {
if ($get('is_slider_enabled') === true) {
return false;
}
if ($get('slide')['slider_id'] !== null) {
return false;
}
return true;
}),
])
->hidden(function (Forms\Get $get, string $context) {
if ($context === 'edit' && $get('slide')['slider_id'] === null) {
return true;
}
return false;
}),
])
->persistTabInQueryString(),
]),
]);
}
}