feat: Рефакторинг компонента HistoryModal с заменой на простой подход с встроенным backdrop. Упрощение структуры и улучшение взаимодействия с пользователем через обновленный интерфейс модального окна.
Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 1m43s

This commit is contained in:
2025-10-03 10:56:56 +07:00
parent 2104c0170d
commit 9bff239035
2 changed files with 177 additions and 186 deletions
+123 -94
View File
@@ -1,4 +1,3 @@
import Modal from './Modal';
import { useState } from 'react'; import { useState } from 'react';
import api from '../lib/api.js'; import api from '../lib/api.js';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
@@ -9,7 +8,7 @@ import { formatDateTimeWithRelative } from '../lib/datetime.js';
/** /**
* HistoryModal - модальное окно истории версий * HistoryModal - модальное окно истории версий
* Рефакторинг: теперь использует базовый Modal компонент * Простой подход со встроенным backdrop
*/ */
export default function HistoryModal({ resource, show, onClose, onRolledBack }) { export default function HistoryModal({ resource, show, onClose, onRolledBack }) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -50,105 +49,135 @@ export default function HistoryModal({ resource, show, onClose, onRolledBack })
}); });
}; };
const handleOpen = () => { if (!show) return null;
if (show) {
refetch().catch(() => notify.error('Не удалось загрузить историю версий')); if (show && items.length === 0) {
} refetch().catch(() => notify.error('Не удалось загрузить историю версий'));
}; }
return ( return (
<> <>
<Modal <div
show={show} className="modal show d-block"
onClose={onClose} role="dialog"
title={ aria-modal="true"
<div className="d-flex align-items-center"> style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
<IconHistory className="me-2" size={24} /> onKeyDown={(e) => { if (e.key === 'Escape') onClose?.(); }}
История версий
</div>
}
size="lg"
centered
scrollable
onOpen={handleOpen}
> >
{/* Info bar */} <div className="modal-dialog modal-lg modal-dialog-centered" role="document">
<div className="d-flex justify-content-between align-items-center mb-3 p-2 bg-blue-lt rounded"> <div
<div className="text-muted small d-flex align-items-center"> className="modal-content"
<IconInfoCircle size={16} className="me-2" /> tabIndex={-1}
Ресурс: <code className="ms-1">{resource}</code> onKeyDown={(e) => {
</div> if (e.key === 'Tab') {
<button const c = e.currentTarget;
className="btn btn-outline-primary btn-sm" const focusable = c.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
onClick={() => refetch()} if (!focusable || focusable.length === 0) return;
disabled={loading} const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}}
> >
<IconRefresh size={16} className={loading ? 'spin' : ''} /> <div className="modal-header">
<span className="ms-1">Обновить</span> <h5 className="modal-title d-flex align-items-center">
</button> <IconHistory className="me-2" size={24} />
</div> История версий
</h5>
<button type="button" className="btn-close" onClick={onClose} />
</div>
<div className="modal-body">
{/* Info bar */}
<div className="d-flex justify-content-between align-items-center mb-3 p-2 bg-blue-lt rounded">
<div className="text-muted small d-flex align-items-center">
<IconInfoCircle size={16} className="me-2" />
Ресурс: <code className="ms-1">{resource}</code>
</div>
<button
className="btn btn-outline-primary btn-sm"
onClick={() => refetch()}
disabled={loading}
>
<IconRefresh size={16} className={loading ? 'spin' : ''} />
<span className="ms-1">Обновить</span>
</button>
</div>
{/* Table */} {/* Table */}
<div className="table-responsive"> <div className="table-responsive">
<table className="table card-table table-vcenter table-hover"> <table className="table card-table table-vcenter table-hover">
<thead> <thead>
<tr> <tr>
<th>Версия</th> <th>Версия</th>
<th>Дата</th> <th>Дата</th>
<th>Размер</th> <th>Размер</th>
<th>ETag</th> <th>ETag</th>
<th className="text-end">Действия</th> <th className="text-end">Действия</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{items.length === 0 ? ( {items.length === 0 ? (
<tr> <tr>
<td colSpan="5" className="text-muted text-center py-5"> <td colSpan="5" className="text-muted text-center py-5">
<div className="empty"> <div className="empty">
<div className="empty-icon"> <div className="empty-icon">
<IconClock size={48} className="text-muted" /> <IconClock size={48} className="text-muted" />
</div> </div>
<p className="empty-title">Нет данных</p> <p className="empty-title">Нет данных</p>
<p className="empty-subtitle text-muted"> <p className="empty-subtitle text-muted">
Версионирование бакета может быть отключено Версионирование бакета может быть отключено
</p> </p>
</div> </div>
</td> </td>
</tr> </tr>
) : ( ) : (
items.map((v) => ( items.map((v) => (
<tr key={v.versionId} className={v.isLatest ? 'table-active' : ''}> <tr key={v.versionId} className={v.isLatest ? 'table-active' : ''}>
<td> <td>
<code className="text-muted small">{v.versionId}</code> <code className="text-muted small">{v.versionId}</code>
{v.isLatest && ( {v.isLatest && (
<span className="badge bg-green-lt text-green ms-2">Текущая</span> <span className="badge bg-green-lt text-green ms-2">Текущая</span>
)} )}
</td> </td>
<td className="text-nowrap"> <td className="text-nowrap">
{v.lastModified ? formatDateTimeWithRelative(v.lastModified) : '—'} {v.lastModified ? formatDateTimeWithRelative(v.lastModified) : '—'}
</td> </td>
<td>{typeof v.size === 'number' ? `${v.size} байт` : '—'}</td> <td>{typeof v.size === 'number' ? `${v.size} байт` : '—'}</td>
<td><code className="text-muted small">{v.etag || '—'}</code></td> <td><code className="text-muted small">{v.etag || '—'}</code></td>
<td className="text-end"> <td className="text-end">
{!v.isLatest && ( {!v.isLatest && (
<button <button
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
onClick={() => rollback(v.versionId)} onClick={() => rollback(v.versionId)}
disabled={loading} disabled={loading}
title="Восстановить содержимое файла до этой версии" title="Восстановить содержимое файла до этой версии"
> >
<IconRotate2 size={16} className="me-1" /> <IconRotate2 size={16} className="me-1" />
Восстановить Восстановить
</button> </button>
)} )}
</td> </td>
</tr> </tr>
)) ))
)} )}
</tbody> </tbody>
</table> </table>
</div>
</div>
<div className="modal-footer">
<button className="btn" onClick={onClose}>Закрыть</button>
</div>
</div>
</div> </div>
</Modal> </div>
<ConfirmDialog <ConfirmDialog
open={confirmState.open} open={confirmState.open}
+54 -92
View File
@@ -1,21 +1,8 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
/** /**
* Универсальный Modal компонент с гарантированным backdrop * Универсальный Modal компонент
* Единая система для всех модальных окон проекта * Простой и надёжный - работает как HistoryModal
*
* @param {boolean} show - Показать/скрыть модалку
* @param {function} onClose - Callback при закрытии
* @param {function} onOpen - Callback при открытии
* @param {string|ReactNode} title - Заголовок модалки
* @param {ReactNode} children - Содержимое
* @param {ReactNode} footer - Футер с кнопками
* @param {string} size - Размер: sm, md, lg, xl
* @param {boolean} backdrop - Показывать backdrop (по умолчанию true)
* @param {boolean} keyboard - Закрывать по ESC (по умолчанию true)
* @param {boolean} scrollable - Прокручиваемое тело
* @param {boolean} centered - Центрировать по вертикали
* @param {string} className - Дополнительные CSS классы
*/ */
function Modal({ function Modal({
show, show,
@@ -32,13 +19,12 @@ function Modal({
className = '' className = ''
}) { }) {
const modalRef = useRef(null); const modalRef = useRef(null);
const backdropRef = useRef(null);
// Управление классом modal-open на body // Управление классом modal-open на body
useEffect(() => { useEffect(() => {
if (show) { if (show) {
document.body.classList.add('modal-open'); document.body.classList.add('modal-open');
modalRef.current?.focus(); setTimeout(() => modalRef.current?.focus(), 100);
onOpen?.(); onOpen?.();
} else { } else {
document.body.classList.remove('modal-open'); document.body.classList.remove('modal-open');
@@ -64,90 +50,72 @@ function Modal({
if (!show) return null; if (!show) return null;
const handleBackdropClick = (e) => {
if (backdrop && e.target === backdropRef.current) {
onClose?.();
}
};
return ( return (
<> <div
{/* Backdrop - гарантированное затемнение */} className={`modal show d-block ${className}`}
{backdrop && ( role="dialog"
<div aria-modal="true"
ref={backdropRef} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
className="modal-backdrop fade show" onKeyDown={(e) => { if (e.key === 'Escape') onClose?.(); }}
onClick={handleBackdropClick} >
style={{
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
zIndex: 1050
}}
/>
)}
{/* Modal */}
<div <div
className={`modal fade show d-block ${className}`} className={`modal-dialog${size !== 'md' ? ` modal-${size}` : ''}${scrollable ? ' modal-dialog-scrollable' : ''}${centered ? ' modal-dialog-centered' : ''}`}
tabIndex="-1" role="document"
role="dialog"
aria-modal="true"
style={{
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
overflow: 'auto',
zIndex: 1055
}}
ref={modalRef}
> >
<div className={`modal-dialog${size !== 'md' ? ` modal-${size}` : ''}${scrollable ? ' modal-dialog-scrollable' : ''}${centered ? ' modal-dialog-centered' : ''}`}> <div
<div className="modal-content"> className="modal-content"
{title && ( ref={modalRef}
<div className="modal-header"> tabIndex={-1}
<h5 className="modal-title">{title}</h5> onKeyDown={(e) => {
<button if (e.key === 'Tab') {
type="button" const c = e.currentTarget;
className="btn-close" const focusable = c.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
onClick={onClose} if (!focusable || focusable.length === 0) return;
aria-label="Закрыть" const first = focusable[0];
/> const last = focusable[focusable.length - 1];
</div> if (e.shiftKey && document.activeElement === first) {
)} e.preventDefault();
last.focus();
<div className="modal-body"> } else if (!e.shiftKey && document.activeElement === last) {
{children} e.preventDefault();
first.focus();
}
}
}}
>
{title && (
<div className="modal-header">
<h5 className="modal-title">{title}</h5>
<button
type="button"
className="btn-close"
onClick={onClose}
aria-label="Закрыть"
/>
</div> </div>
)}
{footer && (
<div className="modal-footer"> <div className="modal-body">
{footer} {children}
</div>
)}
</div> </div>
{footer && (
<div className="modal-footer">
{footer}
</div>
)}
</div> </div>
</div> </div>
</> </div>
); );
} }
export default Modal; export default Modal;
/** /**
* =================================== * Готовые пресеты для быстрого использования
* ГОТОВЫЕ ПРЕСЕТЫ ДЛЯ РАЗНЫХ ЦЕЛЕЙ
* ===================================
*/ */
/**
* Компактная модалка для быстрых подтверждений
*/
export function SmallModal({ show, onClose, title, children, footer, ...props }) { export function SmallModal({ show, onClose, title, children, footer, ...props }) {
return ( return (
<Modal <Modal
@@ -164,9 +132,6 @@ export function SmallModal({ show, onClose, title, children, footer, ...props })
); );
} }
/**
* Большая модалка для сложного контента
*/
export function LargeModal({ show, onClose, title, children, footer, scrollable = true, ...props }) { export function LargeModal({ show, onClose, title, children, footer, scrollable = true, ...props }) {
return ( return (
<Modal <Modal
@@ -184,9 +149,6 @@ export function LargeModal({ show, onClose, title, children, footer, scrollable
); );
} }
/**
* Модалка на весь экран
*/
export function FullscreenModal({ show, onClose, title, children, footer, ...props }) { export function FullscreenModal({ show, onClose, title, children, footer, ...props }) {
return ( return (
<Modal <Modal