- Создание
- События
- Состояние по умолчанию
- Клик вне окна
- Автозакрытие
- Ширина
- Асинхронность
- Внешние атрибуты
Создание
Декоратор Modal позволяет создавать модальные окна.
Вы можете создать Modal, используя статический метод make().
make(Closure|string $title,Closure|View|string $content,Closure|View|ActionButton|string $outer = '',Closure|string|null $asyncUrl = '',MoonShineRenderElements|null $components = null)make(Closure|string $title,Closure|View|string $content,Closure|View|ActionButton|string $outer = '',Closure|string|null $asyncUrl = '',MoonShineRenderElements|null $components = null)
$title- заголовок модального окна,$content- содержимое модального окна,$outer- внешний блок с обработчиком вызова окна,$asyncUrl- url для асинхронного контента,$components- компоненты для модального окна.
use MoonShine\ActionButtons\ActionButton;use MoonShine\Components\FormBuilder;use MoonShine\Components\Modal;use MoonShine\Fields\Password;use MoonShine\Pages\PageComponents;//...public function components(): array{return [Modal::make(title: 'Подтвердить',outer: ActionButton::make('Показать модальное окно', '#'),components: PageComponents::make([FormBuilder::make(route('password.confirm'))->async()->fields([Password::make('Пароль')->eye(),])->submit('Подтвердить'),]))];}//...use MoonShine\ActionButtons\ActionButton;use MoonShine\Components\FormBuilder;use MoonShine\Components\Modal;use MoonShine\Fields\Password;use MoonShine\Pages\PageComponents;//...public function components(): array{return [Modal::make(title: 'Подтвердить',outer: ActionButton::make('Показать модальное окно', '#'),components: PageComponents::make([FormBuilder::make(route('password.confirm'))->async()->fields([Password::make('Пароль')->eye(),])->submit('Подтвердить'),]))];}//...
События
Вы можете открывать или закрывать модальное окно, не используя компонент, через события javascript.
Чтобы иметь доступ к событиям, вы должны установить уникальное имя для модального окна, используя метод name().
use MoonShine\ActionButtons\ActionButton;use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок','Содержимое...',)->name('my-modal'),];}//...use MoonShine\ActionButtons\ActionButton;use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок','Содержимое...',)->name('my-modal'),];}//...
вызов события через ActionButton
Событие модального окна может быть вызвано с помощью компонента ActionButton.
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок','Содержимое...',)->name('my-modal'),ActionButton::make('Показать модальное окно','#')->toggleModal('my-modal')// или асинхронноActionButton::make('Показать модальное окно','/endpoint')->async(events: ['modal-toggled-my-modal'])];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок','Содержимое...',)->name('my-modal'),ActionButton::make('Показать модальное окно','#')->toggleModal('my-modal')// или асинхронноActionButton::make('Показать модальное окно','/endpoint')->async(events: ['modal-toggled-my-modal'])];}//...
вызов события с использованием нативных методов
События могут быть вызваны с использованием нативных методов javascript:
document.addEventListener("DOMContentLoaded", () => {this.dispatchEvent(new Event("modal-toggled-my-modal"))})document.addEventListener("DOMContentLoaded", () => {this.dispatchEvent(new Event("modal-toggled-my-modal"))})
вызов события с использованием метода Alpine.js
Или с использованием магического метода $dispatch() из Alpine.js:
this.$dispatch('modal-toggled-my-modal')this.$dispatch('modal-toggled-my-modal')
Состояние по умолчанию
Метод open() позволяет открыть модальное окно при загрузке страницы.
open(Closure|bool|null $condition = null)open(Closure|bool|null $condition = null)
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', view('path'))->open(),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', view('path'))->open(),];}//...
По умолчанию модальное окно останется закрытым при загрузке страницы.
Клик вне окна
По умолчанию модальное окно закрывается при клике вне области окна. Метод closeOutside() позволяет переопределить это поведение.
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->closeOutside(false),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->closeOutside(false),];}//...
Автозакрытие
По умолчанию модальные окна закрываются после успешного запроса. Метод autoClose() позволяет управлять этим поведением.
autoClose(Closure|bool|null $autoClose = null)autoClose(Closure|bool|null $autoClose = null)
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Демо модальное окно',static fn() => FormBuilder::make(route('alert.post'))->fields([Text::make('Текст'),])->submit('Отправить', ['class' => 'btn-primary'])->async(),)->name('demo-modal')->autoClose(false),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Демо модальное окно',static fn() => FormBuilder::make(route('alert.post'))->fields([Text::make('Текст'),])->submit('Отправить', ['class' => 'btn-primary'])->async(),)->name('demo-modal')->autoClose(false),];}//...
Ширина
wide
Метод wide() компонента Modal устанавливает максимальную ширину модального окна.
wide(Closure|bool|null $condition = null)wide(Closure|bool|null $condition = null)
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->wide(),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->wide(),];}//...
auto
Метод auto() компонента Modal устанавливает ширину модального окна на основе содержимого.
auto(Closure|bool|null $condition = null)auto(Closure|bool|null $condition = null)
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->auto(),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->auto(),];}//...
Асинхронность
Modal::make('Заголовок', '', ActionButton::make('Показать модальное окно', '#'), asyncUrl: '/endpoint'),Modal::make('Заголовок', '', ActionButton::make('Показать модальное окно', '#'), asyncUrl: '/endpoint'),
Запрос будет отправлен один раз, но если вам нужно отправлять запрос при каждом открытии, то используйте атрибут data-always-load
Modal::make(...)->customAttributes(['data-always-load' => true]),Modal::make(...)->customAttributes(['data-always-load' => true]),
Внешние атрибуты
Метод outerAttributes() позволяет установить дополнительные атрибуты для внешнего блока $outer.
outerAttributes(array $attributes)outerAttributes(array $attributes)
use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->outerAttributes(['class' => 'mt-2']),];}//...use MoonShine\Components\Modal;//...public function components(): array{return [Modal::make('Заголовок', 'Содержимое...', ActionButton::make('Показать модальное окно', '#'))->outerAttributes(['class' => 'mt-2']),];}//...