Alert Dialog
jQueryМодальное диалоговое окно, которое прерывает работу пользователя, сообщает важную информацию и ожидает ответа.
На этой странице
Пример
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog">Открыть диалог</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-title" aria-describedby="demo-alert-dialog-description">
<div class="ui-alert-dialog__header">
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-title">Продолжить публикацию?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-description">Новая версия станет доступна всем участникам команды. Вы сможете изменить её позже.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Продолжить</button>
</div>
</dialog>Подключение
Компонент включён в dist/ui.min.css. Подключите сборку один раз и добавьте ui-root на контейнер интерфейса.
<link rel="stylesheet" href="ui-kit/dist/ui.min.css">
<link rel="stylesheet" href="ui-kit/dist/ui-icons.min.css">
<body class="ui-root">
<!-- Компоненты вашего приложения -->
</body>Для выборочной сборки добавьте импорт в src/css/index.css после токенов и базовых стилей:
@import "./components/alert-dialog.css" layer(components);Для поведения подключите jQuery перед UIkit. Атрибуты data-ui-* инициализируются при готовности DOM.
<script defer src="vendor/jquery.min.js"></script>
<script defer src="ui-kit/dist/ui-icons.min.js"></script>
<script defer src="ui-kit/dist/ui.min.js"></script>Alert Dialog использует общий механизм Modal. Для выборочной сборки импортируйте modal.css перед alert-dialog.css, а JS — в порядке core → modal → alert-dialog. В готовых сборках всё уже включено.
Использование
Разметка адаптирована по референсу shadcn для HTML + CSS + jQuery. Используйте нативный dialog и уникальные ID. Свойства React представлены HTML-атрибутами и CSS-классами.
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog">Открыть диалог</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-title" aria-describedby="demo-alert-dialog-description">
<div class="ui-alert-dialog__header">
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-title">Продолжить публикацию?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-description">Новая версия станет доступна всем участникам команды. Вы сможете изменить её позже.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Продолжить</button>
</div>
</dialog>Компоновка
AlertDialog → dialog[data-ui-alert-dialog]
├── Trigger → [data-ui-alert-dialog-open="dialog-id"]
└── Content → .ui-modal.ui-alert-dialog
├── Header → .ui-alert-dialog__header
│ ├── Media → .ui-alert-dialog__media
│ ├── Title → .ui-alert-dialog__title
│ └── Description → .ui-alert-dialog__description
└── Footer → .ui-alert-dialog__footer
├── Cancel → [data-ui-alert-dialog-cancel]
└── Action → [data-ui-alert-dialog-action]Кнопка Trigger находится рядом с dialog. Затемнение, блокировка фоновой страницы и удержание фокуса обеспечиваются нативным модальным окном и плагином.
Basic · Базовый
Диалог с заголовком, описанием и кнопками отмены и продолжения.
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-basic">Открыть диалог</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog-basic"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-basic-title" aria-describedby="demo-alert-dialog-basic-description">
<div class="ui-alert-dialog__header">
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-basic-title">Продолжить публикацию?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-basic-description">Новая версия станет доступна всем участникам команды. Вы сможете изменить её позже.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Продолжить</button>
</div>
</dialog>Small · Компактный
Аналог size="sm" — атрибут data-size="sm" или класс ui-alert-dialog--sm. Ширина — 320px, текст выровнен по центру.
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-small">Компактный диалог</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog data-size="sm" id="demo-alert-dialog-small"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-small-title" aria-describedby="demo-alert-dialog-small-description">
<div class="ui-alert-dialog__header">
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-small-title">Продолжить работу?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-small-description">Новые настройки будут применены ко всему проекту.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Продолжить</button>
</div>
</dialog>Media · С медиа
Добавьте ui-alert-dialog__media — аналог AlertDialogMedia. Контейнер поддерживает локальную иконку Lucide или изображение. Значимой картинке задайте alt.
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-media">Поделиться проектом</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog-media"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-media-title" aria-describedby="demo-alert-dialog-media-description">
<div class="ui-alert-dialog__header">
<div class="ui-alert-dialog__media">
<i data-lucide="users" class="ui-icon" aria-hidden="true"></i>
</div>
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-media-title">Открыть доступ команде?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-media-description">Участники команды смогут просматривать проект и оставлять комментарии.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Открыть доступ</button>
</div>
</dialog>Small with Media · Компактный с медиа
Объедините data-size="sm" и ui-alert-dialog__media. Иконка, заголовок и описание выровнены по центру.
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-small-media">Подключить устройство</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog data-size="sm" id="demo-alert-dialog-small-media"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-small-media-title" aria-describedby="demo-alert-dialog-small-media-description">
<div class="ui-alert-dialog__header">
<div class="ui-alert-dialog__media">
<i data-lucide="bluetooth" class="ui-icon" aria-hidden="true"></i>
</div>
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-small-media-title">Разрешить подключение?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-small-media-description">Устройство сможет обмениваться данными с этим приложением.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>Разрешить</button>
</div>
</dialog>Destructive · Удаление
AlertDialogAction — кнопка с data-ui-alert-dialog-action. Добавьте ui-button--danger для опасного действия. Начальный фокус остаётся на «Отмена».
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-destructive">Удалить чат</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog-destructive"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-destructive-title" aria-describedby="demo-alert-dialog-destructive-description">
<div class="ui-alert-dialog__header">
<div class="ui-alert-dialog__media ui-alert-dialog__media--destructive">
<i data-lucide="trash" class="ui-icon" aria-hidden="true"></i>
</div>
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-destructive-title">Удалить этот чат?</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-destructive-description">Все сообщения в этом чате будут удалены без возможности восстановления.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>Отмена</button>
<button class="ui-button ui-button--danger" type="button" data-ui-alert-dialog-action>Удалить</button>
</div>
</dialog>RTL · Справа налево
Для арабского или иврита задайте dir="rtl" на общем контейнере кнопки и диалога либо на html. Язык содержимого укажите через lang. Направление текста и порядок кнопок наследуются автоматически; Tab следует порядку элементов в HTML. Ниже обычный и компактный варианты на арабском.
<div dir="rtl" lang="ar">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-rtl">إظهار الحوار</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog id="demo-alert-dialog-rtl"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-rtl-title" aria-describedby="demo-alert-dialog-rtl-description">
<div class="ui-alert-dialog__header">
<div class="ui-alert-dialog__media">
<i data-lucide="users" class="ui-icon" aria-hidden="true"></i>
</div>
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-rtl-title">هل تريد المتابعة؟</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-rtl-description">سيتم تطبيق الإعدادات الجديدة على المشروع بأكمله.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>إلغاء</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>متابعة</button>
</div>
</dialog>
</div><div dir="rtl" lang="ar">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-open="demo-alert-dialog-rtl-small">إظهار الحوار الصغير</button>
<dialog class="ui-modal ui-alert-dialog" data-ui-alert-dialog data-size="sm" id="demo-alert-dialog-rtl-small"
role="alertdialog" aria-modal="true" aria-labelledby="demo-alert-dialog-rtl-small-title" aria-describedby="demo-alert-dialog-rtl-small-description">
<div class="ui-alert-dialog__header">
<div class="ui-alert-dialog__media">
<i data-lucide="bluetooth" class="ui-icon" aria-hidden="true"></i>
</div>
<h2 class="ui-alert-dialog__title" id="demo-alert-dialog-rtl-small-title">هل تريد المتابعة؟</h2>
<p class="ui-alert-dialog__description" id="demo-alert-dialog-rtl-small-description">سيتم تطبيق الإعدادات الجديدة على المشروع بأكمله.</p>
</div>
<div class="ui-alert-dialog__footer">
<button class="ui-button ui-button--secondary" type="button" data-ui-alert-dialog-cancel autofocus>إلغاء</button>
<button class="ui-button" type="button" data-ui-alert-dialog-action>متابعة</button>
</div>
</dialog>
</div>Ответ пользователя
Кнопки закрывают диалог. Подключайте действие приложения к ui:alertdialog:confirm; отмена и Escape вызывают ui:alertdialog:cancel. Эти события приходят после закрытия. На этапе beforeclose можно запретить закрытие, например пока выполняется запрос.
$('#delete-dialog').on('ui:alertdialog:confirm', function (event, detail) {
// Выполните действие приложения после подтверждения.
// detail: { action: 'confirm', trigger: HTMLButtonElement | null }
});
$('#delete-dialog').on('ui:alertdialog:beforeclose', function (event, detail) {
if (isSaving) event.preventDefault();
});$('#delete-dialog').uiAlertDialog('open');
$('#delete-dialog').uiAlertDialog('cancel');
$('#delete-dialog').uiAlertDialog('destroy');Проверка со скринридером
После встраивания компонента проверьте итоговый экран с VoiceOver в Safari или NVDA в Firefox. Автоматические проверки названия, описания и фокуса не подтверждают фактическое озвучивание скринридером.
- Откройте диалог с клавиатуры. Должны быть доступны роль диалога, его заголовок, описание и кнопка отмены с начальным фокусом.
- Пройдите содержимое и кнопки: фоновая страница должна оставаться недоступной. Tab и Shift+Tab удерживают фокус внутри.
- Нажмите Escape: окно закрывается без подтверждения, фокус возвращается к кнопке открытия.
- Откройте окно ещё раз и подтвердите действие: ответ приходит один раз, фокус возвращается к кнопке открытия.
- Повторите для длинного описания и арабских примеров. Проверьте язык чтения, доступность всего текста и отсутствие декоративной иконки среди озвучиваемых изображений.
API
| Класс / атрибут | Назначение |
|---|---|
| data-ui-alert-dialog | Автоматическая инициализация dialog; не совмещайте с data-ui-modal |
| data-ui-alert-dialog-open="id" | Открытие связанного диалога |
| data-size="sm" / .ui-alert-dialog--sm | Компактный размер 320px вместо 512px |
| dir="rtl" / lang="ar" | Направление справа налево и язык на общем контейнере или html |
| .ui-alert-dialog__media | Медиа: иконка или изображение 48 × 48px |
| data-ui-alert-dialog-cancel | Отмена и безопасный начальный фокус |
| data-ui-alert-dialog-action | Подтверждение; disabled блокирует действие |
| uiAlertDialog("open" | "close" | "cancel" | "confirm" | "destroy") | Методы jQuery; close равнозначен cancel, destroy освобождает плагин |
| ui:alertdialog:beforeopen / open | До открытия (отменяемое) и после открытия |
| ui:alertdialog:beforeclose / close | До закрытия (отменяемое) и после закрытия; detail.action: confirm, cancel или destroy |
| ui:alertdialog:confirm / cancel | Ответ пользователя; destroy не вызывает подтверждение или отмену |
Доступность
- Используйте
role="alertdialog",aria-modal="true"и связиaria-labelledby/aria-describedbyс заголовком и описанием. - При открытии фокус получает «Отмена», Tab и Shift+Tab остаются внутри окна. После закрытия фокус возвращается на кнопку открытия.
- Escape отменяет действие; клик по затемнению не закрывает окно. Кнопка «Отмена» должна оставаться доступной.
- Фоновая страница становится неактивной, прокрутка блокируется. Декоративные иконки скрыты через aria-hidden; значимым изображениям задайте alt.
- Анимация открытия учитывает prefers-reduced-motion. Для длинного текста предусмотрена прокрутка внутри окна.