Compare commits
No commits in common. "main" and "v0.9.0" have entirely different histories.
188
CHANGELOG.md
188
CHANGELOG.md
|
|
@ -2,194 +2,6 @@
|
||||||
|
|
||||||
Установка версии: `npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^X.Y.Z"`. На 0.x `^0.7.0` не подхватывает 0.8.0 — минорную версию поднимаем в зависимости явно.
|
Установка версии: `npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^X.Y.Z"`. На 0.x `^0.7.0` не подхватывает 0.8.0 — минорную версию поднимаем в зависимости явно.
|
||||||
|
|
||||||
## [0.25.0] — 2026-11-09
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `useSectionTabState(tabId, field, initial, { version }?)`: замена `useState` для форм на вкладках раздела. Если уйти на другую вкладку или в другой пункт меню и вернуться, введённое останется на месте. Значение стирается при закрытии вкладки любым способом, в том числе из бокового меню. Хранится только в памяти: в хранилище браузера не попадает, при перезагрузке страницы теряется. Без правок форма при возврате получает свежий `initial`, а при другой `version` старые правки не восстанавливаются.
|
|
||||||
- `clearSectionTabState()`: стирает значения всех вкладок. Вызывайте при выходе пользователя, иначе следующий пользователь на этом рабочем месте увидит чужие данные. Если хук не используется, ничего менять не нужно.
|
|
||||||
|
|
||||||
## [0.24.0] — 2026-11-07
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `AppSidebar`: у пользователя поле `presence` — `online`, `away`, `busy` или `offline`. На аватаре внизу меню появляется цветная точка, в развёрнутом и свёрнутом меню одинаково. Название статуса показывается в подсказке над точкой и читается скринридером вместе с именем. Без `presence` меню выглядит как раньше.
|
|
||||||
- `PresenceDot`, `PRESENCE`, `PRESENCE_ORDER`: точка статуса для своих меню и списков, подписи и цвета статусов («На месте», «Отошёл», «Не беспокоить», «Не в сети») и порядок, в котором их показывать при выборе.
|
|
||||||
|
|
||||||
## [0.23.0] — 2026-11-07
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `SectionFrame` запоминает прокрутку по адресу страницы. Если переключиться на другую вкладку раздела и вернуться, карточка или список окажутся на том же месте. Это касается и подвкладок внутри карточки, если они в адресе (`?section=`). Запоминаются все прокручиваемые области внутри рамки: `ScrollArea`, колонки, `overflow-auto`. Новая карточка и новый поисковый запрос открываются сверху. Правок в страницах не нужно. Позиции хранятся в памяти и после перезагрузки не сохраняются.
|
|
||||||
- `useScrollMemory(ref, key)`: тот же механизм для своего контейнера. Запоминает прокрутку всего, что внутри `ref`, и возвращает её, когда `key` снова становится текущим.
|
|
||||||
|
|
||||||
## [0.22.0] — 2026-11-06
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `SidebarCards`: у карточки проп `tone` — `positive`, `info`, `warning` или `negative`. Карточка получает подложку и иконку цвета типа, например, чтобы отличать онлайн-запись от критичного результата. В оформлении «Графит» карточки остаются монохромными. Без `tone` карточка выглядит как раньше.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `SidebarCards`: у карточек больше нет рамки и светлой линии сверху, только подложка. Карточка стала на 2px ниже.
|
|
||||||
|
|
||||||
## [0.21.0] — 2026-11-05
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- Оформление «Графит»: монохромное, со светлым меню на сером фоне и белым листом. Основные кнопки чёрные, цветными остаются статусы и тревожные отметки. Есть светлый и тёмный варианты.
|
|
||||||
- `ThemeProvider`: оформление выбирается отдельно от темы. Проп `defaultStyle`, в `useTheme()` — `style` и `setStyle`, значения `clinical` (по умолчанию) и `graphite`. Выбор помнится в `localStorage` под ключом `<storageKey>.style`, на `<html>` ставится атрибут `data-style`. Если ничего не менять, приложение остаётся в прежнем оформлении.
|
|
||||||
- Токены меню для своих блоков внутри него: `sidebar-strong`, `sidebar-ink`, `sidebar-on-warning`, `sidebar-surface`, `sidebar-surface-hover`, `sidebar-surface-border`, `sidebar-surface-border-hover`, `sidebar-surface-highlight`, `sidebar-footer`, `sidebar-footer-shadow`, `sidebar-frame`. Лист `AppShell` получил токен `sheet-ring`.
|
|
||||||
- Вариант Tailwind `graphite:` — для того, что в «Графите» отличается формой, а не цветом.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `AppSidebar`, `SidebarCards`, `AppShell`: цвета теперь берутся из токенов, а не заданы как `white/…`. В клиническом оформлении вид прежний. Если вы кладёте в меню свои блоки (`footerExtra`, `headerExtra`, логотип) с `text-white` или `white/…`, замените их на токены: в «Графите» на светлом меню такой текст и подложки не видны.
|
|
||||||
- `SectionFrame`, `PageFrame`: в «Графите» контент лежит прямо на листе `AppShell`, без отступа и второй рамки. Если раздел стоит не внутри `AppShell`, рамки вокруг него в этом оформлении не будет.
|
|
||||||
|
|
||||||
## [0.20.0] — 2026-11-05
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `SidebarCards`: у карточки проп `onDismiss`. Если он передан, при наведении и фокусе с клавиатуры на карточке появляется крестик: закрыть без перехода. Что значит «закрыть», решает приложение: например, отметить уведомление прочитанным и убрать его из `items`.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `AppSidebar`: строка `footerExtra` теперь стоит над плашкой футера с пользователем, а не внутри неё, и без своего разделителя снизу.
|
|
||||||
|
|
||||||
## [0.19.0] — 2026-11-05
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `SidebarCards` и проп `cards` у `AppSidebar`: листающиеся карточки под меню, например непрочитанные уведомления. Пропы: `label`, `items` (`id`, `title`, `description`, `icon`, `to`, `onClick`), `interval` — смена карточки, по умолчанию 6 секунд. На наведении и фокусе с клавиатуры листание останавливается, при «уменьшить движение» в системе видна только первая карточка. Описание — в одну строку с многоточием, полный текст в подсказке. В свёрнутом меню и когда под меню не хватает места карточки не показываются, поэтому на низких окнах их может не быть. Без `cards` меню выглядит как раньше.
|
|
||||||
|
|
||||||
## [0.18.0] — 2026-11-05
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `AppSidebar`: проп `footerExtra(collapsed)` — строка в футере над пользователем, с разделителем снизу: например, часы или окружение. Функция получает свёрнутость меню, чтобы в узком виде показать меньше. Без пропа футер выглядит как раньше.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `AppSidebar`: кнопки из `actions` переехали из ряда с поиском в ряд с логотипом, справа, и стали без рамки: подложка появляется при наведении и у открытого раздела. Поиск снова занимает всю ширину. В свёрнутом меню кнопки стоят под логотипом, над поиском. Если передаёте `actions` вместе с `headerExtra`, проверьте, что всё помещается в ряд с логотипом.
|
|
||||||
|
|
||||||
## [0.17.0] — 2026-11-03
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `PageFrame`: проп `titleVariant`. `"chip"` (по умолчанию) — заголовок на подложке, как активная вкладка раздела из меню, выглядит как раньше. `"plain"` — обычный заголовок без подложки, для страниц, которые не хочется показывать вкладкой.
|
|
||||||
|
|
||||||
## [0.16.0] — 2026-11-03
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `AppSidebar`: проп `actions` — разделы-кнопки в одном ряду с поиском, для разделов, которым не нужна своя строка в меню (например, «Уведомления»). Тип `SidebarAction`: `to`, `label`, `icon`, `badge`, `badgeTone`, `match`. При `badge` больше нуля на кнопке появляется точка, название и число показываются в подсказке и `aria-label`. В свёрнутом меню кнопки встают столбиком под поиском. Без `actions` меню выглядит как раньше.
|
|
||||||
|
|
||||||
## [0.15.0] — 2026-11-02
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `FileTypeIcon`: цветная плитка типа файла для строк списка — PDF, изображение, документ, таблица, презентация, архив, прочее. Проп `file` — `{ name, type }`; группу можно узнать и без значка, хелпером `fileKind`.
|
|
||||||
- `UploadProgress`: строка загружаемого файла с именем, размером, прогрессом и отменой. `progress` — проценты, `null` — бегущий отрезок; с `error` вместо полосы показывается текст ошибки, а крестик (`onCancel`) скрывает строку.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `formatBytes`: единицы теперь по-русски, дробная часть — через запятую, у чисел от десяти её нет: «512 Б», «1,5 КБ», «12 МБ» вместо «512 B», «1.5 KB», «12.0 MB». Это видно и в `FileGallery`, и в просмотрщике файлов. Если где-то разбираете эту строку или проверяете её в тестах — обновите.
|
|
||||||
|
|
||||||
## [0.14.2] — 2026-11-01
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `Autocomplete`: карточка выбранного значения (`renderValue`) больше не заливается акцентным цветом — фон как у обычного поля.
|
|
||||||
|
|
||||||
## [0.14.1] — 2026-11-01
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `FilterBar`: панель расширенных фильтров устроена как форма в разделе — заголовок на мягкой подложке, поля на белой карточке.
|
|
||||||
- `FilterSwitch`: тумблер слева, подпись и подсказка справа; строка-карточка с рамкой убрана.
|
|
||||||
|
|
||||||
## [0.14.0] — 2026-11-01
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `FilterToggle`: пилюля-переключатель в строке фильтров, по высоте как поле. Цвет задаёт `tone` (`negative`, `positive`, `info`, `warning`, `primary`): выключена — контур, включена — мягкая заливка. Иконка передаётся пропом `icon`.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `FilterBar`, `FilterTabs` и `ContentTabs` с `variant="pill"`: серая подложка стала высотой поля (36px) и стоит вровень с поиском и селектом.
|
|
||||||
|
|
||||||
## [0.13.2] — 2026-10-30
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `FilterBar`: «Сбросить» сокращён до доступной кнопки-иконки и вместе с «Ещё» оформлен компактной группой в стиле контентных вкладок.
|
|
||||||
|
|
||||||
## [0.13.1] — 2026-10-30
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `AppSidebar`: меню стало плотнее по высоте, улучшены поиск, активные и фокусные состояния, счётчики и нижняя панель пользователя. Заголовки групп читаются лучше, а вложенные открытые карточки занимают меньше места.
|
|
||||||
|
|
||||||
## [0.13.0] — 2026-10-30
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `PhoneInput`: общее поле российского мобильного телефона с префиксом `+7`, маской `(000) 000-00-00` и корректной правкой номера в середине строки.
|
|
||||||
- `ScheduleGrid`: проп `compact` для плотной сетки — колонки уже, на карточках остаётся время, остальные данные доступны в подсказке и скринридеру.
|
|
||||||
- `FilterBar`: `moreVariant="popover"` открывает расширенные фильтры всплывающим слоем над контентом; прежняя панель справа остаётся вариантом по умолчанию.
|
|
||||||
- `DateInput`, `DateRangeInput`: `calendarAlign="start" | "center" | "end"` выравнивает календарь относительно поля. У `DateInput` появился `yearCaption="input"` для ввода года с клавиатуры.
|
|
||||||
- `PageFrame`: `showTitleOnMobile` оставляет текст заголовка видимым рядом с иконкой на узком экране.
|
|
||||||
- `Autocomplete`: `renderValue` показывает расширенное представление выбранного объекта прямо внутри поля; по клику поле возвращается в режим поиска.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `FormField` и поля ввода автоматически связывают подсказку и ошибку через `aria-describedby`; ошибки объявляются скринридеру, а `Input`, `Textarea`, `SearchInput` и поля дат получают единое состояние `aria-invalid`.
|
|
||||||
- `Calendar`: выбор месяца и года использует `Select` кита, поэтому список остаётся рядом с календарём и корректно работает внутри popover.
|
|
||||||
- `PatientPanel`: действия переносятся по фактической ширине панели, а не окна, и не сжимают ФИО и контакты на планшете.
|
|
||||||
- `CodeBlock`: кнопка копирования всегда видна, в том числе на сенсорном экране и при навигации с клавиатуры.
|
|
||||||
|
|
||||||
### Исправлено
|
|
||||||
- `DateRangeInput`: год больше не обрезается, а фокус подсвечивает всё составное поле.
|
|
||||||
- Поля даты: удаление цифры в середине сохраняет позиции следующих цифр вместо сдвига года.
|
|
||||||
|
|
||||||
## [0.12.0] — 2026-10-30
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `TimeRangeInput`: проп `overnight` — «по» раньше «с» считается переходом через полночь (21:00–00:00), а не ошибкой: без красной рамки и без `aria-invalid`, скринридер не читает интервал как ошибочный. Ошибкой остаётся только «с» = «по». Если перекрывали красную подсветку своими классами — уберите их и передайте `overnight`.
|
|
||||||
|
|
||||||
## [0.11.2] — 2026-10-28
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `DataTable`: размеры текста как в 0.11.0 — строки 14px, мелкие подписи в ячейках 12px, в карточном виде на телефоне тоже. Шапка таблицы остаётся 13px, `Pagination` — как в 0.11.1.
|
|
||||||
- Токен `text-table` (15px) из 0.11.1 убран: если успели его использовать — замените на `text-sm`.
|
|
||||||
|
|
||||||
## [0.11.1] — 2026-10-28
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `DataTable`: текст на шаг крупнее — строки 15px вместо 14px (токен `text-table`), шапка и мелкие подписи в ячейках (`text-xs`) — 13px вместо 12px, в карточном виде на телефоне тоже. Строки с подписями стали чуть выше.
|
|
||||||
- `Pagination`: подписи 13px, кнопки страниц 32px.
|
|
||||||
- `AppSidebar`: при наведении на пункт меню иконка окрашивается в акцентный цвет и чуть увеличивается; при «уменьшить движение» в системе — только цвет.
|
|
||||||
|
|
||||||
### Исправлено
|
|
||||||
- `Pagination`: при переключении страниц номера и стрелки сдвигались — подпись «1 – 15 из 28» меняет ширину, а страниц показывалось то 4, то 7. Теперь номера строго по центру и мест под них всегда 7.
|
|
||||||
|
|
||||||
## [0.11.0] — 2026-10-28
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `PageFrame`: крайняя справа в шапке — кнопка «Развернуть на весь экран», как у разделов со вкладками: Alt+F, Esc — свернуть, развёрнутость общая с `SectionFrame`. В страницах свою кнопку ставить не нужно.
|
|
||||||
- `ScheduleGrid`: сетку можно таскать мышью — зажать и вести в любую сторону, курсор-рука. Перетаскивание с записи или слота не открывает их, обычный клик работает как раньше; на тач-экранах — привычная прокрутка.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `SearchInput`: поле с рамкой на белом, как `Input` и `Select`, — та же высота, скругление и подсветка фокуса; раньше было на серой подложке и выбивалось из строки фильтров.
|
|
||||||
- `ScheduleGrid`: если день короче окна, шкала времени продолжается до низа (нерабочие часы заштрихованы) — под сеткой больше нет пустоты.
|
|
||||||
- `PageFrame`, `SectionTabsBar`: на телефоне (уже 768px) заголовок раздела и вкладка-раздел сворачиваются до иконки, кнопки действий с иконкой — тоже до иконки; подписи остаются для скринридера. Кнопки без иконки не сжимаются — давайте кнопкам в шапке иконку.
|
|
||||||
|
|
||||||
## [0.10.0] — 2026-10-26
|
|
||||||
|
|
||||||
### Новое
|
|
||||||
- `StatusBadge`: проп `size` — `"sm"` для плотных строк таблиц, `"md"` (по умолчанию, как раньше), `"lg"` для шапки карточки или страницы.
|
|
||||||
- `Chip`: размер `size="lg"` — крупный чип высотой 32px.
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `EditDialog`: новая шапка — иконка на цветной плашке, заголовок и описание рядом; подвал на сером фоне с подсказкой «Enter в поле — сохранить».
|
|
||||||
- `FilterBar`: на «Ещё» вместо счётчика — точка над подписью, когда включены расширенные фильтры, как у «Сбросить»; число — в подсказке. Панель справа — плавающая карточка с отступом от края и иконкой в заголовке, кнопки внизу обычного размера.
|
|
||||||
- `FilterSwitch`: строка-карточка с рамкой, нажимается целиком; включённая подсвечена акцентным цветом.
|
|
||||||
- `Dialog`, `AlertDialog`, `Sheet`: фон — цвет карточки (`bg-card`) вместо фона страницы. Бегунок `Switch` — тоже цвета карточки, с лёгкой тенью.
|
|
||||||
|
|
||||||
### Исправлено
|
|
||||||
- `DateRangeInput`: пустота перед «—» была вдвое больше, чем после, — поле шире текста даты. У растянутого поля (`className="w-full"`) кнопка календаря теперь у правого края.
|
|
||||||
- `DataTable`: у последней строки в растянутой таблице не было линии снизу; у прокрученной до конца линия не задваивается с рамкой.
|
|
||||||
|
|
||||||
## [0.9.2] — 2026-10-26
|
|
||||||
|
|
||||||
### Изменено
|
|
||||||
- `FilterBar`: на «Сбросить» вместо числа — точка над концом подписи, когда есть что сбросить; сколько фильтров включено, видно в подсказке. На «Ещё» счётчик виден всегда: бледный 0, когда расширенные фильтры не включены.
|
|
||||||
|
|
||||||
### Исправлено
|
|
||||||
- `FilterBar`: «Ещё» и «Сбросить» меняли ширину, когда фильтры включали и выключали, и соседние фильтры дёргались.
|
|
||||||
|
|
||||||
## [0.9.1] — 2026-10-26
|
|
||||||
|
|
||||||
### Исправлено
|
|
||||||
- `FilterTabs`: на узком экране варианты уходили за край подложки и обрезались. Теперь переносятся на следующую строку внутри неё.
|
|
||||||
|
|
||||||
## [0.9.0] — 2026-10-26
|
## [0.9.0] — 2026-10-26
|
||||||
|
|
||||||
### Новое
|
### Новое
|
||||||
|
|
|
||||||
25
README.md
25
README.md
|
|
@ -1,6 +1,6 @@
|
||||||
# Medkit — `@medkit/ui`
|
# Medkit — `@medkit/ui`
|
||||||
|
|
||||||
UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui). Живая витрина — `/ui`, `/ui-form` и `/ui-table` в medicine-ui.
|
UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui). Живая витрина — `/ui` и `/ui-form` в medicine-ui.
|
||||||
|
|
||||||
```
|
```
|
||||||
src/ui/ базовые примитивы shadcn/ui
|
src/ui/ базовые примитивы shadcn/ui
|
||||||
|
|
@ -18,7 +18,7 @@ src/styles.css тема (токены, шрифты, тёмный режим)
|
||||||
Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
|
Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.25.0"
|
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.9.0"
|
||||||
```
|
```
|
||||||
|
|
||||||
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.
|
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.
|
||||||
|
|
@ -51,7 +51,7 @@ CSS приложения:
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
```
|
```
|
||||||
|
|
||||||
`ThemeProvider` — светлая, тёмная или `system` (как в ОС): `<ThemeProvider defaultTheme="system" storageKey="lis.theme">`. По умолчанию `light` и ключ `ml.theme`. Оформление не зависит от темы: `clinical` (по умолчанию) или `graphite` — монохромное со светлым меню, задаётся `defaultStyle` и `setStyle` из `useTheme()`. `Toaster` работает и без провайдера — тогда берёт системную тему.
|
`ThemeProvider` — светлая, тёмная или `system` (как в ОС): `<ThemeProvider defaultTheme="system" storageKey="lis.theme">`. По умолчанию `light` и ключ `ml.theme`. `Toaster` работает и без провайдера — тогда берёт системную тему.
|
||||||
|
|
||||||
`NotifyToaster` без `navigate` переходит по `href` через `window.location.assign`.
|
`NotifyToaster` без `navigate` переходит по `href` через `window.location.assign`.
|
||||||
|
|
||||||
|
|
@ -64,7 +64,7 @@ function App() {
|
||||||
return (
|
return (
|
||||||
<ShellProvider storageKey="lis" basename="/medicine-lis" pathname={location.pathname} search={location.search} navigate={navigate}>
|
<ShellProvider storageKey="lis" basename="/medicine-lis" pathname={location.pathname} search={location.search} navigate={navigate}>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route element={<AppShell sidebar={{ logo, groups, search, actions, user, userMenu }}><Outlet /></AppShell>}>…</Route>
|
<Route element={<AppShell sidebar={{ logo, groups, search, user, userMenu }}><Outlet /></AppShell>}>…</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
</ShellProvider>
|
</ShellProvider>
|
||||||
)
|
)
|
||||||
|
|
@ -73,27 +73,12 @@ function App() {
|
||||||
|
|
||||||
`storageKey` — префикс ключей localStorage (вкладки, свёрнутое меню): у приложений на одном домене память не смешивается.
|
`storageKey` — префикс ключей localStorage (вкладки, свёрнутое меню): у приложений на одном домене память не смешивается.
|
||||||
|
|
||||||
### Состояние форм на вкладках
|
|
||||||
|
|
||||||
Страница размонтируется при уходе с вкладки, и обычный `useState` теряет введённое. `useSectionTabState` — такая же замена с результатом `[value, setValue]`, но значение остаётся до закрытия вкладки:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const [form, setForm] = useSectionTabState(tab.id, "form", emptyForm, { version: JSON.stringify(saved) })
|
|
||||||
```
|
|
||||||
|
|
||||||
- `tabId` указываем явно: у новой вкладки до регистрации `activeId` ещё пуст. Работает внутри `SectionTabsProvider`.
|
|
||||||
- `field` — имя значения внутри вкладки. На одной вкладке может быть несколько полей.
|
|
||||||
- `initial` — значение или функция, как в `useState`. Без правок форма при возврате получит свежий `initial`.
|
|
||||||
- `version` (строка или число, необязательно) — версия исходных данных. Если она изменилась, например запись сохранили, старые правки не восстанавливаются и форма берёт `initial`. Брать только те поля, что редактируются: иначе посторонний счётчик сбросит правки.
|
|
||||||
|
|
||||||
Значения хранятся только в памяти: данные пациента не попадают в хранилище браузера, а перезагрузка страницы их стирает. Кит стирает значения сам при закрытии вкладки любым способом, в том числе из бокового меню. При выходе пользователя приложение вызывает `clearSectionTabState()`, иначе следующий пользователь на этом рабочем месте увидит чужие данные.
|
|
||||||
|
|
||||||
Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно.
|
Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно.
|
||||||
|
|
||||||
## Правила для кода пакета
|
## Правила для кода пакета
|
||||||
|
|
||||||
- Импорты внутри пакета — только относительные (`../lib/utils`), без `@/`: алиас принадлежит приложению.
|
- Импорты внутри пакета — только относительные (`../lib/utils`), без `@/`: алиас принадлежит приложению.
|
||||||
- Никаких данных и роутера приложения — только пропсы.
|
- Никаких данных и роутера приложения — только пропсы.
|
||||||
- Новый компонент: файл в `src/kit/`, экспорт в `src/kit/index.ts`, пример на `/ui` (поля — `/ui-form`, таблицы и фильтры — `/ui-table`). Новый shadcn-примитив — файл в `src/ui/` и строка в `src/index.ts`.
|
- Новый компонент: файл в `src/kit/`, экспорт в `src/kit/index.ts`, пример на `/ui`. Новый shadcn-примитив — файл в `src/ui/` и строка в `src/index.ts`.
|
||||||
- Компоненты shadcn берутся исходниками с GitHub (`apps/v4/registry/new-york-v4/ui/*.tsx`), импорт `cn` заменяется на `../lib/utils`.
|
- Компоненты shadcn берутся исходниками с GitHub (`apps/v4/registry/new-york-v4/ui/*.tsx`), импорт `cn` заменяется на `../lib/utils`.
|
||||||
- Проверка типов: `npm run typecheck -w @medkit/ui`.
|
- Проверка типов: `npm run typecheck -w @medkit/ui`.
|
||||||
|
|
|
||||||
11
package.json
11
package.json
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@medkit/ui",
|
"name": "@medkit/ui",
|
||||||
"version": "0.25.0",
|
"version": "0.9.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
|
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|
@ -16,8 +16,7 @@
|
||||||
"./styles.css": "./src/styles.css"
|
"./styles.css": "./src/styles.css"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc --noEmit -p .",
|
"typecheck": "tsc --noEmit -p ."
|
||||||
"test": "vitest run"
|
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
|
|
@ -37,11 +36,5 @@
|
||||||
"sonner": "^2.0.8",
|
"sonner": "^2.0.8",
|
||||||
"tailwind-merge": "^3.7.0",
|
"tailwind-merge": "^3.7.0",
|
||||||
"tw-animate-css": "^1.4.0"
|
"tw-animate-css": "^1.4.0"
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@testing-library/dom": "^10.4.2",
|
|
||||||
"@testing-library/react": "^16.3.3",
|
|
||||||
"jsdom": "^29.1.1",
|
|
||||||
"vitest": "^5.0.5"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,119 +0,0 @@
|
||||||
import * as React from "react"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Память прокрутки по ключу (обычно — адрес страницы).
|
|
||||||
*
|
|
||||||
* Следит за всеми прокручиваемыми контейнерами внутри `rootRef` (ScrollArea, колонки, overflow-auto)
|
|
||||||
* и, когда ключ снова становится текущим, возвращает каждый на прежнее место.
|
|
||||||
* Контейнер узнаётся по пути от корня (индексы детей), поэтому разметка страницы не меняется.
|
|
||||||
* Хранится в памяти вкладки браузера, перезагрузку не переживает.
|
|
||||||
*/
|
|
||||||
|
|
||||||
type Position = { top: number; left: number }
|
|
||||||
|
|
||||||
const LIMIT = 50
|
|
||||||
const HOLD_MS = 600
|
|
||||||
const memory = new Map<string, Map<string, Position>>()
|
|
||||||
|
|
||||||
function pathOf(root: Element, el: Element): string | null {
|
|
||||||
const parts: number[] = []
|
|
||||||
let node: Element | null = el
|
|
||||||
while (node && node !== root) {
|
|
||||||
const parent: Element | null = node.parentElement
|
|
||||||
if (!parent) return null
|
|
||||||
parts.push(Array.prototype.indexOf.call(parent.children, node))
|
|
||||||
node = parent
|
|
||||||
}
|
|
||||||
return node === root ? parts.reverse().join(".") : null
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolve(root: Element, path: string): Element | null {
|
|
||||||
let node: Element | undefined = root
|
|
||||||
for (const part of path ? path.split(".") : []) {
|
|
||||||
node = node?.children[Number(part)]
|
|
||||||
if (!node) return null
|
|
||||||
}
|
|
||||||
return node ?? null
|
|
||||||
}
|
|
||||||
|
|
||||||
function remember(key: string, path: string, pos: Position) {
|
|
||||||
let entry = memory.get(key)
|
|
||||||
if (entry) {
|
|
||||||
memory.delete(key) // в конец — самый свежий
|
|
||||||
} else {
|
|
||||||
entry = new Map()
|
|
||||||
if (memory.size >= LIMIT) memory.delete(memory.keys().next().value!)
|
|
||||||
}
|
|
||||||
memory.set(key, entry)
|
|
||||||
if (pos.top === 0 && pos.left === 0) entry.delete(path)
|
|
||||||
else entry.set(path, pos)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useScrollMemory(rootRef: React.RefObject<HTMLElement | null>, key: string) {
|
|
||||||
const keyRef = React.useRef(key)
|
|
||||||
|
|
||||||
// Запоминаем: scroll не всплывает, но ловится на предке в фазе capture.
|
|
||||||
React.useEffect(() => {
|
|
||||||
const root = rootRef.current
|
|
||||||
if (!root) return
|
|
||||||
const pending = new Set<Element>()
|
|
||||||
let frame = 0
|
|
||||||
|
|
||||||
const flush = () => {
|
|
||||||
frame = 0
|
|
||||||
for (const el of pending) {
|
|
||||||
const path = pathOf(root, el)
|
|
||||||
if (path !== null) remember(keyRef.current, path, { top: el.scrollTop, left: el.scrollLeft })
|
|
||||||
}
|
|
||||||
pending.clear()
|
|
||||||
}
|
|
||||||
const onScroll = (event: Event) => {
|
|
||||||
if (!(event.target instanceof Element)) return
|
|
||||||
pending.add(event.target)
|
|
||||||
if (!frame) frame = requestAnimationFrame(flush)
|
|
||||||
}
|
|
||||||
|
|
||||||
root.addEventListener("scroll", onScroll, { capture: true, passive: true })
|
|
||||||
return () => {
|
|
||||||
root.removeEventListener("scroll", onScroll, { capture: true })
|
|
||||||
if (frame) cancelAnimationFrame(frame)
|
|
||||||
}
|
|
||||||
}, [rootRef])
|
|
||||||
|
|
||||||
// Возвращаем сразу после отрисовки нового адреса и держим позицию, пока раскладка
|
|
||||||
// не устоится: контейнер может появиться позже или ненадолго стать короче, и браузер
|
|
||||||
// прижмёт скролл. Любое действие человека (колесо, касание, клик, клавиша) отпускает.
|
|
||||||
React.useLayoutEffect(() => {
|
|
||||||
keyRef.current = key
|
|
||||||
const root = rootRef.current
|
|
||||||
const saved = memory.get(key)
|
|
||||||
if (!root || !saved?.size) return
|
|
||||||
|
|
||||||
const target = [...saved]
|
|
||||||
const until = performance.now() + HOLD_MS
|
|
||||||
let frame = 0
|
|
||||||
|
|
||||||
const apply = () => {
|
|
||||||
for (const [path, pos] of target) {
|
|
||||||
const el = resolve(root, path)
|
|
||||||
if (!el) continue
|
|
||||||
if (Math.abs(el.scrollTop - pos.top) > 1) el.scrollTop = pos.top
|
|
||||||
if (Math.abs(el.scrollLeft - pos.left) > 1) el.scrollLeft = pos.left
|
|
||||||
}
|
|
||||||
frame = performance.now() < until ? requestAnimationFrame(apply) : 0
|
|
||||||
}
|
|
||||||
const release = () => {
|
|
||||||
cancelAnimationFrame(frame)
|
|
||||||
frame = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
const inputs = ["wheel", "touchstart", "pointerdown", "keydown"] as const
|
|
||||||
inputs.forEach((type) => root.addEventListener(type, release, { capture: true, passive: true }))
|
|
||||||
apply()
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
release()
|
|
||||||
inputs.forEach((type) => root.removeEventListener(type, release, { capture: true }))
|
|
||||||
}
|
|
||||||
}, [rootRef, key])
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// Medkit — UI kit МИС «Медицина». Витрина — /ui, /ui-form и /ui-table в medicine-ui.
|
// Medkit — UI kit МИС «Медицина». Витрина — /ui в medicine-ui.
|
||||||
export * from "./kit"
|
export * from "./kit"
|
||||||
export * from "./ui/alert-dialog"
|
export * from "./ui/alert-dialog"
|
||||||
export * from "./ui/avatar"
|
export * from "./ui/avatar"
|
||||||
|
|
@ -41,7 +41,6 @@ export * from "./charts/column-chart"
|
||||||
export * from "./charts/sparkline"
|
export * from "./charts/sparkline"
|
||||||
export * from "./hooks/use-caret"
|
export * from "./hooks/use-caret"
|
||||||
export * from "./hooks/use-media-query"
|
export * from "./hooks/use-media-query"
|
||||||
export * from "./hooks/use-scroll-memory"
|
|
||||||
export * from "./lib/clipboard"
|
export * from "./lib/clipboard"
|
||||||
export * from "./lib/format"
|
export * from "./lib/format"
|
||||||
export * from "./lib/masks"
|
export * from "./lib/masks"
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { AppSidebar, type AppSidebarProps } from "./app-sidebar"
|
||||||
import { useShell } from "./shell-provider"
|
import { useShell } from "./shell-provider"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Каркас окна: меню слева, справа — лист с текущим разделом (`children`, обычно `<Outlet />`).
|
* Каркас окна: тёмное меню слева, справа — лист с текущим разделом (`children`, обычно `<Outlet />`).
|
||||||
* Окно целиком не прокручивается — только тело раздела. Свёрнутость меню помнится
|
* Окно целиком не прокручивается — только тело раздела. Свёрнутость меню помнится
|
||||||
* (`<storageKey>.sidebar-collapsed`), на узком экране меню всегда свёрнуто. При печати меню скрыто.
|
* (`<storageKey>.sidebar-collapsed`), на узком экране меню всегда свёрнуто. При печати меню скрыто.
|
||||||
* Нужен ShellProvider выше.
|
* Нужен ShellProvider выше.
|
||||||
|
|
@ -50,7 +50,7 @@ export function AppShell({
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<AppSidebar {...sidebar} collapsed={collapsed || narrow} onToggle={toggle} />
|
<AppSidebar {...sidebar} collapsed={collapsed || narrow} onToggle={toggle} />
|
||||||
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-clip bg-background lg:my-2 lg:mr-2 lg:rounded-2xl lg:ring-1 lg:ring-sheet-ring print:m-0 print:block print:overflow-visible print:rounded-none print:bg-transparent">
|
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-clip bg-background lg:my-2 lg:mr-2 lg:rounded-2xl dark:lg:ring-1 dark:lg:ring-white/6 print:m-0 print:block print:overflow-visible print:rounded-none print:bg-transparent">
|
||||||
{children}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import { ChevronRightIcon, PanelLeftCloseIcon, PanelLeftOpenIcon, SearchIcon, XI
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { Avatar, AvatarFallback } from "../ui/avatar"
|
import { Avatar, AvatarFallback } from "../ui/avatar"
|
||||||
import { PRESENCE, PresenceDot, type UserPresence } from "./presence"
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
|
|
@ -17,7 +16,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||||
import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs"
|
import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs"
|
||||||
import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs"
|
import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs"
|
||||||
import { ShellLink, useShell } from "./shell-provider"
|
import { ShellLink, useShell } from "./shell-provider"
|
||||||
import { SIDEBAR_CARDS_HEIGHT, SidebarCards, type SidebarCardsProps } from "./sidebar-cards"
|
|
||||||
|
|
||||||
export interface SidebarNavItem {
|
export interface SidebarNavItem {
|
||||||
readonly to: string
|
readonly to: string
|
||||||
|
|
@ -50,15 +48,10 @@ export interface SidebarSearch {
|
||||||
readonly onClick: () => void
|
readonly onClick: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Кнопка-иконка в шапке меню: раздел, которому не нужна своя строка в меню. При `badge` > 0 — точка; название и число — в подсказке. */
|
|
||||||
export type SidebarAction = Pick<SidebarNavItem, "to" | "label" | "icon" | "badge" | "badgeTone" | "match">
|
|
||||||
|
|
||||||
export interface SidebarUser {
|
export interface SidebarUser {
|
||||||
readonly name: string
|
readonly name: string
|
||||||
readonly subtitle?: string
|
readonly subtitle?: string
|
||||||
readonly initials: string
|
readonly initials: string
|
||||||
/** Присутствие: точка на аватаре, название — в подсказке и для скринридера. */
|
|
||||||
readonly presence?: UserPresence
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppSidebarProps {
|
export interface AppSidebarProps {
|
||||||
|
|
@ -69,16 +62,10 @@ export interface AppSidebarProps {
|
||||||
/** Справа от логотипа в развёрнутом меню (часы, окружение). */
|
/** Справа от логотипа в развёрнутом меню (часы, окружение). */
|
||||||
headerExtra?: React.ReactNode
|
headerExtra?: React.ReactNode
|
||||||
search?: SidebarSearch
|
search?: SidebarSearch
|
||||||
/** Разделы-кнопки в ряду с логотипом, справа («Уведомления»); в свёрнутом меню — под логотипом, над поиском. */
|
|
||||||
actions?: readonly SidebarAction[]
|
|
||||||
groups: readonly SidebarNavGroup[]
|
groups: readonly SidebarNavGroup[]
|
||||||
/** Листающиеся карточки под меню; в свёрнутом меню и когда под меню нет места — не показываются. */
|
|
||||||
cards?: SidebarCardsProps
|
|
||||||
user?: SidebarUser
|
user?: SidebarUser
|
||||||
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
|
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
|
||||||
userMenu?: React.ReactNode
|
userMenu?: React.ReactNode
|
||||||
/** Строка над футером с пользователем (часы, окружение); получает свёрнутость меню. */
|
|
||||||
footerExtra?: (collapsed: boolean) => React.ReactNode
|
|
||||||
className?: string
|
className?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -86,7 +73,7 @@ const toneDot = (tone: SectionTab["tone"], fallback: string) =>
|
||||||
tone === "female" ? "bg-female" : tone === "male" ? "bg-male" : fallback
|
tone === "female" ? "bg-female" : tone === "male" ? "bg-male" : fallback
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Боковое меню (цвета — токены sidebar-*, тёмное или светлое зависит от оформления): логотип, кнопка поиска, разделы-кнопки, разделы группами со счётчиками,
|
* Тёмное боковое меню: логотип, кнопка поиска, разделы группами со счётчиками,
|
||||||
* открытые карточки разделов со вкладками, пользователь и сворачивание. Обычно — внутри AppShell.
|
* открытые карточки разделов со вкладками, пользователь и сворачивание. Обычно — внутри AppShell.
|
||||||
*/
|
*/
|
||||||
export function AppSidebar({
|
export function AppSidebar({
|
||||||
|
|
@ -95,62 +82,35 @@ export function AppSidebar({
|
||||||
logo,
|
logo,
|
||||||
headerExtra,
|
headerExtra,
|
||||||
search,
|
search,
|
||||||
actions,
|
|
||||||
groups,
|
groups,
|
||||||
cards,
|
|
||||||
user,
|
user,
|
||||||
userMenu,
|
userMenu,
|
||||||
footerExtra,
|
|
||||||
className,
|
className,
|
||||||
}: AppSidebarProps) {
|
}: AppSidebarProps) {
|
||||||
const SearchItemIcon = search?.icon ?? SearchIcon
|
const SearchItemIcon = search?.icon ?? SearchIcon
|
||||||
const hasCards = (cards?.items.length ?? 0) > 0
|
|
||||||
const bodyRef = React.useRef<HTMLDivElement>(null)
|
|
||||||
const navRef = React.useRef<HTMLElement>(null)
|
|
||||||
const [cardsFit, setCardsFit] = React.useState(false)
|
|
||||||
|
|
||||||
// Высота тела не зависит от карточек, поэтому показ карточек не меняет результат проверки.
|
|
||||||
React.useEffect(() => {
|
|
||||||
const body = bodyRef.current
|
|
||||||
const nav = navRef.current
|
|
||||||
if (!hasCards || !body || !nav) return
|
|
||||||
const check = () => setCardsFit(nav.offsetHeight + SIDEBAR_CARDS_HEIGHT <= body.clientHeight)
|
|
||||||
const observer = new ResizeObserver(check)
|
|
||||||
observer.observe(body)
|
|
||||||
observer.observe(nav)
|
|
||||||
return () => observer.disconnect()
|
|
||||||
}, [hasCards])
|
|
||||||
|
|
||||||
const actionLinks = actions?.map((action) => <SidebarActionLink key={action.to} action={action} collapsed={collapsed} />)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-svh shrink-0 flex-col overflow-clip border-r border-sidebar-frame/80 bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
|
"flex h-svh shrink-0 flex-col overflow-clip bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
|
||||||
collapsed ? "w-[60px]" : "w-56",
|
collapsed ? "w-[60px]" : "w-56",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className={cn("flex h-16 shrink-0 items-center", collapsed ? "justify-center" : "gap-2.5 px-5")}>
|
<div className={cn("flex h-14 shrink-0 items-center", collapsed ? "justify-center" : "gap-2.5 px-5")}>
|
||||||
{logo(collapsed)}
|
{logo(collapsed)}
|
||||||
{!collapsed && headerExtra}
|
{!collapsed && headerExtra}
|
||||||
{/* Отрицательный отступ — правый край кнопки вровень с поиском (у него px-3, у шапки px-5). */}
|
|
||||||
{!collapsed && actions && actions.length > 0 && <div className="-mr-2 ml-auto flex shrink-0 gap-1">{actionLinks}</div>}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{collapsed && actions && actions.length > 0 && (
|
|
||||||
<div className="flex shrink-0 flex-col items-center gap-1 pb-2">{actionLinks}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{search && (
|
{search && (
|
||||||
<div className="shrink-0 px-3 pb-2">
|
<div className="shrink-0 px-3 pb-1">
|
||||||
<SidebarTooltip label={search.tooltip} enabled={collapsed}>
|
<SidebarTooltip label={search.tooltip} enabled={collapsed}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={search.onClick}
|
onClick={search.onClick}
|
||||||
aria-label={collapsed ? search.tooltip : undefined}
|
aria-label={collapsed ? search.tooltip : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-9 w-full items-center gap-2 rounded-lg border border-sidebar-surface-border bg-sidebar-surface text-sm text-sidebar-muted shadow-[inset_0_1px_0_var(--sidebar-surface-highlight)] transition-colors hover:border-sidebar-surface-border-hover hover:bg-sidebar-surface-hover hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
"flex h-9 w-full items-center gap-2 rounded-lg border border-sidebar-border bg-white/[0.03] text-sm text-sidebar-muted transition hover:bg-white/[0.06] hover:text-sidebar-foreground",
|
||||||
collapsed ? "justify-center" : "px-3",
|
collapsed ? "justify-center" : "px-3",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
@ -159,9 +119,7 @@ export function AppSidebar({
|
||||||
<>
|
<>
|
||||||
<span className="truncate">{search.label}</span>
|
<span className="truncate">{search.label}</span>
|
||||||
{search.shortcut && (
|
{search.shortcut && (
|
||||||
<Kbd className="ml-auto border border-sidebar-ink/[0.06] bg-sidebar-ink/[0.08] text-[10px] text-sidebar-foreground shadow-none">
|
<Kbd className="ml-auto border-0 bg-white/10 text-sidebar-foreground">{search.shortcut}</Kbd>
|
||||||
{search.shortcut}
|
|
||||||
</Kbd>
|
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
@ -170,18 +128,15 @@ export function AppSidebar({
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div ref={bodyRef} className="flex min-h-0 flex-1 flex-col">
|
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-thumb]]:bg-white/15 [&_[data-slot=scroll-area-thumb]]:group-hover/bar:bg-white/30">
|
||||||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-thumb]]:bg-sidebar-ink/15 [&_[data-slot=scroll-area-thumb]]:group-hover/bar:bg-sidebar-ink/30">
|
<nav className={cn("px-3 py-2", collapsed ? "space-y-1.5" : "space-y-4")}>
|
||||||
<nav ref={navRef} className={cn("px-3 py-3", collapsed ? "space-y-2" : "space-y-3.5")}>
|
|
||||||
{groups.map((group) => (
|
{groups.map((group) => (
|
||||||
<div key={group.label} className="group/nav">
|
<div key={group.label} className="group/nav">
|
||||||
{collapsed ? (
|
{collapsed ? (
|
||||||
<div className="mx-auto mb-2 h-px w-7 bg-sidebar-border/90 group-first/nav:hidden" />
|
<div className="mx-auto mb-1.5 h-px w-6 bg-sidebar-border group-first/nav:hidden" />
|
||||||
) : (
|
) : (
|
||||||
<div className="mb-1.5 flex items-center gap-2 px-3">
|
<div className="mb-1 px-3 text-3xs font-semibold tracking-[0.14em] text-sidebar-muted uppercase">
|
||||||
<span className="text-[10px] leading-4 font-semibold tracking-[0.11em] text-sidebar-muted uppercase">
|
|
||||||
{group.label}
|
{group.label}
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<ul className="space-y-0.5">
|
<ul className="space-y-0.5">
|
||||||
|
|
@ -195,12 +150,8 @@ export function AppSidebar({
|
||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
{hasCards && cardsFit && !collapsed && <SidebarCards {...cards!} />}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{footerExtra && <div className="shrink-0 px-3 pb-2">{footerExtra(collapsed)}</div>}
|
<div className="shrink-0 border-t border-sidebar-border p-3">
|
||||||
|
|
||||||
<div className="shrink-0 border-t border-sidebar-frame bg-sidebar-footer px-3 py-2.5 shadow-[0_-8px_20px_var(--sidebar-footer-shadow)]">
|
|
||||||
<div className={cn("flex items-center gap-1", collapsed && "flex-col")}>
|
<div className={cn("flex items-center gap-1", collapsed && "flex-col")}>
|
||||||
{user ? <UserMenu user={user} collapsed={collapsed} menu={userMenu} /> : <div className="flex-1" />}
|
{user ? <UserMenu user={user} collapsed={collapsed} menu={userMenu} /> : <div className="flex-1" />}
|
||||||
<SidebarIconButton label={collapsed ? "Развернуть меню" : "Свернуть меню"} onClick={onToggle}>
|
<SidebarIconButton label={collapsed ? "Развернуть меню" : "Свернуть меню"} onClick={onToggle}>
|
||||||
|
|
@ -240,7 +191,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
const label = count > 0 ? `${item.label}: ${count}` : item.label
|
const label = count > 0 ? `${item.label}: ${count}` : item.label
|
||||||
|
|
||||||
const base = cn(
|
const base = cn(
|
||||||
"relative flex h-8.5 items-center rounded-lg text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
"relative flex h-9 items-center rounded-lg text-sm font-medium transition-colors",
|
||||||
collapsed ? "justify-center" : "gap-3 px-3",
|
collapsed ? "justify-center" : "gap-3 px-3",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -264,29 +215,20 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
aria-current={active ? "page" : undefined}
|
aria-current={active ? "page" : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
base,
|
base,
|
||||||
"group/link",
|
active ? "bg-sidebar-accent text-white" : "text-sidebar-foreground/85 hover:bg-white/[0.04] hover:text-white",
|
||||||
active
|
|
||||||
? "bg-sidebar-accent text-sidebar-strong ring-1 ring-inset ring-sidebar-ink/[0.05]"
|
|
||||||
: "text-sidebar-foreground/80 hover:bg-sidebar-ink/[0.05] hover:text-sidebar-strong",
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{active && <span className="absolute top-1.5 bottom-1.5 left-0 w-[3px] rounded-r-full bg-sidebar-primary" />}
|
{active && <span className="absolute top-2 bottom-2 left-0 w-[3px] rounded-r-full bg-sidebar-primary" />}
|
||||||
{/* При наведении иконка окрашивается и чуть увеличивается (без анимации, если в системе «уменьшить движение»). */}
|
<Icon className={cn("size-[18px] shrink-0", active && "text-sidebar-primary")} />
|
||||||
<Icon
|
|
||||||
className={cn(
|
|
||||||
"size-[18px] shrink-0 transition-colors group-hover/link:text-sidebar-primary motion-safe:group-hover/link:animate-nav-icon",
|
|
||||||
active && "text-sidebar-primary",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
{!collapsed && <span className="truncate">{item.label}</span>}
|
{!collapsed && <span className="truncate">{item.label}</span>}
|
||||||
{count > 0 ? (
|
{count > 0 ? (
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"grid place-items-center rounded-full font-semibold tabular-nums",
|
"grid place-items-center rounded-full font-semibold tabular-nums",
|
||||||
item.badgeTone === "warning" ? "bg-warning text-sidebar-on-warning" : "bg-coral text-white",
|
item.badgeTone === "warning" ? "bg-warning text-sidebar" : "bg-coral text-white",
|
||||||
collapsed
|
collapsed
|
||||||
? "absolute top-0.5 right-1 min-w-4 px-1 text-3xs leading-4 ring-2 ring-sidebar"
|
? "absolute top-0.5 right-1 min-w-4 px-1 text-3xs leading-4 ring-2 ring-sidebar"
|
||||||
: "ml-auto min-w-5 px-1.5 text-2xs leading-5 ring-1 ring-sidebar-ink/10",
|
: "ml-auto min-w-5 px-1.5 text-2xs leading-5",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{count > 999 ? "999+" : count}
|
{count > 999 ? "999+" : count}
|
||||||
|
|
@ -295,7 +237,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
collapsed ? (
|
collapsed ? (
|
||||||
<span className="absolute top-1 right-1.5 size-2 rounded-full bg-sidebar-primary ring-2 ring-sidebar" />
|
<span className="absolute top-1 right-1.5 size-2 rounded-full bg-sidebar-primary ring-2 ring-sidebar" />
|
||||||
) : (
|
) : (
|
||||||
<span className="ml-auto rounded-md bg-sidebar-ink/10 px-1.5 text-2xs leading-5 font-semibold text-sidebar-foreground">
|
<span className="ml-auto rounded-md bg-white/10 px-1.5 text-2xs leading-5 font-semibold text-sidebar-foreground">
|
||||||
{tabs.length}
|
{tabs.length}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
|
|
@ -305,24 +247,22 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
|
|
||||||
{/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */}
|
{/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */}
|
||||||
{!collapsed && tabs.length > 0 && (
|
{!collapsed && tabs.length > 0 && (
|
||||||
<ul className="mt-0.5 ml-[21px] space-y-px border-l border-sidebar-border/80 py-0.5 pl-2.5">
|
<ul className="mt-0.5 ml-[21px] space-y-px border-l border-sidebar-border py-1 pl-2">
|
||||||
{visible.map((tab) => {
|
{visible.map((tab) => {
|
||||||
const here = isHere(tab)
|
const here = isHere(tab)
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={tab.id}
|
key={tab.id}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/item flex h-7.5 items-center rounded-md text-sm transition-colors",
|
"group/item flex h-7 items-center rounded-md text-sm transition-colors",
|
||||||
here
|
here ? "bg-white/[0.06] text-white" : "text-sidebar-muted hover:bg-white/[0.03] hover:text-sidebar-foreground",
|
||||||
? "bg-sidebar-ink/[0.07] text-sidebar-strong ring-1 ring-inset ring-sidebar-ink/[0.04]"
|
|
||||||
: "text-sidebar-muted hover:bg-sidebar-ink/[0.04] hover:text-sidebar-foreground",
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigate(tab.href)}
|
onClick={() => navigate(tab.href)}
|
||||||
title={tab.alert ? `${tab.label} · ${tab.alert}` : tab.label}
|
title={tab.alert ? `${tab.label} · ${tab.alert}` : tab.label}
|
||||||
className="flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left outline-none focus-visible:text-sidebar-strong"
|
className="flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left"
|
||||||
>
|
>
|
||||||
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-sidebar-muted"))} />
|
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-sidebar-muted"))} />
|
||||||
<span className="truncate">{tab.label}</span>
|
<span className="truncate">{tab.label}</span>
|
||||||
|
|
@ -335,7 +275,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
type="button"
|
type="button"
|
||||||
aria-label={`Закрыть ${tab.label}`}
|
aria-label={`Закрыть ${tab.label}`}
|
||||||
onClick={() => closeTab(item.tabsSection!, tab.id)}
|
onClick={() => closeTab(item.tabsSection!, tab.id)}
|
||||||
className="absolute inset-0.5 grid place-items-center rounded text-sidebar-muted opacity-0 transition group-hover/item:opacity-100 hover:bg-sidebar-ink/10 hover:text-sidebar-strong focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-primary/60"
|
className="absolute inset-0.5 grid place-items-center rounded text-sidebar-muted opacity-0 transition group-hover/item:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100"
|
||||||
>
|
>
|
||||||
<XIcon className="size-3.5" />
|
<XIcon className="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -349,7 +289,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-2xs text-sidebar-muted transition hover:bg-sidebar-ink/[0.04] hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-primary/60 data-[state=open]:bg-sidebar-ink/[0.04] data-[state=open]:text-sidebar-foreground"
|
className="flex h-6 w-full items-center gap-1.5 rounded-md px-2 text-2xs text-sidebar-muted transition hover:bg-white/[0.03] hover:text-sidebar-foreground data-[state=open]:text-sidebar-foreground"
|
||||||
>
|
>
|
||||||
ещё {hidden.length}
|
ещё {hidden.length}
|
||||||
{hidden.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}
|
{hidden.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}
|
||||||
|
|
@ -389,76 +329,25 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function SidebarActionLink({ action, collapsed }: { action: SidebarAction; collapsed: boolean }) {
|
|
||||||
const Icon = action.icon
|
|
||||||
const { pathname } = useShell()
|
|
||||||
const active = action.match ? action.match(pathname) : isUnder(pathname, action.to)
|
|
||||||
const count = action.badge ?? 0
|
|
||||||
const label = count > 0 ? `${action.label}: ${count}` : action.label
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<ShellLink
|
|
||||||
href={action.to}
|
|
||||||
aria-label={label}
|
|
||||||
aria-current={active ? "page" : undefined}
|
|
||||||
className={cn(
|
|
||||||
"group/link relative grid size-8 shrink-0 place-items-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
|
||||||
active
|
|
||||||
? "bg-sidebar-accent text-sidebar-strong ring-1 ring-inset ring-sidebar-ink/[0.05]"
|
|
||||||
: "text-sidebar-foreground/80 hover:bg-sidebar-ink/[0.07] hover:text-sidebar-strong",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
className={cn(
|
|
||||||
"size-[18px] shrink-0 transition-colors group-hover/link:text-sidebar-primary motion-safe:group-hover/link:animate-nav-icon",
|
|
||||||
active && "text-sidebar-primary",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
{count > 0 && (
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"absolute top-1 right-1 size-1.5 rounded-full ring-2 ring-sidebar",
|
|
||||||
action.badgeTone === "warning" ? "bg-warning" : "bg-coral",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</ShellLink>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side={collapsed ? "right" : "bottom"}>{label}</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) {
|
function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) {
|
||||||
const presence = user.presence ? PRESENCE[user.presence] : null
|
|
||||||
const trigger = (
|
const trigger = (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label={collapsed ? [user.name, presence?.label].filter(Boolean).join(", ") : undefined}
|
aria-label={collapsed ? user.name : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex min-w-0 items-center gap-2.5 rounded-lg text-left transition-colors hover:bg-sidebar-ink/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
"flex min-w-0 items-center gap-2.5 rounded-lg p-1.5 text-left transition hover:bg-white/[0.05]",
|
||||||
collapsed ? "size-9 justify-center p-0" : "flex-1 p-1.5",
|
collapsed ? "justify-center" : "flex-1",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span className="relative shrink-0">
|
|
||||||
<Avatar className="size-8 rounded-lg">
|
<Avatar className="size-8 rounded-lg">
|
||||||
<AvatarFallback className="rounded-lg bg-sidebar-primary/20 text-xs font-semibold text-sidebar-primary">
|
<AvatarFallback className="rounded-lg bg-sidebar-primary/20 text-xs font-semibold text-sidebar-primary">
|
||||||
{user.initials}
|
{user.initials}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
{user.presence && (
|
|
||||||
<span title={presence?.label} className="absolute -right-0.5 -bottom-0.5 flex">
|
|
||||||
<PresenceDot presence={user.presence} className="size-2.5 ring-2 ring-sidebar" />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
{!collapsed && (
|
{!collapsed && (
|
||||||
<div className="min-w-0 flex-1 leading-tight">
|
<div className="min-w-0 flex-1 leading-tight">
|
||||||
<div className="truncate text-sm font-semibold text-sidebar-strong">{user.name}</div>
|
<div className="truncate text-sm font-semibold text-white">{user.name}</div>
|
||||||
{user.subtitle && <div className="truncate text-xs text-sidebar-muted">{user.subtitle}</div>}
|
{user.subtitle && <div className="truncate text-xs text-sidebar-muted">{user.subtitle}</div>}
|
||||||
{presence && <span className="sr-only">{presence.label}</span>}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -483,7 +372,7 @@ function SidebarIconButton({ label, onClick, children }: { label: string; onClic
|
||||||
type="button"
|
type="button"
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
className="grid size-8 shrink-0 place-items-center rounded-lg text-sidebar-muted transition-colors hover:bg-sidebar-ink/[0.07] hover:text-sidebar-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60 [&_svg]:size-4"
|
className="grid size-8 shrink-0 place-items-center rounded-lg text-sidebar-muted transition hover:bg-white/[0.06] hover:text-white [&_svg]:size-4"
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ export function Autocomplete<T>({
|
||||||
getKey,
|
getKey,
|
||||||
getLabel,
|
getLabel,
|
||||||
renderOption,
|
renderOption,
|
||||||
renderValue,
|
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
searchDelay = 300,
|
searchDelay = 300,
|
||||||
minSearchLength = 0,
|
minSearchLength = 0,
|
||||||
|
|
@ -45,8 +44,6 @@ export function Autocomplete<T>({
|
||||||
getLabel: (option: T) => string
|
getLabel: (option: T) => string
|
||||||
/** Строка списка; по умолчанию — `getLabel`. */
|
/** Строка списка; по умолчанию — `getLabel`. */
|
||||||
renderOption?: (option: T) => React.ReactNode
|
renderOption?: (option: T) => React.ReactNode
|
||||||
/** Расширенное представление выбранного значения внутри поля. */
|
|
||||||
renderValue?: (option: T) => React.ReactNode
|
|
||||||
/** Задан — варианты ищет сервер, сами не фильтруем. */
|
/** Задан — варианты ищет сервер, сами не фильтруем. */
|
||||||
onSearchChange?: (search: string) => void
|
onSearchChange?: (search: string) => void
|
||||||
searchDelay?: number
|
searchDelay?: number
|
||||||
|
|
@ -99,7 +96,6 @@ export function Autocomplete<T>({
|
||||||
const activeKey = keys.includes(active) ? active : (keys[0] ?? "")
|
const activeKey = keys.includes(active) ? active : (keys[0] ?? "")
|
||||||
// вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна
|
// вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна
|
||||||
const hasContent = tooShort ? !!hint && !(query === null && value) : true
|
const hasContent = tooShort ? !!hint && !(query === null && value) : true
|
||||||
const richValue = value && query === null && renderValue ? renderValue(value) : null
|
|
||||||
|
|
||||||
const pick = (option: T) => {
|
const pick = (option: T) => {
|
||||||
onChange(option)
|
onChange(option)
|
||||||
|
|
@ -108,16 +104,6 @@ export function Autocomplete<T>({
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const beginEdit = () => {
|
|
||||||
if (disabled) return
|
|
||||||
setQuery(text)
|
|
||||||
setOpen(true)
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
inputRef.current?.focus()
|
|
||||||
inputRef.current?.select()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const restore = () => {
|
const restore = () => {
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
setQuery(null)
|
setQuery(null)
|
||||||
|
|
@ -136,25 +122,10 @@ export function Autocomplete<T>({
|
||||||
>
|
>
|
||||||
<Popover open={open && hasContent && !disabled} onOpenChange={(next) => !next && setOpen(false)}>
|
<Popover open={open && hasContent && !disabled} onOpenChange={(next) => !next && setOpen(false)}>
|
||||||
<PopoverAnchor asChild>
|
<PopoverAnchor asChild>
|
||||||
<div ref={anchorRef} className="w-full">
|
<InputGroup ref={anchorRef} data-disabled={disabled || undefined}>
|
||||||
<InputGroup
|
<InputGroupAddon>
|
||||||
data-disabled={disabled || undefined}
|
|
||||||
className={cn(richValue && "h-auto min-h-12")}
|
|
||||||
>
|
|
||||||
{!richValue && <InputGroupAddon>
|
|
||||||
<SearchIcon />
|
<SearchIcon />
|
||||||
</InputGroupAddon>}
|
</InputGroupAddon>
|
||||||
{richValue && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={disabled}
|
|
||||||
aria-label={`Изменить: ${getLabel(value!)}`}
|
|
||||||
onClick={beginEdit}
|
|
||||||
className="min-w-0 flex-1 px-2.5 py-1.5 text-left disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{richValue}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<CommandPrimitive.Input
|
<CommandPrimitive.Input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
id={id}
|
id={id}
|
||||||
|
|
@ -166,10 +137,7 @@ export function Autocomplete<T>({
|
||||||
setOpen(true)
|
setOpen(true)
|
||||||
if (!next && value) onChange(null)
|
if (!next && value) onChange(null)
|
||||||
}}
|
}}
|
||||||
onFocus={() => {
|
onFocus={() => setOpen(true)}
|
||||||
if (richValue) setQuery(text)
|
|
||||||
setOpen(true)
|
|
||||||
}}
|
|
||||||
onClick={() => setOpen(true)}
|
onClick={() => setOpen(true)}
|
||||||
onBlur={restore}
|
onBlur={restore}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
|
|
@ -181,10 +149,7 @@ export function Autocomplete<T>({
|
||||||
aria-label={ariaLabel ?? placeholder}
|
aria-label={ariaLabel ?? placeholder}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
className={cn(
|
className="h-full min-w-0 flex-1 bg-transparent pr-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
"h-full min-w-0 flex-1 bg-transparent pr-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
richValue && "sr-only",
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
{(loading || (text && !disabled)) && (
|
{(loading || (text && !disabled)) && (
|
||||||
<InputGroupAddon align="inline-end">
|
<InputGroupAddon align="inline-end">
|
||||||
|
|
@ -210,7 +175,6 @@ export function Autocomplete<T>({
|
||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
)}
|
)}
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</div>
|
|
||||||
</PopoverAnchor>
|
</PopoverAnchor>
|
||||||
<PopoverContent
|
<PopoverContent
|
||||||
align="start"
|
align="start"
|
||||||
|
|
|
||||||
|
|
@ -47,9 +47,8 @@ const toneClass: Record<ChipTone, Record<ChipVariant | "hover", string>> = {
|
||||||
}
|
}
|
||||||
|
|
||||||
const sizeClass = {
|
const sizeClass = {
|
||||||
sm: { root: "h-5 gap-1 px-1.5 text-2xs", remove: "pr-0.5", x: "size-4", count: "text-2xs" },
|
sm: { root: "h-5 gap-1 px-1.5 text-2xs", remove: "pr-0.5", x: "size-4" },
|
||||||
md: { root: "h-6 gap-1.5 px-2.5 text-xs", remove: "pr-1", x: "size-4.5", count: "text-2xs" },
|
md: { root: "h-6 gap-1.5 px-2.5 text-xs", remove: "pr-1", x: "size-4.5" },
|
||||||
lg: { root: "h-8 gap-2 px-3 text-sm [&_svg]:size-3.5", remove: "pr-1.5", x: "size-5.5", count: "text-xs" },
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -73,7 +72,7 @@ export function Chip({
|
||||||
}: {
|
}: {
|
||||||
tone?: ChipTone
|
tone?: ChipTone
|
||||||
variant?: ChipVariant
|
variant?: ChipVariant
|
||||||
size?: "sm" | "md" | "lg"
|
size?: "sm" | "md"
|
||||||
selected?: boolean
|
selected?: boolean
|
||||||
onClick?: () => void
|
onClick?: () => void
|
||||||
count?: number
|
count?: number
|
||||||
|
|
@ -101,7 +100,7 @@ export function Chip({
|
||||||
<>
|
<>
|
||||||
{icon}
|
{icon}
|
||||||
{children}
|
{children}
|
||||||
{count != null && <span className={cn("font-mono tabular-nums opacity-70", sizes.count)}>{count}</span>}
|
{count != null && <span className="font-mono text-2xs tabular-nums opacity-70">{count}</span>}
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,15 @@ import { copyToClipboard } from "../lib/clipboard"
|
||||||
/** Фрагмент кода с кнопкой копирования. */
|
/** Фрагмент кода с кнопкой копирования. */
|
||||||
export function CodeBlock({ code, className }: { code: string; className?: string }) {
|
export function CodeBlock({ code, className }: { code: string; className?: string }) {
|
||||||
return (
|
return (
|
||||||
<div className={cn("relative", className)}>
|
<div className={cn("group relative", className)}>
|
||||||
<pre className="overflow-x-auto rounded-xl border bg-muted/60 p-3 pr-12 font-mono text-ui leading-relaxed text-foreground/90 sm:p-4 sm:pr-12">
|
<pre className="overflow-x-auto rounded-xl bg-muted/70 p-4 font-mono text-ui leading-relaxed text-foreground/90">
|
||||||
<code>{code}</code>
|
<code>{code}</code>
|
||||||
</pre>
|
</pre>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label="Скопировать код"
|
aria-label="Скопировать код"
|
||||||
onClick={() => copyToClipboard(code, "Код скопирован")}
|
onClick={() => copyToClipboard(code, "Код скопирован")}
|
||||||
className="absolute top-2 right-2 grid size-7 place-items-center rounded-md border bg-card text-muted-foreground shadow-xs transition hover:text-foreground focus:ring-[3px] focus:ring-ring/50 focus:outline-none"
|
className="absolute top-2 right-2 grid size-7 place-items-center rounded-md bg-card text-muted-foreground opacity-0 shadow-xs transition group-hover:opacity-100 hover:text-foreground"
|
||||||
>
|
>
|
||||||
<CopyIcon className="size-3.5" />
|
<CopyIcon className="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
|
|
@ -48,8 +48,7 @@ export function ContentTabs<T extends string>({
|
||||||
variant === "line" && "px-3",
|
variant === "line" && "px-3",
|
||||||
variant === "line" && !actions && "border-b",
|
variant === "line" && !actions && "border-b",
|
||||||
variant === "line" && actions && "min-w-0 flex-1 self-end",
|
variant === "line" && actions && "min-w-0 flex-1 self-end",
|
||||||
// h-9 и p-0.5: внешняя высота как у поля (36px), кнопки h-8 внутри.
|
variant === "pill" && "w-fit max-w-full rounded-xl bg-muted/70 p-1",
|
||||||
variant === "pill" && "h-9 w-fit max-w-full rounded-xl bg-muted/70 p-0.5",
|
|
||||||
!actions && className,
|
!actions && className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import { nextSort, sortRows, type DataColumn } from "./data-table"
|
|
||||||
|
|
||||||
interface Row {
|
|
||||||
name: string
|
|
||||||
age: number
|
|
||||||
}
|
|
||||||
|
|
||||||
const columns: DataColumn<Row>[] = [
|
|
||||||
{ id: "name", header: "Имя", cell: (row) => row.name, sort: (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) },
|
|
||||||
{ id: "age", header: "Возраст", cell: (row) => row.age, sort: (a, b) => a.age - b.age },
|
|
||||||
]
|
|
||||||
|
|
||||||
const rows: Row[] = [
|
|
||||||
{ name: "Борис", age: 40 },
|
|
||||||
{ name: "Анна", age: 30 },
|
|
||||||
]
|
|
||||||
|
|
||||||
describe("nextSort", () => {
|
|
||||||
it("крутит колонку: по возрастанию, по убыванию, без сортировки", () => {
|
|
||||||
expect(nextSort(null, "name")).toEqual({ id: "name", direction: "asc" })
|
|
||||||
expect(nextSort({ id: "name", direction: "asc" }, "name")).toEqual({ id: "name", direction: "desc" })
|
|
||||||
expect(nextSort({ id: "name", direction: "desc" }, "name")).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it("клик по другой колонке начинает с возрастания", () => {
|
|
||||||
expect(nextSort({ id: "name", direction: "desc" }, "age")).toEqual({ id: "age", direction: "asc" })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("sortRows", () => {
|
|
||||||
it("сортирует копию и без сортировки сохраняет порядок", () => {
|
|
||||||
expect(sortRows(rows, columns, { id: "name", direction: "asc" }).map((row) => row.name)).toEqual(["Анна", "Борис"])
|
|
||||||
expect(sortRows(rows, columns, { id: "age", direction: "desc" }).map((row) => row.age)).toEqual([40, 30])
|
|
||||||
expect(sortRows(rows, columns, null)).toEqual(rows)
|
|
||||||
expect(sortRows(rows, columns, null)).not.toBe(rows)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -57,53 +57,13 @@ export function nextSort(current: SortState | null, id: string): SortState | nul
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
|
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
|
||||||
* кликабельные строки (мышь, Tab, Enter и пробел; кнопка и ссылка внутри строки не открывают её).
|
* кликабельные строки. Строки передаются уже отсортированными/порезанными
|
||||||
* Строки передаются уже отсортированными/порезанными
|
|
||||||
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
|
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
|
||||||
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
|
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
|
||||||
* Ширина считается по контейнеру, а не по окну: колонки с `minWidth` прячутся, когда места мало,
|
* Ширина считается по контейнеру, а не по окну: колонки с `minWidth` прячутся, когда места мало,
|
||||||
* `grow`-колонка сжимается первой, а уже `cardsBelow` (640px) строки показываются карточками `renderCard`.
|
* `grow`-колонка сжимается первой, а уже `cardsBelow` (640px) строки показываются карточками `renderCard`.
|
||||||
* Если колонки всё равно не влезают — оберните таблицу в `<ScrollArea horizontal>`.
|
* Если колонки всё равно не влезают — оберните таблицу в `<ScrollArea horizontal>`.
|
||||||
*/
|
*/
|
||||||
/**
|
|
||||||
* Линия строки. У последней — тень вместо border: тень не входит в область прокрутки,
|
|
||||||
* поэтому в растянутой таблице линия видна, а у прокрученной до конца не задваивается с рамкой снизу.
|
|
||||||
*/
|
|
||||||
const rowLine =
|
|
||||||
"border-b border-border/60 last:border-b-0 last:*:shadow-[0_1px_0_color-mix(in_oklab,var(--border)_60%,transparent)]"
|
|
||||||
|
|
||||||
/** Клик или клавиша пришли из кнопки, ссылки или поля внутри строки — строку не открываем. */
|
|
||||||
const nestedControl = "a, button, input, textarea, select, [role='button'], [role='link'], [role='checkbox'], [role='menuitem']"
|
|
||||||
|
|
||||||
function isNestedControl(event: React.SyntheticEvent) {
|
|
||||||
const target = event.target
|
|
||||||
if (!(target instanceof Element) || target === event.currentTarget) return false
|
|
||||||
return Boolean(target.closest(nestedControl))
|
|
||||||
}
|
|
||||||
|
|
||||||
function rowActivate<T>(
|
|
||||||
row: T,
|
|
||||||
onRowClick: ((row: T, event: React.MouseEvent | React.KeyboardEvent) => void) | undefined,
|
|
||||||
extra: React.HTMLAttributes<HTMLElement> | undefined,
|
|
||||||
) {
|
|
||||||
if (!onRowClick) return {}
|
|
||||||
return {
|
|
||||||
tabIndex: extra?.tabIndex ?? 0,
|
|
||||||
onClick: (event: React.MouseEvent<HTMLElement>) => {
|
|
||||||
extra?.onClick?.(event)
|
|
||||||
if (event.defaultPrevented || isNestedControl(event)) return
|
|
||||||
onRowClick(row, event)
|
|
||||||
},
|
|
||||||
onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => {
|
|
||||||
extra?.onKeyDown?.(event)
|
|
||||||
if (event.defaultPrevented || isNestedControl(event)) return
|
|
||||||
if (event.key !== "Enter" && event.key !== " ") return
|
|
||||||
event.preventDefault()
|
|
||||||
onRowClick(row, event)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DataTable<T>({
|
export function DataTable<T>({
|
||||||
columns,
|
columns,
|
||||||
rows,
|
rows,
|
||||||
|
|
@ -124,7 +84,7 @@ export function DataTable<T>({
|
||||||
getRowId: (row: T) => React.Key
|
getRowId: (row: T) => React.Key
|
||||||
sort?: SortState | null
|
sort?: SortState | null
|
||||||
onSortChange?: (sort: SortState | null) => void
|
onSortChange?: (sort: SortState | null) => void
|
||||||
onRowClick?: (row: T, event: React.MouseEvent | React.KeyboardEvent) => void
|
onRowClick?: (row: T, event: React.MouseEvent) => void
|
||||||
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
|
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
|
||||||
rowClassName?: (row: T, index: number) => string | false | undefined
|
rowClassName?: (row: T, index: number) => string | false | undefined
|
||||||
empty?: React.ReactNode
|
empty?: React.ReactNode
|
||||||
|
|
@ -162,10 +122,10 @@ export function DataTable<T>({
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={getRowId(row)}
|
key={getRowId(row)}
|
||||||
{...rowActivate(row, onRowClick, extra)}
|
onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"px-4 py-3 transition-colors",
|
"px-4 py-3 transition-colors",
|
||||||
onRowClick && "cursor-pointer active:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
|
onRowClick && "cursor-pointer active:bg-muted/60",
|
||||||
rowClassName?.(row, i),
|
rowClassName?.(row, i),
|
||||||
extra?.className,
|
extra?.className,
|
||||||
)}
|
)}
|
||||||
|
|
@ -185,7 +145,7 @@ export function DataTable<T>({
|
||||||
<table className={cn("w-full text-sm", className)}>
|
<table className={cn("w-full text-sm", className)}>
|
||||||
{/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */}
|
{/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */}
|
||||||
<thead className="sticky top-0 z-10">
|
<thead className="sticky top-0 z-10">
|
||||||
<tr className="text-left text-ui text-muted-foreground">
|
<tr className="text-left text-xs text-muted-foreground">
|
||||||
{visible.map((col) => {
|
{visible.map((col) => {
|
||||||
const active = sort?.id === col.id
|
const active = sort?.id === col.id
|
||||||
const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon
|
const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon
|
||||||
|
|
@ -227,11 +187,10 @@ export function DataTable<T>({
|
||||||
<tr
|
<tr
|
||||||
key={getRowId(row)}
|
key={getRowId(row)}
|
||||||
{...extra}
|
{...extra}
|
||||||
{...rowActivate(row, onRowClick, extra)}
|
onClick={onRowClick ? (e) => onRowClick(row, e) : extra?.onClick}
|
||||||
className={cn(
|
className={cn(
|
||||||
rowLine,
|
"border-b border-border/60 transition-colors last:border-b-0",
|
||||||
"transition-colors",
|
onRowClick && "cursor-pointer hover:bg-muted/50",
|
||||||
onRowClick && "cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
|
|
||||||
rowClassName?.(row, i),
|
rowClassName?.(row, i),
|
||||||
extra?.className,
|
extra?.className,
|
||||||
)}
|
)}
|
||||||
|
|
@ -246,7 +205,7 @@ export function DataTable<T>({
|
||||||
})}
|
})}
|
||||||
{skeleton &&
|
{skeleton &&
|
||||||
Array.from({ length: 6 }, (_, i) => (
|
Array.from({ length: 6 }, (_, i) => (
|
||||||
<tr key={i} className={rowLine}>
|
<tr key={i} className="border-b border-border/60 last:border-b-0">
|
||||||
{visible.map((col, c) => (
|
{visible.map((col, c) => (
|
||||||
<td key={col.id} className="px-3 py-3.5 first:pl-5 last:pr-5">
|
<td key={col.id} className="px-3 py-3.5 first:pl-5 last:pr-5">
|
||||||
<Skeleton className={cn("h-3.5", c === 0 ? "w-12" : c % 2 ? "w-3/4" : "w-1/2")} />
|
<Skeleton className={cn("h-3.5", c === 0 ? "w-12" : c % 2 ? "w-3/4" : "w-1/2")} />
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,7 @@ export interface DateLimits {
|
||||||
/** Почему введённый текст не стал датой; undefined — всё в порядке (или поле пустое). */
|
/** Почему введённый текст не стал датой; undefined — всё в порядке (или поле пустое). */
|
||||||
export function dateTextError(text: string, { min, max }: DateLimits = {}) {
|
export function dateTextError(text: string, { min, max }: DateLimits = {}) {
|
||||||
if (!text) return undefined
|
if (!text) return undefined
|
||||||
// «_» — дырка на месте стёртой цифры: дата ещё не дописана, даже если строка уже длины 10.
|
if (text.length < 10) return "Дата в формате дд.мм.гггг"
|
||||||
if (text.includes("_") || text.length < 10) return "Дата в формате дд.мм.гггг"
|
|
||||||
const date = parseRuDate(text)
|
const date = parseRuDate(text)
|
||||||
if (!date) return "Такой даты нет"
|
if (!date) return "Такой даты нет"
|
||||||
if (min && date < startOfDay(min)) return `Не раньше ${formatRuDate(min)}`
|
if (min && date < startOfDay(min)) return `Не раньше ${formatRuDate(min)}`
|
||||||
|
|
@ -53,7 +52,6 @@ export function useDateText(value: Date | null, onChange: (date: Date | null) =>
|
||||||
text,
|
text,
|
||||||
maskDate,
|
maskDate,
|
||||||
isDatePrefixValid,
|
isDatePrefixValid,
|
||||||
"_",
|
|
||||||
)
|
)
|
||||||
setText(next)
|
setText(next)
|
||||||
setCaret(e.target, caret)
|
setCaret(e.target, caret)
|
||||||
|
|
@ -69,18 +67,12 @@ export function useDateText(value: Date | null, onChange: (date: Date | null) =>
|
||||||
}
|
}
|
||||||
|
|
||||||
const error = dateTextError(text, limits)
|
const error = dateTextError(text, limits)
|
||||||
// Неполную дату и дырку в маске не ругаем, пока человек печатает.
|
// Неполную дату не ругаем, пока человек печатает.
|
||||||
const complete = text.length === 10 && !text.includes("_")
|
const shownError = error && (touched || text.length === 10) ? error : undefined
|
||||||
const shownError = error && (touched || complete) ? error : undefined
|
|
||||||
|
|
||||||
return { text, change, set, error, shownError, onBlur: () => setTouched(true) }
|
return { text, change, set, error, shownError, onBlur: () => setTouched(true) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Список месяца и года рисуется порталом вне попапа календаря. */
|
|
||||||
function inSelectLayer(target: EventTarget | null) {
|
|
||||||
return target instanceof Element && Boolean(target.closest("[data-slot=select-content]"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Состояние попапа с календарём у поля ввода: при каждом открытии календарь показывает
|
* Состояние попапа с календарём у поля ввода: при каждом открытии календарь показывает
|
||||||
* месяц текущего значения, а после закрытия (выбор, Esc, кнопка) фокус возвращается в поле —
|
* месяц текущего значения, а после закрытия (выбор, Esc, кнопка) фокус возвращается в поле —
|
||||||
|
|
@ -104,13 +96,9 @@ export function useCalendarPopover(initialMonth: () => Date) {
|
||||||
const contentProps = {
|
const contentProps = {
|
||||||
onInteractOutside: (e: Event) => {
|
onInteractOutside: (e: Event) => {
|
||||||
// Кнопка календаря сама закроет попап своим кликом, иначе он тут же откроется снова.
|
// Кнопка календаря сама закроет попап своим кликом, иначе он тут же откроется снова.
|
||||||
// Список месяца и года — в портале, вне попапа: клик по нему не закрывает календарь.
|
if (toggleRef.current?.contains(e.target as Node)) e.preventDefault()
|
||||||
if (toggleRef.current?.contains(e.target as Node) || inSelectLayer(e.target)) e.preventDefault()
|
|
||||||
else clickedOutside.current = true
|
else clickedOutside.current = true
|
||||||
},
|
},
|
||||||
onFocusOutside: (e: Event) => {
|
|
||||||
if (inSelectLayer(e.target)) e.preventDefault()
|
|
||||||
},
|
|
||||||
onCloseAutoFocus: (e: Event) => {
|
onCloseAutoFocus: (e: Event) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (!clickedOutside.current) returnFocus.current?.focus()
|
if (!clickedOutside.current) returnFocus.current?.focus()
|
||||||
|
|
@ -143,7 +131,7 @@ export function calendarBounds({ min, max }: DateLimits, captionLayout: "label"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Дата: ввод вручную по маске «дд.мм.гггг» или выбор в календаре (кнопка, Alt+↓).
|
* Дата: ввод вручную по маске «дд.мм.гггг» или выбор в календаре (кнопка, Alt+↓).
|
||||||
* captionLayout="dropdown" — месяц списком. yearCaption="input" — год полем из четырёх цифр.
|
* captionLayout="dropdown" — месяц и год списками, удобно для даты рождения.
|
||||||
*/
|
*/
|
||||||
export function DateInput({
|
export function DateInput({
|
||||||
value,
|
value,
|
||||||
|
|
@ -152,8 +140,6 @@ export function DateInput({
|
||||||
max,
|
max,
|
||||||
invalid,
|
invalid,
|
||||||
captionLayout = "label",
|
captionLayout = "label",
|
||||||
yearCaption = "select",
|
|
||||||
calendarAlign = "end",
|
|
||||||
onErrorChange,
|
onErrorChange,
|
||||||
id,
|
id,
|
||||||
disabled,
|
disabled,
|
||||||
|
|
@ -166,10 +152,6 @@ export function DateInput({
|
||||||
/** Подсветить извне (ошибка формы), вдобавок к собственной проверке. */
|
/** Подсветить извне (ошибка формы), вдобавок к собственной проверке. */
|
||||||
invalid?: boolean
|
invalid?: boolean
|
||||||
captionLayout?: "label" | "dropdown"
|
captionLayout?: "label" | "dropdown"
|
||||||
/** Год в шапке календаря. «input» — набрать цифрами, когда список годов длинный. */
|
|
||||||
yearCaption?: "select" | "input"
|
|
||||||
/** Выравнивание всплывающего календаря относительно поля. */
|
|
||||||
calendarAlign?: "start" | "center" | "end"
|
|
||||||
/** Сообщение о неправильном вводе — чтобы показать его в FormField. */
|
/** Сообщение о неправильном вводе — чтобы показать его в FormField. */
|
||||||
onErrorChange?: (error: string | undefined) => void
|
onErrorChange?: (error: string | undefined) => void
|
||||||
id?: string
|
id?: string
|
||||||
|
|
@ -225,13 +207,12 @@ export function DateInput({
|
||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</PopoverAnchor>
|
</PopoverAnchor>
|
||||||
<PopoverContent align={calendarAlign} collisionPadding={8} className="w-auto p-0" {...popover.contentProps}>
|
<PopoverContent align="end" collisionPadding={8} className="w-auto p-0" {...popover.contentProps}>
|
||||||
<Calendar
|
<Calendar
|
||||||
mode="single"
|
mode="single"
|
||||||
required
|
required
|
||||||
autoFocus
|
autoFocus
|
||||||
captionLayout={captionLayout}
|
captionLayout={captionLayout}
|
||||||
yearCaption={yearCaption}
|
|
||||||
selected={value ?? undefined}
|
selected={value ?? undefined}
|
||||||
month={popover.month}
|
month={popover.month}
|
||||||
onMonthChange={popover.setMonth}
|
onMonthChange={popover.setMonth}
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,6 @@ export function DateRangeInput({
|
||||||
min,
|
min,
|
||||||
max,
|
max,
|
||||||
presets = DEFAULT_RANGE_PRESETS,
|
presets = DEFAULT_RANGE_PRESETS,
|
||||||
calendarAlign = "start",
|
|
||||||
invalid,
|
invalid,
|
||||||
onErrorChange,
|
onErrorChange,
|
||||||
disabled,
|
disabled,
|
||||||
|
|
@ -58,8 +57,6 @@ export function DateRangeInput({
|
||||||
onChange: (value: DateRangeValue) => void
|
onChange: (value: DateRangeValue) => void
|
||||||
/** Пустой массив — без быстрых периодов. */
|
/** Пустой массив — без быстрых периодов. */
|
||||||
presets?: readonly DateRangePreset[]
|
presets?: readonly DateRangePreset[]
|
||||||
/** Выравнивание всплывающего календаря относительно поля. */
|
|
||||||
calendarAlign?: "start" | "center" | "end"
|
|
||||||
invalid?: boolean
|
invalid?: boolean
|
||||||
/** Сообщение о неправильном вводе (в том числе перевёрнутом диапазоне) — для FormField. */
|
/** Сообщение о неправильном вводе (в том числе перевёрнутом диапазоне) — для FormField. */
|
||||||
onErrorChange?: (error: string | undefined) => void
|
onErrorChange?: (error: string | undefined) => void
|
||||||
|
|
@ -67,8 +64,6 @@ export function DateRangeInput({
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const wide = useMediaQuery("(min-width: 768px)")
|
const wide = useMediaQuery("(min-width: 768px)")
|
||||||
// У «по» свой id: иначе оба поля заберут id FormField, и подпись укажет на два элемента сразу.
|
|
||||||
const toId = React.useId()
|
|
||||||
const limits = { min, max }
|
const limits = { min, max }
|
||||||
const fromField = useDateText(value.from, (from) => onChange({ ...value, from }), limits)
|
const fromField = useDateText(value.from, (from) => onChange({ ...value, from }), limits)
|
||||||
const toField = useDateText(value.to, (to) => onChange({ ...value, to }), limits)
|
const toField = useDateText(value.to, (to) => onChange({ ...value, to }), limits)
|
||||||
|
|
@ -93,9 +88,7 @@ export function DateRangeInput({
|
||||||
popover.setOpen(false)
|
popover.setOpen(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ширина — по тексту даты плюс отступы поля. 5.2em хватает на «2026»,
|
const input = "w-[6.6rem] flex-none px-2.5 tabular"
|
||||||
// без лишнего хвоста перед «—».
|
|
||||||
const input = "w-[calc(5.2em+1.125rem)] flex-none px-2.5 tabular"
|
|
||||||
// Фокус после закрытия календаря возвращается в то поле, где человек был последним.
|
// Фокус после закрытия календаря возвращается в то поле, где человек был последним.
|
||||||
const remember = (e: React.FocusEvent<HTMLInputElement>) => {
|
const remember = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||||
popover.returnFocus.current = e.currentTarget
|
popover.returnFocus.current = e.currentTarget
|
||||||
|
|
@ -122,7 +115,6 @@ export function DateRangeInput({
|
||||||
/>
|
/>
|
||||||
<InputGroupText className="px-0.5">—</InputGroupText>
|
<InputGroupText className="px-0.5">—</InputGroupText>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
id={toId}
|
|
||||||
aria-label="По"
|
aria-label="По"
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
|
|
@ -136,8 +128,7 @@ export function DateRangeInput({
|
||||||
onKeyDown={popover.onKeyDown}
|
onKeyDown={popover.onKeyDown}
|
||||||
className={input}
|
className={input}
|
||||||
/>
|
/>
|
||||||
{/* ml-auto — у растянутого поля (className="w-full") кнопка остаётся у правого края. */}
|
<InputGroupAddon align="inline-end">
|
||||||
<InputGroupAddon align="inline-end" className="ml-auto">
|
|
||||||
<InputGroupButton
|
<InputGroupButton
|
||||||
size="icon-xs"
|
size="icon-xs"
|
||||||
aria-label="Открыть календарь"
|
aria-label="Открыть календарь"
|
||||||
|
|
@ -150,7 +141,7 @@ export function DateRangeInput({
|
||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</PopoverAnchor>
|
</PopoverAnchor>
|
||||||
<PopoverContent align={calendarAlign} collisionPadding={8} className="flex w-auto max-w-[calc(100vw-1rem)] flex-col p-0 md:flex-row" {...popover.contentProps}>
|
<PopoverContent align="start" collisionPadding={8} className="flex w-auto max-w-[calc(100vw-1rem)] flex-col p-0 md:flex-row" {...popover.contentProps}>
|
||||||
{presets.length > 0 && (
|
{presets.length > 0 && (
|
||||||
<div className="flex gap-1 overflow-x-auto border-b p-2 md:w-44 md:flex-col md:border-r md:border-b-0">
|
<div className="flex gap-1 overflow-x-auto border-b p-2 md:w-44 md:flex-col md:border-r md:border-b-0">
|
||||||
{presets.map((preset) => {
|
{presets.map((preset) => {
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import type { LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
import { Button } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog"
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog"
|
||||||
import { Kbd } from "../ui/kbd"
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -33,12 +32,7 @@ export function EditDialog({
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent
|
<DialogContent className={cn("gap-0 p-0 sm:max-w-xl", className)}>
|
||||||
className={cn(
|
|
||||||
"gap-0 overflow-hidden rounded-xl border-0 p-0 shadow-2xl ring-1 ring-primary/15 sm:max-w-xl",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<form
|
<form
|
||||||
noValidate
|
noValidate
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
|
|
@ -46,22 +40,15 @@ export function EditDialog({
|
||||||
if (canSave) onSave()
|
if (canSave) onSave()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DialogHeader className="flex-row items-center gap-3 border-b border-primary/10 bg-primary/5 px-5 py-4 pr-12 text-left sm:text-left">
|
<DialogHeader className="border-b px-5 py-4">
|
||||||
{Icon && (
|
<DialogTitle className="flex items-center gap-2 text-base">
|
||||||
<span className="grid size-9 shrink-0 place-items-center rounded-lg bg-primary text-primary-foreground shadow-sm shadow-primary/30">
|
{Icon && <Icon className="size-4 text-primary" />}
|
||||||
<Icon className="size-4.5" />
|
{title}
|
||||||
</span>
|
</DialogTitle>
|
||||||
)}
|
|
||||||
<div className="min-w-0 space-y-0.5">
|
|
||||||
<DialogTitle className="text-base">{title}</DialogTitle>
|
|
||||||
{description && <DialogDescription className="text-xs">{description}</DialogDescription>}
|
{description && <DialogDescription className="text-xs">{description}</DialogDescription>}
|
||||||
</div>
|
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="space-y-4 px-5 py-5">{children}</div>
|
<div className="space-y-4 px-5 py-5">{children}</div>
|
||||||
<DialogFooter className="items-center border-t bg-muted/50 px-5 py-3">
|
<DialogFooter className="border-t px-5 py-3">
|
||||||
<span className="mr-auto hidden items-center gap-1.5 text-xs text-muted-foreground sm:flex">
|
|
||||||
<Kbd className="border bg-background">Enter</Kbd> в поле — сохранить
|
|
||||||
</span>
|
|
||||||
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
|
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
|
||||||
Отмена
|
Отмена
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -26,11 +26,11 @@ export interface FileItem {
|
||||||
|
|
||||||
export type FileGallerySize = "sm" | "md" | "lg"
|
export type FileGallerySize = "sm" | "md" | "lg"
|
||||||
|
|
||||||
export function isImageFile(file: Pick<FileItem, "name" | "type">) {
|
export function isImageFile(file: FileItem) {
|
||||||
return Boolean(file.type?.startsWith("image/")) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(file.name)
|
return Boolean(file.type?.startsWith("image/")) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(file.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isPdfFile(file: Pick<FileItem, "name" | "type">) {
|
export function isPdfFile(file: FileItem) {
|
||||||
return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name)
|
return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import { fileKind } from "./file-type-icon"
|
|
||||||
|
|
||||||
describe("fileKind", () => {
|
|
||||||
it.each([
|
|
||||||
["analizy.PDF", "pdf"],
|
|
||||||
["snimok.jpeg", "image"],
|
|
||||||
["napravlenie.docx", "document"],
|
|
||||||
["zametka.txt", "document"],
|
|
||||||
["prays.xlsx", "sheet"],
|
|
||||||
["vygruzka.csv", "sheet"],
|
|
||||||
["doklad.pptx", "slides"],
|
|
||||||
["seriya.7z", "archive"],
|
|
||||||
["dannye.bin", "other"],
|
|
||||||
["bez-rasshireniya", "other"],
|
|
||||||
])("%s → %s", (name, kind) => {
|
|
||||||
expect(fileKind({ name })).toBe(kind)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("без расширения смотрит на тип из браузера", () => {
|
|
||||||
expect(fileKind({ name: "snimok", type: "image/png" })).toBe("image")
|
|
||||||
expect(fileKind({ name: "otchet", type: "application/pdf" })).toBe("pdf")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
import {
|
|
||||||
FileArchiveIcon,
|
|
||||||
FileIcon,
|
|
||||||
FileSpreadsheetIcon,
|
|
||||||
FileTextIcon,
|
|
||||||
ImageIcon,
|
|
||||||
PresentationIcon,
|
|
||||||
type LucideIcon,
|
|
||||||
} from "lucide-react"
|
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
import { isImageFile, isPdfFile, type FileItem } from "./file-gallery"
|
|
||||||
|
|
||||||
export type FileKind = "pdf" | "image" | "document" | "sheet" | "slides" | "archive" | "other"
|
|
||||||
|
|
||||||
const EXTENSION_KIND: Readonly<Record<string, FileKind>> = {
|
|
||||||
doc: "document",
|
|
||||||
docx: "document",
|
|
||||||
odt: "document",
|
|
||||||
rtf: "document",
|
|
||||||
txt: "document",
|
|
||||||
xls: "sheet",
|
|
||||||
xlsx: "sheet",
|
|
||||||
ods: "sheet",
|
|
||||||
csv: "sheet",
|
|
||||||
ppt: "slides",
|
|
||||||
pptx: "slides",
|
|
||||||
odp: "slides",
|
|
||||||
zip: "archive",
|
|
||||||
rar: "archive",
|
|
||||||
"7z": "archive",
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Группа файла по типу из браузера и расширению. */
|
|
||||||
export function fileKind(file: Pick<FileItem, "name" | "type">): FileKind {
|
|
||||||
if (isPdfFile(file)) return "pdf"
|
|
||||||
if (isImageFile(file)) return "image"
|
|
||||||
return EXTENSION_KIND[file.name.split(".").pop()?.toLowerCase() ?? ""] ?? "other"
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Цвет различает группы файлов, а не украшает. */
|
|
||||||
const KIND_STYLE: Readonly<Record<FileKind, { icon: LucideIcon; tone: string }>> = {
|
|
||||||
pdf: { icon: FileTextIcon, tone: "bg-coral-soft text-coral" },
|
|
||||||
image: { icon: ImageIcon, tone: "bg-accent text-primary" },
|
|
||||||
document: { icon: FileTextIcon, tone: "bg-info-soft text-info" },
|
|
||||||
sheet: { icon: FileSpreadsheetIcon, tone: "bg-success-soft text-success" },
|
|
||||||
slides: { icon: PresentationIcon, tone: "bg-warning-soft text-warning" },
|
|
||||||
archive: { icon: FileArchiveIcon, tone: "bg-muted text-muted-foreground" },
|
|
||||||
other: { icon: FileIcon, tone: "bg-muted text-muted-foreground" },
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Значок типа файла: цветная плитка для строк списка. */
|
|
||||||
export function FileTypeIcon({ file, className }: { file: Pick<FileItem, "name" | "type">; className?: string }) {
|
|
||||||
const { icon: Icon, tone } = KIND_STYLE[fileKind(file)]
|
|
||||||
return (
|
|
||||||
<span aria-hidden className={cn("grid size-8 shrink-0 place-items-center rounded-lg", tone, className)}>
|
|
||||||
<Icon className="size-4" />
|
|
||||||
</span>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { RotateCwIcon, SlidersHorizontalIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { Button } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "../ui/popover"
|
import { Label } from "../ui/label"
|
||||||
import { ScrollArea } from "../ui/scroll-area"
|
import { ScrollArea } from "../ui/scroll-area"
|
||||||
import {
|
import {
|
||||||
Sheet,
|
Sheet,
|
||||||
|
|
@ -19,16 +19,14 @@ import { Switch } from "../ui/switch"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Панель фильтров списка: основные фильтры в строку, расширенные (`more`) — в панели справа,
|
* Панель фильтров списка: основные фильтры в строку, расширенные (`more`) — в панели справа,
|
||||||
* которую открывает кнопка «Ещё»; «Ещё» и кнопка сброса — всегда справа.
|
* которую открывает кнопка «Ещё» со счётчиком включённых; «Ещё» и «Сбросить» — всегда справа.
|
||||||
* Поиску внутри дают `className="min-w-40 flex-1"` — он забирает свободное место.
|
* Поиску внутри дают `className="min-w-40 flex-1"` — он забирает свободное место.
|
||||||
* Фильтры в панели применяются сразу, как и в строке; поля внутри — `FormField`, переключатели — `FilterSwitch`.
|
* Фильтры в панели применяются сразу, как и в строке; поля внутри — `FormField`, переключатели — `FilterSwitch`.
|
||||||
* Сама панель — как форма в разделе: заголовок на мягкой подложке, поля на белой карточке.
|
|
||||||
*/
|
*/
|
||||||
export function FilterBar({
|
export function FilterBar({
|
||||||
more,
|
more,
|
||||||
moreCount = 0,
|
moreCount = 0,
|
||||||
moreTitle = "Фильтры",
|
moreTitle = "Фильтры",
|
||||||
moreVariant = "sheet",
|
|
||||||
activeCount = 0,
|
activeCount = 0,
|
||||||
onReset,
|
onReset,
|
||||||
className,
|
className,
|
||||||
|
|
@ -36,13 +34,11 @@ export function FilterBar({
|
||||||
}: {
|
}: {
|
||||||
/** Расширенные фильтры — показываются в панели справа по кнопке «Ещё». */
|
/** Расширенные фильтры — показываются в панели справа по кнопке «Ещё». */
|
||||||
more?: React.ReactNode
|
more?: React.ReactNode
|
||||||
/** Сколько из `more` включено: точка на «Ещё», число — в подсказке. */
|
/** Сколько из `more` включено — счётчик на кнопке «Ещё». */
|
||||||
moreCount?: number
|
moreCount?: number
|
||||||
/** Заголовок панели. */
|
/** Заголовок панели. */
|
||||||
moreTitle?: string
|
moreTitle?: string
|
||||||
/** Как открыть расширенные фильтры: в боковой панели или всплывающим слоем над контентом. */
|
/** Сколько фильтров отличается от умолчания — счётчик и доступность «Сбросить». */
|
||||||
moreVariant?: "sheet" | "popover"
|
|
||||||
/** Сколько фильтров отличается от умолчания: точка на «Сбросить», число — в подсказке. */
|
|
||||||
activeCount?: number
|
activeCount?: number
|
||||||
/** Без него кнопки «Сбросить» нет. */
|
/** Без него кнопки «Сбросить» нет. */
|
||||||
onReset?: () => void
|
onReset?: () => void
|
||||||
|
|
@ -55,170 +51,52 @@ export function FilterBar({
|
||||||
на узкой панели (фильтрам меньше 16rem) кнопки уходят строкой ниже, но остаются справа. */}
|
на узкой панели (фильтрам меньше 16rem) кнопки уходят строкой ниже, но остаются справа. */}
|
||||||
<div className="flex min-w-[min(100%,16rem)] flex-1 flex-wrap items-center gap-2.5">{children}</div>
|
<div className="flex min-w-[min(100%,16rem)] flex-1 flex-wrap items-center gap-2.5">{children}</div>
|
||||||
{(more != null || onReset) && (
|
{(more != null || onReset) && (
|
||||||
<div
|
<div className="ml-auto flex h-9 shrink-0 items-center gap-1">
|
||||||
role="group"
|
|
||||||
aria-label="Действия с фильтрами"
|
|
||||||
className="ml-auto flex h-9 shrink-0 items-center gap-1 rounded-xl bg-muted/70 p-0.5"
|
|
||||||
>
|
|
||||||
{onReset && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon-sm"
|
|
||||||
disabled={!activeCount}
|
|
||||||
onClick={onReset}
|
|
||||||
aria-label="Сбросить фильтры"
|
|
||||||
title={activeCount ? `Сбросить фильтры: ${activeCount}` : "Нет активных фильтров"}
|
|
||||||
className="rounded-lg text-muted-foreground"
|
|
||||||
>
|
|
||||||
<RotateCwIcon />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{more != null && (
|
{more != null && (
|
||||||
moreVariant === "popover" ? (
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<MoreButton moreCount={moreCount} />
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent
|
|
||||||
align="end"
|
|
||||||
sideOffset={8}
|
|
||||||
collisionPadding={8}
|
|
||||||
className="flex max-h-[min(36rem,calc(100vh-1rem))] w-[min(24rem,calc(100vw-1rem))] flex-col overflow-hidden rounded-xl p-0 shadow-lg"
|
|
||||||
>
|
|
||||||
{/* Непрозрачная основа: bg-muted/50 сам по себе просвечивает страницу под слоем. */}
|
|
||||||
<div className="flex min-h-0 flex-1 flex-col bg-muted/50">
|
|
||||||
<MorePanel
|
|
||||||
title={moreTitle}
|
|
||||||
activeCount={activeCount}
|
|
||||||
onReset={onReset}
|
|
||||||
done={
|
|
||||||
<PopoverClose asChild>
|
|
||||||
<Button>Готово</Button>
|
|
||||||
</PopoverClose>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{more}
|
|
||||||
</MorePanel>
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
) : (
|
|
||||||
<Sheet>
|
<Sheet>
|
||||||
<SheetTrigger asChild>
|
<SheetTrigger asChild>
|
||||||
<MoreButton moreCount={moreCount} />
|
<Button variant="outline" size="sm" className="shrink-0">
|
||||||
|
<SlidersHorizontalIcon /> Ещё
|
||||||
|
{moreCount > 0 && <Count value={moreCount} />}
|
||||||
|
</Button>
|
||||||
</SheetTrigger>
|
</SheetTrigger>
|
||||||
{/* Как форма в разделе: мягкая подложка, заголовок, поля на белой карточке. */}
|
<SheetContent side="right" className="gap-0 sm:max-w-sm">
|
||||||
<SheetContent
|
<SheetHeader className="border-b px-5 py-4 pr-12">
|
||||||
side="right"
|
<SheetTitle>{moreTitle}</SheetTitle>
|
||||||
className="inset-y-2 right-2 h-auto w-[calc(100%-1rem)] gap-0 overflow-hidden rounded-xl border bg-card sm:max-w-sm"
|
|
||||||
>
|
|
||||||
<div className="flex min-h-0 flex-1 flex-col bg-muted/50">
|
|
||||||
<SheetHeader className="gap-0 px-4 pt-3.5 pb-1 pr-10 text-left">
|
|
||||||
<SheetTitle className="flex items-center gap-2 text-sm">
|
|
||||||
<SlidersHorizontalIcon className="size-4 text-primary" />
|
|
||||||
{moreTitle}
|
|
||||||
</SheetTitle>
|
|
||||||
{/* Описание нужно Radix для доступности; видно только скринридерам. */}
|
{/* Описание нужно Radix для доступности; видно только скринридерам. */}
|
||||||
<SheetDescription className="sr-only">Фильтры применяются сразу</SheetDescription>
|
<SheetDescription className="sr-only">Фильтры применяются сразу</SheetDescription>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
<MoreFields>{more}</MoreFields>
|
<div className="flex flex-col gap-5 p-5">{more}</div>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
<SheetFooter className="mt-0 flex-row items-center justify-between gap-2 px-2 py-2">
|
<SheetFooter className="flex-row justify-between border-t px-5 py-3">
|
||||||
<ResetAll activeCount={activeCount} onReset={onReset} />
|
{onReset ? (
|
||||||
<SheetClose asChild>
|
<Button variant="ghost" size="sm" disabled={!activeCount} onClick={onReset} className="text-muted-foreground">
|
||||||
<Button>Готово</Button>
|
|
||||||
</SheetClose>
|
|
||||||
</SheetFooter>
|
|
||||||
</div>
|
|
||||||
</SheetContent>
|
|
||||||
</Sheet>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Заголовок панели — как у InfoSection: иконка и название на мягкой подложке, без разделителя. */
|
|
||||||
function MoreTitle({ title }: { title: string }) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-2 px-4 pt-3.5 pb-1 text-sm font-semibold">
|
|
||||||
<SlidersHorizontalIcon className="size-4 text-primary" />
|
|
||||||
{title}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Поля на белой карточке, как форма внутри InfoSection. */
|
|
||||||
function MoreFields({ children }: { children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<div className="px-2 pt-2">
|
|
||||||
<div className="flex flex-col gap-4 rounded-lg bg-card p-4 shadow-xs">{children}</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ResetAll({ activeCount, onReset }: { activeCount: number; onReset?: () => void }) {
|
|
||||||
if (!onReset) return <span />
|
|
||||||
return (
|
|
||||||
<Button variant="ghost" disabled={!activeCount} onClick={onReset} className="text-muted-foreground">
|
|
||||||
<RotateCwIcon /> Сбросить все
|
<RotateCwIcon /> Сбросить все
|
||||||
</Button>
|
</Button>
|
||||||
)
|
) : (
|
||||||
}
|
<span />
|
||||||
|
)}
|
||||||
function MorePanel({
|
<SheetClose asChild>
|
||||||
title,
|
<Button size="sm">Готово</Button>
|
||||||
activeCount,
|
</SheetClose>
|
||||||
onReset,
|
</SheetFooter>
|
||||||
done,
|
</SheetContent>
|
||||||
children,
|
</Sheet>
|
||||||
}: {
|
)}
|
||||||
title: string
|
{onReset && (
|
||||||
activeCount: number
|
<Button variant="ghost" size="sm" disabled={!activeCount} onClick={onReset} className="text-muted-foreground">
|
||||||
onReset?: () => void
|
<RotateCwIcon /> Сбросить
|
||||||
done: React.ReactNode
|
{activeCount > 0 && <Count value={activeCount} />}
|
||||||
children: React.ReactNode
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<MoreTitle title={title} />
|
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
|
||||||
<MoreFields>{children}</MoreFields>
|
|
||||||
</ScrollArea>
|
|
||||||
<div className="flex items-center justify-between gap-2 px-2 py-2">
|
|
||||||
<ResetAll activeCount={activeCount} onReset={onReset} />
|
|
||||||
{done}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function MoreButton({
|
|
||||||
moreCount,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: { moreCount: number } & React.ComponentProps<typeof Button>) {
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
{...props}
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
title={moreCount ? `Включено расширенных фильтров: ${moreCount}` : undefined}
|
|
||||||
className={cn("shrink-0 rounded-lg bg-card text-foreground shadow-xs hover:bg-card/80", className)}
|
|
||||||
>
|
|
||||||
<SlidersHorizontalIcon />
|
|
||||||
<Dotted on={moreCount > 0}>Ещё</Dotted>
|
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Переключатель для панели расширенных фильтров: подпись слева, тумблер справа, подсказка под подписью. */
|
||||||
* Переключатель для панели расширенных фильтров — как тумблер в форме:
|
|
||||||
* тумблер слева, подпись и подсказка справа; нажимается вся строка.
|
|
||||||
*/
|
|
||||||
export function FilterSwitch({
|
export function FilterSwitch({
|
||||||
id,
|
id,
|
||||||
label,
|
label,
|
||||||
|
|
@ -233,23 +111,22 @@ export function FilterSwitch({
|
||||||
onCheckedChange: (checked: boolean) => void
|
onCheckedChange: (checked: boolean) => void
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<label htmlFor={id} className="flex cursor-pointer items-center gap-3">
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label htmlFor={id} className="font-normal">
|
||||||
|
{label}
|
||||||
|
</Label>
|
||||||
|
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
|
||||||
|
</div>
|
||||||
<Switch id={id} checked={checked} onCheckedChange={onCheckedChange} />
|
<Switch id={id} checked={checked} onCheckedChange={onCheckedChange} />
|
||||||
<span className="min-w-0 space-y-0.5">
|
</div>
|
||||||
<span className="block text-sm leading-none font-medium">{label}</span>
|
|
||||||
{hint && <span className="block text-xs text-muted-foreground">{hint}</span>}
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Подпись кнопки с точкой над концом, когда что-то включено; точка вне потока — ширина кнопки не меняется. */
|
function Count({ value }: { value: number }) {
|
||||||
function Dotted({ on, children }: { on: boolean; children: React.ReactNode }) {
|
|
||||||
return (
|
return (
|
||||||
// mr-1 — запас под точку внутри кнопки, чтобы она не прилипала к рамке; есть всегда, ширина постоянная.
|
<span className="grid min-w-4.5 place-items-center rounded-full bg-primary px-1 text-2xs font-semibold text-primary-foreground tabular">
|
||||||
<span className="relative mr-1">
|
{value}
|
||||||
{children}
|
|
||||||
{on && <span aria-hidden className="absolute top-0.5 -right-2 size-1.5 rounded-full bg-primary" />}
|
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -66,9 +66,7 @@ export function FilterTabs<T extends string>({
|
||||||
<div
|
<div
|
||||||
role="group"
|
role="group"
|
||||||
className={cn(
|
className={cn(
|
||||||
// Не влезают в строку — переносятся внутри той же подложки, а не обрезаются.
|
"scrollbar-none flex w-fit max-w-full shrink-0 items-center gap-1 overflow-x-auto overflow-y-hidden rounded-xl bg-muted/70 p-1",
|
||||||
// p-0.5: одна строка получается 36px, как поле фильтра; кнопки внутри — h-8.
|
|
||||||
"flex w-fit max-w-full flex-wrap items-center gap-1 rounded-xl bg-muted/70 p-0.5",
|
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
import * as React from "react"
|
|
||||||
import { type LucideIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
import type { ChipTone } from "./chip"
|
|
||||||
|
|
||||||
/** Цвет пилюли — те же тона, что у `Chip`, без нейтрального. */
|
|
||||||
export type FilterToggleTone = Exclude<ChipTone, "neutral">
|
|
||||||
|
|
||||||
const offClass: Record<FilterToggleTone, string> = {
|
|
||||||
primary: "border-primary/30 text-primary hover:bg-primary/5",
|
|
||||||
positive: "border-success/30 text-success hover:bg-success-soft",
|
|
||||||
info: "border-info/30 text-info hover:bg-info-soft",
|
|
||||||
warning: "border-warning/40 text-warning hover:bg-warning-soft",
|
|
||||||
negative: "border-coral/30 text-coral hover:bg-coral-soft",
|
|
||||||
}
|
|
||||||
|
|
||||||
const onClass: Record<FilterToggleTone, string> = {
|
|
||||||
primary: "border-transparent bg-primary/10 text-primary",
|
|
||||||
positive: "border-transparent bg-success-soft text-success",
|
|
||||||
info: "border-transparent bg-info-soft text-info",
|
|
||||||
warning: "border-transparent bg-warning-soft text-warning",
|
|
||||||
negative: "border-transparent bg-coral-soft text-coral",
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Переключатель в строке фильтров: пилюля высотой поля (`h-9`).
|
|
||||||
* Выключена — контур и текст `tone`, включена — мягкая заливка того же цвета.
|
|
||||||
*/
|
|
||||||
export function FilterToggle({
|
|
||||||
tone = "negative",
|
|
||||||
pressed = false,
|
|
||||||
onPressedChange,
|
|
||||||
icon: Icon,
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
tone?: FilterToggleTone
|
|
||||||
pressed?: boolean
|
|
||||||
onPressedChange: (pressed: boolean) => void
|
|
||||||
icon?: LucideIcon
|
|
||||||
className?: string
|
|
||||||
children: React.ReactNode
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-pressed={pressed}
|
|
||||||
onClick={() => onPressedChange(!pressed)}
|
|
||||||
className={cn(
|
|
||||||
"inline-flex h-9 shrink-0 items-center gap-1.5 rounded-full border px-3 text-sm font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
|
||||||
pressed ? onClass[tone] : offClass[tone],
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{Icon && <Icon className="size-4" />}
|
|
||||||
{children}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
|
||||||
import { FormControlProvider, type FormControlState } from "../lib/form-control"
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { Label } from "../ui/label"
|
import { Label } from "../ui/label"
|
||||||
|
|
||||||
|
|
@ -14,12 +13,7 @@ export function FormSection({ title, children }: { title: string; children: Reac
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Подпись, поле, подсказка или ошибка под ним. */
|
||||||
* Подпись, поле, подсказка или ошибка под ним.
|
|
||||||
* Сам выдаёт id поля и id текста под ним: Input, DateInput, TimeInput, SnilsInput, PhoneInput
|
|
||||||
* и SearchInput подхватывают их и ставят aria-invalid / aria-describedby.
|
|
||||||
* htmlFor — когда контрол сам не читает контекст (список, своя кнопка): подпись укажет на его id.
|
|
||||||
*/
|
|
||||||
export function FormField({
|
export function FormField({
|
||||||
label,
|
label,
|
||||||
htmlFor,
|
htmlFor,
|
||||||
|
|
@ -35,26 +29,15 @@ export function FormField({
|
||||||
className?: string
|
className?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
const generatedId = React.useId()
|
|
||||||
const descriptionId = React.useId()
|
|
||||||
const id = htmlFor ?? generatedId
|
|
||||||
const message = error || hint
|
|
||||||
const control = React.useMemo<FormControlState>(
|
|
||||||
() => ({ id, descriptionId: message ? descriptionId : undefined, invalid: Boolean(error) }),
|
|
||||||
[id, descriptionId, message, error],
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FormControlProvider value={control}>
|
|
||||||
<div className={cn("space-y-1.5", className)}>
|
<div className={cn("space-y-1.5", className)}>
|
||||||
<Label htmlFor={id}>{label}</Label>
|
<Label htmlFor={htmlFor}>{label}</Label>
|
||||||
{children}
|
{children}
|
||||||
{error ? (
|
{error ? (
|
||||||
<p id={descriptionId} className="text-xs text-destructive">{error}</p>
|
<p className="text-xs text-destructive">{error}</p>
|
||||||
) : hint ? (
|
) : hint ? (
|
||||||
<p id={descriptionId} className="text-xs text-muted-foreground">{hint}</p>
|
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</FormControlProvider>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
// Действия в шапке раздела (PageFrame, SectionTabsBar): на телефоне (уже md) от кнопок остаются иконки,
|
|
||||||
// на планшете и шире — с подписью. Подпись кнопки — текстовый узел, поэтому прячем его нулевым шрифтом:
|
|
||||||
// имя для скринридера остаётся, а счётчик со своим размером шрифта — виден. Кнопки без иконки не трогаем.
|
|
||||||
// Классы целиком, без склейки: иначе Tailwind их не найдёт.
|
|
||||||
export const FRAME_ACTIONS_CLASS =
|
|
||||||
"max-md:[&_:is([data-slot=button],[data-slot=toggle-group-item],[data-slot=tooltip-trigger]):has(>svg)]:gap-0 max-md:[&_:is([data-slot=button],[data-slot=toggle-group-item],[data-slot=tooltip-trigger]):has(>svg)]:px-2 max-md:[&_:is([data-slot=button],[data-slot=toggle-group-item],[data-slot=tooltip-trigger]):has(>svg)]:text-[0px]"
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
// Составные компоненты Medkit. Витрина — /ui, /ui-form и /ui-table в medicine-ui.
|
// Составные компоненты Medkit. Витрина — /ui в medicine-ui (src/pages/ui/ui-page.tsx).
|
||||||
export * from "./app-shell"
|
export * from "./app-shell"
|
||||||
export * from "./app-sidebar"
|
export * from "./app-sidebar"
|
||||||
export * from "./sidebar-cards"
|
|
||||||
export * from "./autocomplete"
|
export * from "./autocomplete"
|
||||||
export * from "./chip"
|
export * from "./chip"
|
||||||
export * from "./code-block"
|
export * from "./code-block"
|
||||||
|
|
@ -17,10 +16,8 @@ export * from "./edit-dialog"
|
||||||
export * from "./empty-state"
|
export * from "./empty-state"
|
||||||
export * from "./file-drop"
|
export * from "./file-drop"
|
||||||
export * from "./file-gallery"
|
export * from "./file-gallery"
|
||||||
export * from "./file-type-icon"
|
|
||||||
export * from "./filter-bar"
|
export * from "./filter-bar"
|
||||||
export * from "./filter-tabs"
|
export * from "./filter-tabs"
|
||||||
export * from "./filter-toggle"
|
|
||||||
export * from "./form-field"
|
export * from "./form-field"
|
||||||
export * from "./info-section"
|
export * from "./info-section"
|
||||||
export * from "./loading-bar"
|
export * from "./loading-bar"
|
||||||
|
|
@ -32,12 +29,10 @@ export * from "./notify"
|
||||||
export * from "./page-frame"
|
export * from "./page-frame"
|
||||||
export * from "./page-tabs"
|
export * from "./page-tabs"
|
||||||
export * from "./pagination"
|
export * from "./pagination"
|
||||||
export * from "./presence"
|
|
||||||
export * from "./patient-avatar"
|
export * from "./patient-avatar"
|
||||||
export * from "./patient-panel"
|
export * from "./patient-panel"
|
||||||
export * from "./patient-picker"
|
export * from "./patient-picker"
|
||||||
export * from "./person-chip"
|
export * from "./person-chip"
|
||||||
export * from "./phone-input"
|
|
||||||
export * from "./save-bar"
|
export * from "./save-bar"
|
||||||
export * from "./schedule-grid"
|
export * from "./schedule-grid"
|
||||||
export * from "./search-field"
|
export * from "./search-field"
|
||||||
|
|
@ -53,4 +48,3 @@ export * from "./status-badge"
|
||||||
export * from "./stepper"
|
export * from "./stepper"
|
||||||
export * from "./time-input"
|
export * from "./time-input"
|
||||||
export * from "./time-range-input"
|
export * from "./time-range-input"
|
||||||
export * from "./upload-progress"
|
|
||||||
|
|
|
||||||
|
|
@ -135,7 +135,6 @@ export function LoginForm({
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
const errorId = React.useId()
|
|
||||||
const spinner = <Loader2Icon className="animate-spin" />
|
const spinner = <Loader2Icon className="animate-spin" />
|
||||||
|
|
||||||
if (challenge) {
|
if (challenge) {
|
||||||
|
|
@ -185,11 +184,7 @@ export function LoginForm({
|
||||||
</InputOTPGroup>
|
</InputOTPGroup>
|
||||||
</InputOTP>
|
</InputOTP>
|
||||||
|
|
||||||
{error && (
|
{error && <p className="text-center text-sm text-destructive">{error}</p>}
|
||||||
<p id={errorId} role="alert" className="text-center text-sm text-destructive">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
|
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
|
||||||
{pending === "otp" && spinner} Подтвердить
|
{pending === "otp" && spinner} Подтвердить
|
||||||
|
|
@ -227,8 +222,9 @@ export function LoginForm({
|
||||||
void submitLogin()
|
void submitLogin()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FormField label="Логин">
|
<FormField label="Логин" htmlFor="login-form-login">
|
||||||
<Input
|
<Input
|
||||||
|
id="login-form-login"
|
||||||
autoComplete="username"
|
autoComplete="username"
|
||||||
autoFocus={autoFocus && !defaultLogin}
|
autoFocus={autoFocus && !defaultLogin}
|
||||||
value={login}
|
value={login}
|
||||||
|
|
@ -236,15 +232,18 @@ export function LoginForm({
|
||||||
setLogin(e.target.value)
|
setLogin(e.target.value)
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
}}
|
}}
|
||||||
aria-invalid={Boolean(error)}
|
|
||||||
aria-describedby={error ? errorId : undefined}
|
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
/>
|
/>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="Пароль" hint={capsLock ? "Включён Caps Lock" : undefined}>
|
<FormField
|
||||||
|
label="Пароль"
|
||||||
|
htmlFor="login-form-password"
|
||||||
|
hint={capsLock ? "Включён Caps Lock" : undefined}
|
||||||
|
>
|
||||||
<InputGroup data-disabled={busy || undefined}>
|
<InputGroup data-disabled={busy || undefined}>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
|
id="login-form-password"
|
||||||
type={showPassword ? "text" : "password"}
|
type={showPassword ? "text" : "password"}
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
autoFocus={autoFocus && Boolean(defaultLogin)}
|
autoFocus={autoFocus && Boolean(defaultLogin)}
|
||||||
|
|
@ -257,7 +256,6 @@ export function LoginForm({
|
||||||
onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))}
|
onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))}
|
||||||
onBlur={() => setCapsLock(false)}
|
onBlur={() => setCapsLock(false)}
|
||||||
aria-invalid={Boolean(error)}
|
aria-invalid={Boolean(error)}
|
||||||
aria-describedby={error ? errorId : undefined}
|
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
/>
|
/>
|
||||||
<InputGroupAddon align="inline-end">
|
<InputGroupAddon align="inline-end">
|
||||||
|
|
@ -273,11 +271,7 @@ export function LoginForm({
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{error && (
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
<p id={errorId} role="alert" className="text-sm text-destructive">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
|
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
|
||||||
{pending === "login" && spinner} Войти
|
{pending === "login" && spinner} Войти
|
||||||
|
|
|
||||||
|
|
@ -3,67 +3,43 @@ import { type LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { ScrollArea } from "../ui/scroll-area"
|
import { ScrollArea } from "../ui/scroll-area"
|
||||||
import { FRAME_ACTIONS_CLASS } from "./frame-actions"
|
|
||||||
import { FrameMaximizeButton, SectionFrame } from "./section-frame"
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Рамка раздела без вкладок: карточка с шапкой (иконка, заголовок, действия)
|
* Рамка раздела без вкладок: карточка с шапкой (иконка, заголовок, действия)
|
||||||
* и прокручиваемым телом. Разделы со вкладками используют SectionFrame.
|
* и прокручиваемым телом. Разделы со вкладками используют SectionFrame.
|
||||||
* Крайняя справа в шапке — «Развернуть на весь экран» (Alt+F), как у разделов со вкладками.
|
|
||||||
* На телефоне заголовок сворачивается до иконки, кнопки действий — до иконок.
|
|
||||||
*/
|
*/
|
||||||
export function PageFrame({
|
export function PageFrame({
|
||||||
icon: Icon,
|
icon: Icon,
|
||||||
title,
|
title,
|
||||||
titleVariant = "chip",
|
|
||||||
actions,
|
actions,
|
||||||
toolbar,
|
toolbar,
|
||||||
scroll = true,
|
scroll = true,
|
||||||
showTitleOnMobile = false,
|
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
icon?: LucideIcon
|
icon?: LucideIcon
|
||||||
title: React.ReactNode
|
title: React.ReactNode
|
||||||
/** chip — как активная вкладка раздела из меню; plain — обычный заголовок, без подложки. */
|
|
||||||
titleVariant?: "chip" | "plain"
|
|
||||||
actions?: React.ReactNode
|
actions?: React.ReactNode
|
||||||
/** Строка под шапкой: фильтры, поиск. */
|
/** Строка под шапкой: фильтры, поиск. */
|
||||||
toolbar?: React.ReactNode
|
toolbar?: React.ReactNode
|
||||||
/** false — тело само управляет прокруткой (списки с панелью деталей). */
|
/** false — тело само управляет прокруткой (списки с панелью деталей). */
|
||||||
scroll?: boolean
|
scroll?: boolean
|
||||||
/** Не скрывать текст заголовка рядом с иконкой на узком экране. */
|
|
||||||
showTitleOnMobile?: boolean
|
|
||||||
className?: string
|
className?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SectionFrame
|
<div className="flex min-h-0 flex-1 flex-col p-2 lg:p-3">
|
||||||
bar={
|
<div className="flex min-h-0 flex-1 flex-col overflow-clip rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]">
|
||||||
<>
|
|
||||||
{/* Шапка и заголовок — как у SectionTabsBar с активной корневой вкладкой (PageTabs, CHIP_CLASS):
|
{/* Шапка и заголовок — как у SectionTabsBar с активной корневой вкладкой (PageTabs, CHIP_CLASS):
|
||||||
разделы со вкладками и без выглядят одинаково. */}
|
разделы со вкладками и без выглядят одинаково. */}
|
||||||
<header className="flex h-12 shrink-0 items-center gap-2 border-b px-2">
|
<header className="flex h-12 shrink-0 items-center gap-2 border-b px-2">
|
||||||
<h1
|
<h1 className="flex h-8 min-w-0 items-center gap-2 rounded-lg bg-accent px-2.5 text-sm font-medium text-accent-foreground">
|
||||||
className={cn(
|
|
||||||
"flex h-8 min-w-0 items-center gap-2 px-2.5 text-sm",
|
|
||||||
titleVariant === "chip"
|
|
||||||
? "rounded-lg bg-accent font-medium text-accent-foreground"
|
|
||||||
: "font-semibold text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{Icon && <Icon className="size-4 shrink-0 text-primary" />}
|
{Icon && <Icon className="size-4 shrink-0 text-primary" />}
|
||||||
<span className={cn("truncate", Icon && !showTitleOnMobile && "max-md:sr-only")}>{title}</span>
|
<span className="truncate">{title}</span>
|
||||||
</h1>
|
</h1>
|
||||||
<div className={cn("ml-auto flex shrink-0 items-center gap-2", FRAME_ACTIONS_CLASS)}>
|
{actions && <div className="ml-auto flex shrink-0 items-center gap-2">{actions}</div>}
|
||||||
{actions}
|
|
||||||
<FrameMaximizeButton />
|
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
{toolbar && <div className="shrink-0 border-b px-4 py-3">{toolbar}</div>}
|
{toolbar && <div className="shrink-0 border-b px-4 py-3">{toolbar}</div>}
|
||||||
</>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{scroll ? (
|
{scroll ? (
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
<div className={className}>{children}</div>
|
<div className={className}>{children}</div>
|
||||||
|
|
@ -71,6 +47,7 @@ export function PageFrame({
|
||||||
) : (
|
) : (
|
||||||
<div className={cn("flex min-h-0 flex-1", className)}>{children}</div>
|
<div className={cn("flex min-h-0 flex-1", className)}>{children}</div>
|
||||||
)}
|
)}
|
||||||
</SectionFrame>
|
</div>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,6 @@ import {
|
||||||
} from "../ui/dropdown-menu"
|
} from "../ui/dropdown-menu"
|
||||||
import { Kbd } from "../ui/kbd"
|
import { Kbd } from "../ui/kbd"
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||||
import { FRAME_ACTIONS_CLASS } from "./frame-actions"
|
|
||||||
|
|
||||||
export type PageTabTone = "male" | "female" | "neutral"
|
export type PageTabTone = "male" | "female" | "neutral"
|
||||||
|
|
||||||
|
|
@ -241,7 +240,7 @@ export function PageTabs({
|
||||||
})}
|
})}
|
||||||
{hidden.length > 0 && <OverflowTabs tabs={hidden} onSelect={onSelect} onClose={onClose} />}
|
{hidden.length > 0 && <OverflowTabs tabs={hidden} onSelect={onSelect} onClose={onClose} />}
|
||||||
</div>
|
</div>
|
||||||
{actions && <div className={cn("flex shrink-0 items-center gap-1", FRAME_ACTIONS_CLASS)}>{actions}</div>}
|
{actions && <div className="flex shrink-0 items-center gap-1">{actions}</div>}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -261,8 +260,6 @@ function TabFace({
|
||||||
onClose?: () => void
|
onClose?: () => void
|
||||||
hotkey?: string
|
hotkey?: string
|
||||||
}) {
|
}) {
|
||||||
// Вкладка-раздел (с иконкой, как пункт меню) на телефоне — одна иконка; подпись остаётся для скринридера.
|
|
||||||
const labelClass = cn("truncate", tab.icon && "max-md:sr-only")
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{tab.icon ? (
|
{tab.icon ? (
|
||||||
|
|
@ -282,7 +279,7 @@ function TabFace({
|
||||||
{onClose ? (
|
{onClose ? (
|
||||||
<Tooltip delayDuration={600}>
|
<Tooltip delayDuration={600}>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<span className={labelClass}>{tab.label}</span>
|
<span className="truncate">{tab.label}</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="bottom">
|
<TooltipContent side="bottom">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|
@ -298,7 +295,7 @@ function TabFace({
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
) : (
|
) : (
|
||||||
<span className={labelClass}>{tab.label}</span>
|
<span className="truncate">{tab.label}</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{closable &&
|
{closable &&
|
||||||
|
|
|
||||||
|
|
@ -4,16 +4,12 @@ import { cn } from "../lib/utils"
|
||||||
|
|
||||||
const DEFAULT_SIZES = [15, 30, 50] as const
|
const DEFAULT_SIZES = [15, 30, 50] as const
|
||||||
|
|
||||||
/**
|
/** Номера страниц с многоточиями: 1 … 4 5 6 … 12 */
|
||||||
* Номера страниц с многоточиями: 1 … 4 5 6 … 12. Мест всегда 7 — при переключении стрелки не сдвигаются:
|
|
||||||
* у начала 1 2 3 4 5 … 12, у конца 1 … 8 9 10 11 12.
|
|
||||||
*/
|
|
||||||
function pageList(current: number, pages: number): (number | "gap")[] {
|
function pageList(current: number, pages: number): (number | "gap")[] {
|
||||||
if (pages <= 7) return Array.from({ length: pages }, (_, i) => i)
|
if (pages <= 7) return Array.from({ length: pages }, (_, i) => i)
|
||||||
const last = pages - 1
|
const set = new Set([0, pages - 1, current - 1, current, current + 1])
|
||||||
if (current < 4) return [0, 1, 2, 3, 4, "gap", last]
|
const sorted = [...set].filter((p) => p >= 0 && p < pages).sort((a, b) => a - b)
|
||||||
if (current > last - 4) return [0, "gap", last - 4, last - 3, last - 2, last - 1, last]
|
return sorted.flatMap((p, i) => (i > 0 && p - sorted[i - 1] > 1 ? ["gap" as const, p] : [p]))
|
||||||
return [0, "gap", current - 1, current, current + 1, "gap", last]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -42,18 +38,11 @@ export function Pagination({
|
||||||
const from = total ? current * size + 1 : 0
|
const from = total ? current * size + 1 : 0
|
||||||
const to = Math.min((current + 1) * size, total)
|
const to = Math.min((current + 1) * size, total)
|
||||||
|
|
||||||
const pageButton = "grid h-8 min-w-8 place-items-center rounded-md px-2 text-ui font-medium tabular transition"
|
const pageButton = "grid h-7 min-w-7 place-items-center rounded-md px-1.5 text-xs font-medium tabular transition"
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// Три колонки: страницы строго по центру, сколько бы места ни занимали «1 – 15 из 28» и размеры.
|
<div className={cn("flex flex-wrap items-center justify-between gap-3 px-4 py-2.5", className)}>
|
||||||
// На телефоне не влезает в строку — переносится, как раньше.
|
<span className="rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground tabular">
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-wrap items-center justify-between gap-3 px-4 py-2.5 sm:grid sm:grid-cols-[1fr_auto_1fr]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="justify-self-start rounded-md bg-muted px-2 py-1 text-ui text-muted-foreground tabular">
|
|
||||||
{from} – {to} из {total}
|
{from} – {to} из {total}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
|
|
@ -69,7 +58,7 @@ export function Pagination({
|
||||||
</button>
|
</button>
|
||||||
{pageList(current, pages).map((p, i) =>
|
{pageList(current, pages).map((p, i) =>
|
||||||
p === "gap" ? (
|
p === "gap" ? (
|
||||||
<span key={`gap-${i}`} className="grid h-8 min-w-8 place-items-center text-ui text-muted-foreground">
|
<span key={`gap-${i}`} className="px-1 text-xs text-muted-foreground">
|
||||||
…
|
…
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -99,7 +88,7 @@ export function Pagination({
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{onSizeChange ? (
|
{onSizeChange ? (
|
||||||
<div className="flex items-center gap-0.5 justify-self-end rounded-lg bg-muted p-0.5">
|
<div className="flex items-center gap-0.5 rounded-lg bg-muted p-0.5">
|
||||||
{sizeOptions.map((s) => (
|
{sizeOptions.map((s) => (
|
||||||
<button
|
<button
|
||||||
key={s}
|
key={s}
|
||||||
|
|
@ -109,7 +98,7 @@ export function Pagination({
|
||||||
onPageChange(0)
|
onPageChange(0)
|
||||||
}}
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-7 rounded-md px-2.5 text-ui font-medium tabular transition",
|
"h-6 rounded-md px-2 text-xs font-medium tabular transition",
|
||||||
s === size ? "bg-card text-foreground shadow-xs" : "text-muted-foreground hover:text-foreground",
|
s === size ? "bg-card text-foreground shadow-xs" : "text-muted-foreground hover:text-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ export function PatientPanel<T extends string>({
|
||||||
const fullName = [p.lastName, p.firstName, p.middleName].filter(Boolean).join(" ")
|
const fullName = [p.lastName, p.firstName, p.middleName].filter(Boolean).join(" ")
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("@container/patient-panel shrink-0", className)}>
|
<div className={cn("shrink-0", className)}>
|
||||||
<header className="relative overflow-hidden border-b">
|
<header className="relative overflow-hidden border-b">
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
|
|
@ -115,11 +115,7 @@ export function PatientPanel<T extends string>({
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{actions && (
|
{actions && <div className="flex min-w-0 flex-wrap items-center gap-2 max-sm:w-full">{actions}</div>}
|
||||||
<div className="flex min-w-0 flex-wrap items-center gap-2 @max-[760px]/patient-panel:w-full @max-[760px]/patient-panel:justify-start">
|
|
||||||
{actions}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
import * as React from "react"
|
|
||||||
|
|
||||||
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"
|
|
||||||
import { maskPhone, maskWithCaret } from "../lib/masks"
|
|
||||||
import { useCaret } from "../hooks/use-caret"
|
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
|
|
||||||
/** Мобильный телефон: префикс +7 и маска «(000) 000-00-00». Правка в середине не сдвигает курсор в конец. */
|
|
||||||
export function PhoneInput({
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
invalid,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: Omit<React.ComponentProps<"input">, "value" | "onChange"> & {
|
|
||||||
value: string
|
|
||||||
onChange: (value: string) => void
|
|
||||||
invalid?: boolean
|
|
||||||
}) {
|
|
||||||
const setCaret = useCaret()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<InputGroup className={cn("w-full", className)}>
|
|
||||||
<InputGroupAddon className="tabular">+7</InputGroupAddon>
|
|
||||||
<InputGroupInput
|
|
||||||
type="tel"
|
|
||||||
inputMode="tel"
|
|
||||||
autoComplete="tel"
|
|
||||||
placeholder="(000) 000-00-00"
|
|
||||||
{...props}
|
|
||||||
value={value}
|
|
||||||
aria-invalid={invalid}
|
|
||||||
onChange={(e) => {
|
|
||||||
const next = maskWithCaret(e.target, (e.nativeEvent as InputEvent).inputType, value, maskPhone)
|
|
||||||
onChange(next.value)
|
|
||||||
setCaret(e.target, next.caret)
|
|
||||||
}}
|
|
||||||
className="tabular"
|
|
||||||
/>
|
|
||||||
</InputGroup>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
import { StatusDot, type StatusTone } from "./status-badge"
|
|
||||||
|
|
||||||
/** Присутствие пользователя: видно коллегам и в меню профиля. */
|
|
||||||
export type UserPresence = "online" | "away" | "busy" | "offline"
|
|
||||||
|
|
||||||
export const PRESENCE: Record<UserPresence, { readonly label: string; readonly tone: StatusTone }> = {
|
|
||||||
online: { label: "На месте", tone: "positive" },
|
|
||||||
away: { label: "Отошёл", tone: "warning" },
|
|
||||||
busy: { label: "Не беспокоить", tone: "negative" },
|
|
||||||
offline: { label: "Не в сети", tone: "neutral" },
|
|
||||||
}
|
|
||||||
|
|
||||||
export const PRESENCE_ORDER: readonly UserPresence[] = ["online", "away", "busy", "offline"]
|
|
||||||
|
|
||||||
/** Точка присутствия: в меню и списках — сама по себе, на аватаре — с `ring` в цвет подложки. */
|
|
||||||
export function PresenceDot({ presence, className }: { presence: UserPresence; className?: string }) {
|
|
||||||
return <StatusDot tone={PRESENCE[presence].tone} className={cn("size-2", className)} />
|
|
||||||
}
|
|
||||||
|
|
@ -3,8 +3,6 @@ import { PlusIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { ScrollArea } from "../ui/scroll-area"
|
import { ScrollArea } from "../ui/scroll-area"
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
|
||||||
import { layoutLanes, minutes } from "./schedule-lanes"
|
|
||||||
import type { StatusTone } from "./status-badge"
|
import type { StatusTone } from "./status-badge"
|
||||||
|
|
||||||
/** Время «ЧЧ:ММ». */
|
/** Время «ЧЧ:ММ». */
|
||||||
|
|
@ -42,6 +40,36 @@ const toneClass: Record<StatusTone, string> = {
|
||||||
neutral: "border-l-muted-foreground/50 bg-muted",
|
neutral: "border-l-muted-foreground/50 bg-muted",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const minutes = (t: Clock) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
|
||||||
|
|
||||||
|
/** Раскладка пересекающихся записей одного врача по дорожкам: `lane` из `lanes`. */
|
||||||
|
function layoutLanes(events: readonly ScheduleGridEvent[]) {
|
||||||
|
const sorted = events.toSorted((a, b) => minutes(a.start) - minutes(b.start) || minutes(b.end) - minutes(a.end))
|
||||||
|
const result = new Map<React.Key, { lane: number; lanes: number }>()
|
||||||
|
let cluster: ScheduleGridEvent[] = []
|
||||||
|
let laneEnds: number[] = []
|
||||||
|
let clusterEnd = -1
|
||||||
|
|
||||||
|
const flush = () => {
|
||||||
|
for (const e of cluster) result.set(e.id, { lane: result.get(e.id)!.lane, lanes: laneEnds.length })
|
||||||
|
cluster = []
|
||||||
|
laneEnds = []
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const e of sorted) {
|
||||||
|
const start = minutes(e.start)
|
||||||
|
if (start >= clusterEnd) flush()
|
||||||
|
let lane = laneEnds.findIndex((end) => end <= start)
|
||||||
|
if (lane < 0) lane = laneEnds.push(0) - 1
|
||||||
|
laneEnds[lane] = minutes(e.end)
|
||||||
|
clusterEnd = Math.max(clusterEnd, minutes(e.end))
|
||||||
|
cluster.push(e)
|
||||||
|
result.set(e.id, { lane, lanes: 0 })
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
/** Границы сетки: от первого рабочего часа/записи до последнего, с округлением до часа. */
|
/** Границы сетки: от первого рабочего часа/записи до последнего, с округлением до часа. */
|
||||||
function gridBounds(resources: readonly ScheduleGridResource[], events: readonly ScheduleGridEvent[]) {
|
function gridBounds(resources: readonly ScheduleGridResource[], events: readonly ScheduleGridEvent[]) {
|
||||||
const starts = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.from)) ?? []), ...events.map((e) => minutes(e.start))]
|
const starts = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.from)) ?? []), ...events.map((e) => minutes(e.start))]
|
||||||
|
|
@ -56,9 +84,6 @@ const clock = (m: number) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${S
|
||||||
* Сетка дня: колонки — врачи (кабинеты, аппараты), строки — время.
|
* Сетка дня: колонки — врачи (кабинеты, аппараты), строки — время.
|
||||||
* Записи — плашки цвета статуса, свободные слоты кликабельны, линия «сейчас».
|
* Записи — плашки цвета статуса, свободные слоты кликабельны, линия «сейчас».
|
||||||
* Шапка и шкала времени липкие; при открытии сетка прокручивается к первой записи или к текущему времени.
|
* Шапка и шкала времени липкие; при открытии сетка прокручивается к первой записи или к текущему времени.
|
||||||
* Короткий день шкала дотягивает до низа окна — дальше штриховка нерабочего времени, без пустоты под сеткой.
|
|
||||||
* Мышью сетку можно таскать: зажать и вести в сторону.
|
|
||||||
* `compact` — на плашках только время, колонки уже; ФИО — в подсказке и для скринридера.
|
|
||||||
*/
|
*/
|
||||||
export function ScheduleGrid({
|
export function ScheduleGrid({
|
||||||
resources,
|
resources,
|
||||||
|
|
@ -66,7 +91,6 @@ export function ScheduleGrid({
|
||||||
from,
|
from,
|
||||||
to,
|
to,
|
||||||
minuteHeight = 1.8,
|
minuteHeight = 1.8,
|
||||||
compact = false,
|
|
||||||
now,
|
now,
|
||||||
selectedId,
|
selectedId,
|
||||||
onEventClick,
|
onEventClick,
|
||||||
|
|
@ -77,13 +101,11 @@ export function ScheduleGrid({
|
||||||
}: {
|
}: {
|
||||||
resources: readonly ScheduleGridResource[]
|
resources: readonly ScheduleGridResource[]
|
||||||
events: readonly ScheduleGridEvent[]
|
events: readonly ScheduleGridEvent[]
|
||||||
/** Начало и конец шкалы; по умолчанию — по рабочим часам и записям. Если окно выше, шкала продолжается до низа. */
|
/** Начало и конец шкалы; по умолчанию — по рабочим часам и записям. */
|
||||||
from?: Clock
|
from?: Clock
|
||||||
to?: Clock
|
to?: Clock
|
||||||
/** Высота минуты в пикселях. */
|
/** Высота минуты в пикселях. */
|
||||||
minuteHeight?: number
|
minuteHeight?: number
|
||||||
/** Компактный вид: на плашке только время, колонки уже. ФИО и статус — в подсказке при наведении. */
|
|
||||||
compact?: boolean
|
|
||||||
/** Текущее время — красная линия; только для сегодняшнего дня. */
|
/** Текущее время — красная линия; только для сегодняшнего дня. */
|
||||||
now?: Clock
|
now?: Clock
|
||||||
selectedId?: React.Key | null
|
selectedId?: React.Key | null
|
||||||
|
|
@ -95,25 +117,9 @@ export function ScheduleGrid({
|
||||||
empty?: React.ReactNode
|
empty?: React.ReactNode
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const grid = React.useRef<HTMLDivElement>(null)
|
|
||||||
const viewportOf = () => grid.current?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')
|
|
||||||
// Сколько минут шкалы помещается в окне под шапкой: короткий день дотягиваем до низа, без пустоты под сеткой.
|
|
||||||
const [fitMinutes, setFitMinutes] = React.useState(0)
|
|
||||||
const hasResources = resources.length > 0
|
|
||||||
React.useLayoutEffect(() => {
|
|
||||||
const viewport = viewportOf()
|
|
||||||
const head = grid.current?.firstElementChild as HTMLElement | null
|
|
||||||
if (!viewport || !head) return
|
|
||||||
const measure = () => setFitMinutes(Math.floor((viewport.clientHeight - head.offsetHeight) / minuteHeight))
|
|
||||||
const observer = new ResizeObserver(measure)
|
|
||||||
observer.observe(viewport)
|
|
||||||
measure()
|
|
||||||
return () => observer.disconnect()
|
|
||||||
}, [minuteHeight, hasResources])
|
|
||||||
|
|
||||||
const auto = gridBounds(resources, events)
|
const auto = gridBounds(resources, events)
|
||||||
const start = from ? minutes(from) : auto.from
|
const start = from ? minutes(from) : auto.from
|
||||||
const end = Math.min(24 * 60, Math.max(to ? minutes(to) : auto.to, start + fitMinutes))
|
const end = to ? minutes(to) : auto.to
|
||||||
const height = (end - start) * minuteHeight
|
const height = (end - start) * minuteHeight
|
||||||
const y = (t: Clock) => (minutes(t) - start) * minuteHeight
|
const y = (t: Clock) => (minutes(t) - start) * minuteHeight
|
||||||
// Дорожки считаются по каждой колонке отдельно.
|
// Дорожки считаются по каждой колонке отдельно.
|
||||||
|
|
@ -124,54 +130,17 @@ export function ScheduleGrid({
|
||||||
const hours = Array.from({ length: Math.floor((end - start) / 60) + 1 }, (_, i) => start + i * 60)
|
const hours = Array.from({ length: Math.floor((end - start) / 60) + 1 }, (_, i) => start + i * 60)
|
||||||
const nowY = now && minutes(now) >= start && minutes(now) <= end ? y(now) : null
|
const nowY = now && minutes(now) >= start && minutes(now) <= end ? y(now) : null
|
||||||
|
|
||||||
|
const grid = React.useRef<HTMLDivElement>(null)
|
||||||
const firstEvent = events.length ? Math.min(...events.map((e) => minutes(e.start))) : null
|
const firstEvent = events.length ? Math.min(...events.map((e) => minutes(e.start))) : null
|
||||||
const focus = nowY != null ? minutes(now!) - 45 : firstEvent != null ? firstEvent - 30 : start
|
const focus = nowY != null ? minutes(now!) - 45 : firstEvent != null ? firstEvent - 30 : start
|
||||||
const focusTop = Math.max(0, (focus - start) * minuteHeight)
|
const focusTop = Math.max(0, (focus - start) * minuteHeight)
|
||||||
// Крутим только свой вьюпорт: scrollIntoView сдвинул бы и каркас окна.
|
// Крутим только свой вьюпорт: scrollIntoView сдвинул бы и каркас окна.
|
||||||
React.useLayoutEffect(() => {
|
React.useLayoutEffect(() => {
|
||||||
const viewport = viewportOf()
|
const viewport = grid.current?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')
|
||||||
if (viewport) viewport.scrollTop = focusTop
|
if (viewport) viewport.scrollTop = focusTop
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- только при смене дня
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- только при смене дня
|
||||||
}, [scrollKey])
|
}, [scrollKey])
|
||||||
|
|
||||||
// Перетаскивание мышью: зажал и тянешь — сетка едет за курсором.
|
|
||||||
// Пока сдвиг меньше порога, это обычный клик по записи или слоту; после перетаскивания клик гасим.
|
|
||||||
const drag = React.useRef<{ x: number; y: number; left: number; top: number; moved: boolean } | null>(null)
|
|
||||||
const dragged = React.useRef(false)
|
|
||||||
const [dragging, setDragging] = React.useState(false)
|
|
||||||
|
|
||||||
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
|
||||||
const viewport = viewportOf()
|
|
||||||
if (e.pointerType !== "mouse" || e.button !== 0 || !viewport) return
|
|
||||||
if ((e.target as Element).closest('[data-slot="scroll-area-scrollbar"]')) return
|
|
||||||
drag.current = { x: e.clientX, y: e.clientY, left: viewport.scrollLeft, top: viewport.scrollTop, moved: false }
|
|
||||||
}
|
|
||||||
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
|
||||||
const d = drag.current
|
|
||||||
const viewport = viewportOf()
|
|
||||||
if (!d || !viewport) return
|
|
||||||
const dx = e.clientX - d.x
|
|
||||||
const dy = e.clientY - d.y
|
|
||||||
if (!d.moved) {
|
|
||||||
if (Math.hypot(dx, dy) < 5) return
|
|
||||||
d.moved = true
|
|
||||||
setDragging(true)
|
|
||||||
e.currentTarget.setPointerCapture(e.pointerId)
|
|
||||||
window.getSelection()?.removeAllRanges()
|
|
||||||
}
|
|
||||||
viewport.scrollLeft = d.left - dx
|
|
||||||
viewport.scrollTop = d.top - dy
|
|
||||||
}
|
|
||||||
const onPointerUp = () => {
|
|
||||||
if (drag.current?.moved) {
|
|
||||||
dragged.current = true
|
|
||||||
// click приходит сразу после pointerup — к следующему кадру флаг уже не нужен
|
|
||||||
requestAnimationFrame(() => (dragged.current = false))
|
|
||||||
}
|
|
||||||
drag.current = null
|
|
||||||
setDragging(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!resources.length) return <>{empty}</>
|
if (!resources.length) return <>{empty}</>
|
||||||
|
|
||||||
// Линии сетки: час — сплошная, полчаса — бледная.
|
// Линии сетки: час — сплошная, полчаса — бледная.
|
||||||
|
|
@ -181,28 +150,11 @@ export function ScheduleGrid({
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// Таскать можно и за пустое место под сеткой — обработчики на всей области, кроме полос прокрутки.
|
<ScrollArea horizontal className={cn("min-h-0 flex-1", className)}>
|
||||||
<ScrollArea
|
|
||||||
horizontal
|
|
||||||
onPointerDown={onPointerDown}
|
|
||||||
onPointerMove={onPointerMove}
|
|
||||||
onPointerUp={onPointerUp}
|
|
||||||
onPointerCancel={onPointerUp}
|
|
||||||
onClickCapture={(e) => {
|
|
||||||
if (!dragged.current) return
|
|
||||||
e.preventDefault()
|
|
||||||
e.stopPropagation()
|
|
||||||
}}
|
|
||||||
className={cn(
|
|
||||||
"min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]]:cursor-grab",
|
|
||||||
dragging && "select-none [&_*]:cursor-grabbing!",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
ref={grid}
|
ref={grid}
|
||||||
className="grid min-w-full"
|
className="grid min-w-full"
|
||||||
style={{ gridTemplateColumns: `3.5rem repeat(${resources.length}, minmax(${compact ? "8rem" : "11rem"}, 1fr))` }}
|
style={{ gridTemplateColumns: `3.5rem repeat(${resources.length}, minmax(11rem, 1fr))` }}
|
||||||
>
|
>
|
||||||
<div className="sticky top-0 left-0 z-30 border-r border-b bg-card" />
|
<div className="sticky top-0 left-0 z-30 border-r border-b bg-card" />
|
||||||
{resources.map((r) => (
|
{resources.map((r) => (
|
||||||
|
|
@ -261,7 +213,7 @@ export function ScheduleGrid({
|
||||||
type="button"
|
type="button"
|
||||||
disabled={!onSlotClick}
|
disabled={!onSlotClick}
|
||||||
onClick={() => onSlotClick?.(r, s)}
|
onClick={() => onSlotClick?.(r, s)}
|
||||||
className="group/slot absolute inset-x-1 flex cursor-pointer items-center gap-1 rounded-md border border-dashed border-transparent px-1.5 text-2xs font-medium text-primary transition-colors hover:border-primary/40 hover:bg-accent/70 focus-visible:border-primary focus-visible:outline-none disabled:pointer-events-none"
|
className="group/slot absolute inset-x-1 flex items-center gap-1 rounded-md border border-dashed border-transparent px-1.5 text-2xs font-medium text-primary transition-colors hover:border-primary/40 hover:bg-accent/70 focus-visible:border-primary focus-visible:outline-none disabled:pointer-events-none"
|
||||||
style={{ top: y(s.start) + 1, height: (minutes(s.end) - minutes(s.start)) * minuteHeight - 2 }}
|
style={{ top: y(s.start) + 1, height: (minutes(s.end) - minutes(s.start)) * minuteHeight - 2 }}
|
||||||
aria-label={`Записать на ${s.start}`}
|
aria-label={`Записать на ${s.start}`}
|
||||||
>
|
>
|
||||||
|
|
@ -277,13 +229,13 @@ export function ScheduleGrid({
|
||||||
.map((e) => {
|
.map((e) => {
|
||||||
const place = lanes.get(e.id) ?? { lane: 0, lanes: 1 }
|
const place = lanes.get(e.id) ?? { lane: 0, lanes: 1 }
|
||||||
const h = (minutes(e.end) - minutes(e.start)) * minuteHeight
|
const h = (minutes(e.end) - minutes(e.start)) * minuteHeight
|
||||||
const card = (
|
return (
|
||||||
<button
|
<button
|
||||||
key={e.id}
|
key={e.id}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onEventClick?.(e)}
|
onClick={() => onEventClick?.(e)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"absolute cursor-pointer overflow-hidden rounded-md border-l-[3px] px-1.5 text-left text-xs leading-tight shadow-[0_1px_2px_rgba(15,40,60,0.06)] transition hover:z-10 hover:shadow-md focus-visible:z-10 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
|
"absolute overflow-hidden rounded-md border-l-[3px] px-1.5 text-left text-xs leading-tight shadow-[0_1px_2px_rgba(15,40,60,0.06)] transition hover:z-10 hover:shadow-md focus-visible:z-10 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
|
||||||
toneClass[e.tone ?? "neutral"],
|
toneClass[e.tone ?? "neutral"],
|
||||||
e.muted && "opacity-55",
|
e.muted && "opacity-55",
|
||||||
e.id === selectedId && "z-10 ring-2 ring-primary",
|
e.id === selectedId && "z-10 ring-2 ring-primary",
|
||||||
|
|
@ -295,45 +247,13 @@ export function ScheduleGrid({
|
||||||
width: `calc(${100 / place.lanes}% - 8px)`,
|
width: `calc(${100 / place.lanes}% - 8px)`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{compact ? (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"truncate font-mono text-2xs font-semibold tabular",
|
|
||||||
h >= 30 ? "pt-1" : "pt-px",
|
|
||||||
e.muted && "line-through",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{e.start}
|
|
||||||
<span className="sr-only">
|
|
||||||
{" "}
|
|
||||||
{e.title}
|
|
||||||
{e.subtitle && <>, {e.subtitle}</>}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className={cn("flex min-w-0 items-baseline gap-1.5", h >= 30 ? "pt-1" : "pt-px")}>
|
<div className={cn("flex min-w-0 items-baseline gap-1.5", h >= 30 ? "pt-1" : "pt-px")}>
|
||||||
<span className="shrink-0 font-mono text-2xs text-muted-foreground tabular">{e.start}</span>
|
<span className="shrink-0 font-mono text-2xs text-muted-foreground tabular">{e.start}</span>
|
||||||
<span className={cn("truncate font-semibold", e.muted && "line-through")}>{e.title}</span>
|
<span className={cn("truncate font-semibold", e.muted && "line-through")}>{e.title}</span>
|
||||||
</div>
|
</div>
|
||||||
{e.subtitle && h >= 40 && <div className="truncate text-2xs text-muted-foreground">{e.subtitle}</div>}
|
{e.subtitle && h >= 40 && <div className="truncate text-2xs text-muted-foreground">{e.subtitle}</div>}
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
if (!compact) return card
|
|
||||||
return (
|
|
||||||
<Tooltip key={e.id} delayDuration={300}>
|
|
||||||
<TooltipTrigger asChild>{card}</TooltipTrigger>
|
|
||||||
<TooltipContent side="right">
|
|
||||||
<div className="font-semibold">{e.title}</div>
|
|
||||||
<div className="font-mono text-2xs opacity-75 tabular">
|
|
||||||
{e.start}–{e.end}
|
|
||||||
{e.subtitle && <span className="font-sans"> · {e.subtitle}</span>}
|
|
||||||
</div>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
)
|
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{nowY != null && (
|
{nowY != null && (
|
||||||
|
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import { layoutLanes, type LaneEvent } from "./schedule-lanes"
|
|
||||||
|
|
||||||
function lanes(events: readonly LaneEvent[]) {
|
|
||||||
return Object.fromEntries([...layoutLanes(events)].map(([id, lane]) => [id, lane]))
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("layoutLanes", () => {
|
|
||||||
it("ставит непересекающиеся записи в одну дорожку, каждую своим кластером", () => {
|
|
||||||
expect(
|
|
||||||
lanes([
|
|
||||||
{ id: 1, start: "09:00", end: "10:00" },
|
|
||||||
{ id: 2, start: "10:00", end: "11:00" },
|
|
||||||
]),
|
|
||||||
).toEqual({
|
|
||||||
1: { lane: 0, lanes: 1 },
|
|
||||||
2: { lane: 0, lanes: 1 },
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it("кладёт пересечение рядом и возвращает освободившуюся дорожку следующей записи", () => {
|
|
||||||
expect(
|
|
||||||
lanes([
|
|
||||||
{ id: "a", start: "09:00", end: "10:00" },
|
|
||||||
{ id: "b", start: "09:30", end: "11:00" },
|
|
||||||
{ id: "c", start: "10:00", end: "10:30" },
|
|
||||||
]),
|
|
||||||
).toEqual({
|
|
||||||
a: { lane: 0, lanes: 2 },
|
|
||||||
b: { lane: 1, lanes: 2 },
|
|
||||||
c: { lane: 0, lanes: 2 },
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
import type { Key } from "react"
|
|
||||||
|
|
||||||
/** «ЧЧ:ММ» → минуты от полуночи. */
|
|
||||||
export function minutes(t: string) {
|
|
||||||
return Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LaneEvent {
|
|
||||||
readonly id: Key
|
|
||||||
readonly start: string
|
|
||||||
readonly end: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Раскладка пересекающихся записей одного врача по дорожкам: `lane` из `lanes`. */
|
|
||||||
export function layoutLanes(events: readonly LaneEvent[]) {
|
|
||||||
const sorted = events.toSorted((a, b) => minutes(a.start) - minutes(b.start) || minutes(b.end) - minutes(a.end))
|
|
||||||
const result = new Map<Key, { lane: number; lanes: number }>()
|
|
||||||
let cluster: LaneEvent[] = []
|
|
||||||
let laneEnds: number[] = []
|
|
||||||
let clusterEnd = -1
|
|
||||||
|
|
||||||
const flush = () => {
|
|
||||||
for (const e of cluster) result.set(e.id, { lane: result.get(e.id)!.lane, lanes: laneEnds.length })
|
|
||||||
cluster = []
|
|
||||||
laneEnds = []
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const e of sorted) {
|
|
||||||
const start = minutes(e.start)
|
|
||||||
if (start >= clusterEnd) flush()
|
|
||||||
let lane = laneEnds.findIndex((end) => end <= start)
|
|
||||||
if (lane < 0) lane = laneEnds.push(0) - 1
|
|
||||||
laneEnds[lane] = minutes(e.end)
|
|
||||||
clusterEnd = Math.max(clusterEnd, minutes(e.end))
|
|
||||||
cluster.push(e)
|
|
||||||
result.set(e.id, { lane, lanes: 0 })
|
|
||||||
}
|
|
||||||
flush()
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { SearchIcon, XIcon } from "lucide-react"
|
import { SearchIcon, XIcon } from "lucide-react"
|
||||||
|
|
||||||
import { useFormControl } from "../lib/form-control"
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
/** Поле поиска: иконка, крестик очистки. */
|
/** Поле поиска на мягкой подложке: иконка, крестик очистки. */
|
||||||
export const SearchInput = React.forwardRef<
|
export const SearchInput = React.forwardRef<
|
||||||
HTMLInputElement,
|
HTMLInputElement,
|
||||||
Omit<React.ComponentProps<"input">, "value" | "onChange" | "size"> & {
|
Omit<React.ComponentProps<"input">, "value" | "onChange" | "size"> & {
|
||||||
|
|
@ -14,11 +13,7 @@ export const SearchInput = React.forwardRef<
|
||||||
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
||||||
trailing?: React.ReactNode
|
trailing?: React.ReactNode
|
||||||
}
|
}
|
||||||
>(function SearchInput(
|
>(function SearchInput({ value, onValueChange, size = "md", trailing, className, onKeyDown, ...props }, ref) {
|
||||||
{ value, onValueChange, size = "md", trailing, className, onKeyDown, id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, ...props },
|
|
||||||
ref,
|
|
||||||
) {
|
|
||||||
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
|
||||||
const innerRef = React.useRef<HTMLInputElement>(null)
|
const innerRef = React.useRef<HTMLInputElement>(null)
|
||||||
React.useImperativeHandle(ref, () => innerRef.current!)
|
React.useImperativeHandle(ref, () => innerRef.current!)
|
||||||
|
|
||||||
|
|
@ -42,19 +37,14 @@ export const SearchInput = React.forwardRef<
|
||||||
}
|
}
|
||||||
onKeyDown?.(e)
|
onKeyDown?.(e)
|
||||||
}}
|
}}
|
||||||
{...props}
|
|
||||||
id={field.id}
|
|
||||||
aria-describedby={field["aria-describedby"]}
|
|
||||||
aria-invalid={field["aria-invalid"]}
|
|
||||||
className={cn(
|
className={cn(
|
||||||
// как Input: рамка на белом, та же подсветка фокуса — в строке фильтров стоит рядом с Select
|
"w-full rounded-lg border border-transparent bg-muted/70 transition outline-none placeholder:text-muted-foreground/80 [&::-webkit-search-cancel-button]:hidden",
|
||||||
"w-full min-w-0 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground dark:bg-input/30 [&::-webkit-search-cancel-button]:hidden",
|
"focus:border-primary/40 focus:bg-card focus:ring-4 focus:ring-primary/10",
|
||||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
|
||||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
|
||||||
size === "sm" && "h-8 pr-8 pl-9 text-sm",
|
size === "sm" && "h-8 pr-8 pl-9 text-sm",
|
||||||
size === "md" && "h-9 pr-8 pl-9 text-sm",
|
size === "md" && "h-9 pr-8 pl-9 text-sm",
|
||||||
size === "lg" && "h-12 rounded-xl pr-12 pl-12 text-base",
|
size === "lg" && "h-12 rounded-xl pr-12 pl-12 text-base",
|
||||||
)}
|
)}
|
||||||
|
{...props}
|
||||||
/>
|
/>
|
||||||
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center">
|
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center">
|
||||||
{value ? (
|
{value ? (
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,11 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { Maximize2Icon, Minimize2Icon } from "lucide-react"
|
import { Maximize2Icon, Minimize2Icon } from "lucide-react"
|
||||||
|
|
||||||
import { useScrollMemory } from "../hooks/use-scroll-memory"
|
|
||||||
import { createStore } from "../lib/store"
|
import { createStore } from "../lib/store"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { Button } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
import { Kbd } from "../ui/kbd"
|
import { Kbd } from "../ui/kbd"
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||||
import { useShell } from "./shell-provider"
|
|
||||||
|
|
||||||
// Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает.
|
// Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает.
|
||||||
const maximizedStore = createStore(false)
|
const maximizedStore = createStore(false)
|
||||||
|
|
@ -16,14 +14,10 @@ const toggleMaximized = () => maximizedStore.set((v) => !v)
|
||||||
/**
|
/**
|
||||||
* Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент.
|
* Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент.
|
||||||
* Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть.
|
* Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть.
|
||||||
* Прокрутка контента запоминается по адресу: вернулся на вкладку — на том же месте.
|
|
||||||
* Разделы без вкладок — `PageFrame`.
|
* Разделы без вкладок — `PageFrame`.
|
||||||
*/
|
*/
|
||||||
export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) {
|
export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) {
|
||||||
const maximized = maximizedStore.use()
|
const maximized = maximizedStore.use()
|
||||||
const { pathname, search } = useShell()
|
|
||||||
const contentRef = React.useRef<HTMLDivElement>(null)
|
|
||||||
useScrollMemory(contentRef, pathname + search)
|
|
||||||
|
|
||||||
// Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню).
|
// Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню).
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
|
|
@ -49,20 +43,17 @@ export function SectionFrame({ bar, children }: { bar: React.ReactNode; children
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex min-h-0 flex-1 flex-col",
|
"flex min-h-0 flex-1 flex-col",
|
||||||
// Развёрнуто — поверх меню на тёмной подложке, как будто окно на весь экран.
|
// Развёрнуто — поверх меню на тёмной подложке, как будто окно на весь экран.
|
||||||
maximized ? "fixed inset-0 z-40 bg-sidebar p-2 duration-200 animate-in fade-in" : "p-2 lg:p-3 graphite:p-0",
|
maximized ? "fixed inset-0 z-40 bg-sidebar p-2 duration-200 animate-in fade-in" : "p-2 lg:p-3",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex min-h-0 flex-1 flex-col overflow-clip rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]",
|
"flex min-h-0 flex-1 flex-col overflow-clip rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]",
|
||||||
// В «Графите» карточкой служит сам лист AppShell: вторая рамка внутри него не нужна.
|
maximized && "duration-200 animate-in zoom-in-[0.98]",
|
||||||
maximized ? "duration-200 animate-in zoom-in-[0.98]" : "graphite:rounded-none graphite:border-0 graphite:shadow-none",
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{bar}
|
{bar}
|
||||||
<div ref={contentRef} className="relative flex min-h-0 flex-1 flex-col">
|
<div className="relative flex min-h-0 flex-1 flex-col">{children}</div>
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,488 +0,0 @@
|
||||||
// @vitest-environment jsdom
|
|
||||||
import * as React from "react"
|
|
||||||
import { act, cleanup, render, screen } from "@testing-library/react"
|
|
||||||
import { afterEach, beforeEach, describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import {
|
|
||||||
clearSectionTabState,
|
|
||||||
SectionTabsProvider,
|
|
||||||
useCloseSectionTab,
|
|
||||||
useSectionTabState,
|
|
||||||
useSectionTabs,
|
|
||||||
} from "./section-tabs"
|
|
||||||
import { ShellProvider } from "./shell-provider"
|
|
||||||
|
|
||||||
const ROOT = { id: "root", label: "Список", base: "/x" }
|
|
||||||
const noop = () => {}
|
|
||||||
|
|
||||||
type Setter = React.Dispatch<React.SetStateAction<string>>
|
|
||||||
const setters: Record<string, Setter> = {}
|
|
||||||
let tabs: ReturnType<typeof useSectionTabs>
|
|
||||||
|
|
||||||
function Capture() {
|
|
||||||
tabs = useSectionTabs()
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
function Form({
|
|
||||||
tabId,
|
|
||||||
field = "text",
|
|
||||||
initial = "исходное",
|
|
||||||
version,
|
|
||||||
}: {
|
|
||||||
tabId: string
|
|
||||||
field?: string
|
|
||||||
initial?: string | (() => string)
|
|
||||||
version?: string | number
|
|
||||||
}) {
|
|
||||||
const [value, setValue] = useSectionTabState(tabId, field, initial, version === undefined ? undefined : { version })
|
|
||||||
setters[field === "text" ? tabId : `${tabId}.${field}`] = setValue
|
|
||||||
return <output data-testid={field === "text" ? tabId : `${tabId}.${field}`}>{value}</output>
|
|
||||||
}
|
|
||||||
|
|
||||||
function Section({
|
|
||||||
storageKey = "t",
|
|
||||||
section = "orders",
|
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
storageKey?: string
|
|
||||||
section?: string
|
|
||||||
children?: React.ReactNode
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<ShellProvider storageKey={storageKey} pathname="/x" navigate={noop}>
|
|
||||||
<SectionTabsProvider section={section} root={ROOT}>
|
|
||||||
<Capture />
|
|
||||||
{children}
|
|
||||||
</SectionTabsProvider>
|
|
||||||
</ShellProvider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const shown = (id: string) => screen.getByTestId(id).textContent
|
|
||||||
|
|
||||||
const edit = (id: string, value: string) => act(() => setters[id](value))
|
|
||||||
|
|
||||||
const openTab = (...ids: string[]) =>
|
|
||||||
act(() => {
|
|
||||||
for (const id of ids) tabs.open({ id, label: id, base: `/x/${id}` }, { focus: false })
|
|
||||||
})
|
|
||||||
|
|
||||||
/** Значение поля при новом монтировании формы. */
|
|
||||||
function readFresh(tabId: string, props: { storageKey?: string; section?: string } = {}) {
|
|
||||||
cleanup()
|
|
||||||
render(
|
|
||||||
<Section {...props}>
|
|
||||||
<Form tabId={tabId} />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
const value = shown(tabId)
|
|
||||||
cleanup()
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
localStorage.clear()
|
|
||||||
clearSectionTabState()
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(cleanup)
|
|
||||||
|
|
||||||
describe("useSectionTabState: значение", () => {
|
|
||||||
it("без записи возвращает initial", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(shown("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("принимает ленивый initial", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" initial={() => "из функции"} />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(shown("a")).toBe("из функции")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("восстанавливает значение, когда форма размонтирована внутри раздела", () => {
|
|
||||||
const view = render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a", "черновик")
|
|
||||||
view.rerender(<Section />)
|
|
||||||
expect(screen.queryByTestId("a")).toBeNull()
|
|
||||||
view.rerender(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(shown("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("восстанавливает значение после размонтирования всего раздела", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a", "черновик")
|
|
||||||
expect(readFresh("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("работает с функциональными обновлениями, идущими подряд", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" initial="" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
act(() => {
|
|
||||||
setters.a((v) => v + "1")
|
|
||||||
setters.a((v) => v + "2")
|
|
||||||
})
|
|
||||||
expect(shown("a")).toBe("12")
|
|
||||||
expect(readFresh("a")).toBe("12")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("не меняет setValue между рендерами", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
const first = setters.a
|
|
||||||
edit("a", "черновик")
|
|
||||||
expect(setters.a).toBe(first)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("без правок при следующем монтировании берёт новый initial", () => {
|
|
||||||
const view = render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" initial="старые данные" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
view.rerender(<Section />)
|
|
||||||
view.rerender(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" initial="новые данные" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(shown("a")).toBe("новые данные")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("в StrictMode не считает initial правкой и сохраняет настоящие", () => {
|
|
||||||
const strict = (initial: string) => (
|
|
||||||
<React.StrictMode>
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" initial={initial} />
|
|
||||||
</Section>
|
|
||||||
</React.StrictMode>
|
|
||||||
)
|
|
||||||
render(strict("старые данные"))
|
|
||||||
cleanup()
|
|
||||||
render(strict("новые данные"))
|
|
||||||
expect(shown("a")).toBe("новые данные")
|
|
||||||
edit("a", "черновик")
|
|
||||||
cleanup()
|
|
||||||
render(strict("новые данные"))
|
|
||||||
expect(shown("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("пишет значение и до регистрации вкладки", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(tabs.tabs.some((t) => t.id === "a")).toBe(false)
|
|
||||||
edit("a", "черновик")
|
|
||||||
expect(readFresh("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("useSectionTabState: version", () => {
|
|
||||||
const withVersion = (version: string | number) => (
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" version={version} />
|
|
||||||
</Section>
|
|
||||||
)
|
|
||||||
|
|
||||||
it("при той же version восстанавливает значение", () => {
|
|
||||||
render(withVersion("v1"))
|
|
||||||
edit("a", "черновик")
|
|
||||||
cleanup()
|
|
||||||
render(withVersion("v1"))
|
|
||||||
expect(shown("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("при другой version сбрасывает на initial", () => {
|
|
||||||
render(withVersion("v1"))
|
|
||||||
edit("a", "черновик")
|
|
||||||
cleanup()
|
|
||||||
render(withVersion("v2"))
|
|
||||||
expect(shown("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("при смене version без размонтирования сбрасывает на initial и не портит запись старой", () => {
|
|
||||||
const view = render(withVersion("v1"))
|
|
||||||
edit("a", "черновик")
|
|
||||||
view.rerender(withVersion("v2"))
|
|
||||||
expect(shown("a")).toBe("исходное")
|
|
||||||
view.rerender(withVersion("v1"))
|
|
||||||
expect(shown("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("useSectionTabState: разделение", () => {
|
|
||||||
it("смена tabId в одном экземпляре не смешивает значения", () => {
|
|
||||||
const form = (tabId: string) => (
|
|
||||||
<Section>
|
|
||||||
<Form key="один экземпляр" tabId={tabId} />
|
|
||||||
</Section>
|
|
||||||
)
|
|
||||||
const view = render(form("a"))
|
|
||||||
edit("a", "значение a")
|
|
||||||
|
|
||||||
view.rerender(form("b"))
|
|
||||||
expect(shown("b")).toBe("исходное")
|
|
||||||
edit("b", "значение b")
|
|
||||||
|
|
||||||
view.rerender(form("a"))
|
|
||||||
expect(shown("a")).toBe("значение a")
|
|
||||||
view.rerender(form("b"))
|
|
||||||
expect(shown("b")).toBe("значение b")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("поля одной вкладки независимы", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" field="first" />
|
|
||||||
<Form tabId="a" field="second" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a.first", "1")
|
|
||||||
expect(shown("a.second")).toBe("исходное")
|
|
||||||
cleanup()
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" field="first" />
|
|
||||||
<Form tabId="a" field="second" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
expect(shown("a.first")).toBe("1")
|
|
||||||
expect(shown("a.second")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("не смешивает вкладки, разделы и storageKey", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a", "черновик")
|
|
||||||
expect(readFresh("b")).toBe("исходное")
|
|
||||||
expect(readFresh("a", { section: "panels" })).toBe("исходное")
|
|
||||||
expect(readFresh("a", { storageKey: "other" })).toBe("исходное")
|
|
||||||
expect(readFresh("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("useSectionTabState: закрытие вкладок", () => {
|
|
||||||
function draft(...ids: string[]) {
|
|
||||||
render(<Section>{ids.map((id) => <Form key={id} tabId={id} />)}</Section>)
|
|
||||||
openTab(...ids)
|
|
||||||
for (const id of ids) edit(id, `черновик ${id}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
it("close стирает значение вкладки и не трогает соседнюю", () => {
|
|
||||||
draft("a", "b")
|
|
||||||
act(() => tabs.close("a"))
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
expect(readFresh("b")).toBe("черновик b")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("closeOthers стирает всё, кроме выбранной", () => {
|
|
||||||
draft("a", "b", "c")
|
|
||||||
act(() => tabs.closeOthers("b"))
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
expect(readFresh("b")).toBe("черновик b")
|
|
||||||
expect(readFresh("c")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("closeToRight стирает только вкладки правее", () => {
|
|
||||||
// Новая вкладка встаёт сразу справа от активной, поэтому открываем с конца.
|
|
||||||
draft("c", "b", "a")
|
|
||||||
expect(tabs.tabs.map((t) => t.id)).toEqual([ROOT.id, "a", "b", "c"])
|
|
||||||
act(() => tabs.closeToRight("b"))
|
|
||||||
expect(readFresh("a")).toBe("черновик a")
|
|
||||||
expect(readFresh("b")).toBe("черновик b")
|
|
||||||
expect(readFresh("c")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("closeAll стирает открытые вкладки, но не закреплённую корневую", () => {
|
|
||||||
draft("a")
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId={ROOT.id} />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit(ROOT.id, "фильтр списка")
|
|
||||||
act(() => tabs.closeAll())
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
expect(readFresh(ROOT.id)).toBe("фильтр списка")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("правка в одном батче с закрытием не возвращает запись", () => {
|
|
||||||
draft("a")
|
|
||||||
act(() => {
|
|
||||||
setters.a("последняя правка")
|
|
||||||
tabs.close("a")
|
|
||||||
})
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("форма, ещё смонтированная после закрытия, запись не возвращает", () => {
|
|
||||||
draft("a")
|
|
||||||
act(() => tabs.close("a"))
|
|
||||||
edit("a", "правка после закрытия")
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("после повторного открытия вкладки запись снова работает", () => {
|
|
||||||
draft("a")
|
|
||||||
act(() => tabs.close("a"))
|
|
||||||
openTab("a")
|
|
||||||
edit("a", "новый черновик")
|
|
||||||
expect(readFresh("a")).toBe("новый черновик")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("useCloseSectionTab", () => {
|
|
||||||
let closeExternal: ReturnType<typeof useCloseSectionTab>
|
|
||||||
|
|
||||||
function Closer() {
|
|
||||||
closeExternal = useCloseSectionTab()
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Раздел размонтирован: остались только меню и хранилище. */
|
|
||||||
function renderMenuOnly() {
|
|
||||||
cleanup()
|
|
||||||
render(
|
|
||||||
<ShellProvider storageKey="t" pathname="/other" navigate={noop}>
|
|
||||||
<Closer />
|
|
||||||
</ShellProvider>,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
it("при смонтированном разделе стирает значение", () => {
|
|
||||||
render(
|
|
||||||
<ShellProvider storageKey="t" pathname="/x" navigate={noop}>
|
|
||||||
<Closer />
|
|
||||||
<SectionTabsProvider section="orders" root={ROOT}>
|
|
||||||
<Capture />
|
|
||||||
<Form tabId="a" />
|
|
||||||
</SectionTabsProvider>
|
|
||||||
</ShellProvider>,
|
|
||||||
)
|
|
||||||
openTab("a")
|
|
||||||
edit("a", "черновик")
|
|
||||||
act(() => closeExternal("orders", "a"))
|
|
||||||
expect(tabs.tabs.some((t) => t.id === "a")).toBe(false)
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("при размонтированном разделе стирает значение", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
<Form tabId="b" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
openTab("a", "b")
|
|
||||||
edit("a", "черновик a")
|
|
||||||
edit("b", "черновик b")
|
|
||||||
|
|
||||||
renderMenuOnly()
|
|
||||||
act(() => closeExternal("orders", "a"))
|
|
||||||
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
expect(readFresh("b")).toBe("черновик b")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("не стирает значение закреплённой вкладки, которая не закрывается", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId={ROOT.id} />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit(ROOT.id, "фильтр списка")
|
|
||||||
|
|
||||||
renderMenuOnly()
|
|
||||||
act(() => closeExternal("orders", ROOT.id))
|
|
||||||
|
|
||||||
expect(readFresh(ROOT.id)).toBe("фильтр списка")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("clearSectionTabState", () => {
|
|
||||||
it("стирает значения всех вкладок, разделов и storageKey", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a", "1")
|
|
||||||
cleanup()
|
|
||||||
render(
|
|
||||||
<Section section="panels" storageKey="other">
|
|
||||||
<Form tabId="b" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("b", "2")
|
|
||||||
|
|
||||||
clearSectionTabState()
|
|
||||||
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
expect(readFresh("b", { section: "panels", storageKey: "other" })).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("правка в одном батче с очисткой не возвращает запись", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
act(() => {
|
|
||||||
setters.a("данные пациента")
|
|
||||||
clearSectionTabState()
|
|
||||||
})
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("форма, пережившая очистку, больше не пишет", () => {
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
act(() => clearSectionTabState())
|
|
||||||
edit("a", "данные пациента")
|
|
||||||
expect(readFresh("a")).toBe("исходное")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("форма, смонтированная после очистки, пишет как обычно", () => {
|
|
||||||
clearSectionTabState()
|
|
||||||
render(
|
|
||||||
<Section>
|
|
||||||
<Form tabId="a" />
|
|
||||||
</Section>,
|
|
||||||
)
|
|
||||||
edit("a", "черновик")
|
|
||||||
expect(readFresh("a")).toBe("черновик")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -17,7 +17,6 @@ import { useShell } from "./shell-provider"
|
||||||
* поэтому при переключении человек возвращается ровно туда, где был.
|
* поэтому при переключении человек возвращается ровно туда, где был.
|
||||||
* Набор вкладок переживает перезагрузку (localStorage, ключ `<storageKey>.section-tabs.<раздел>`).
|
* Набор вкладок переживает перезагрузку (localStorage, ключ `<storageKey>.section-tabs.<раздел>`).
|
||||||
* Адрес и переход берутся из ShellProvider.
|
* Адрес и переход берутся из ShellProvider.
|
||||||
* Несохранённое состояние форм — `useSectionTabState`: живёт только в памяти, пока вкладка открыта.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export type SectionTabTone = "male" | "female" | "neutral"
|
export type SectionTabTone = "male" | "female" | "neutral"
|
||||||
|
|
@ -59,42 +58,6 @@ const changeEvent = (storageKey: string) => `${storageKey}:section-tabs`
|
||||||
/** Разделы, чей провайдер сейчас смонтирован, — им закрытие передаётся напрямую. Ключ — storageName. */
|
/** Разделы, чей провайдер сейчас смонтирован, — им закрытие передаётся напрямую. Ключ — storageName. */
|
||||||
const mountedClosers = new Map<string, (id: string) => void>()
|
const mountedClosers = new Map<string, (id: string) => void>()
|
||||||
|
|
||||||
type SectionTabStateVersion = string | number
|
|
||||||
|
|
||||||
interface SectionTabStateRecord {
|
|
||||||
readonly value: unknown
|
|
||||||
readonly version: SectionTabStateVersion | undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Состояние форм на вкладках: storageName → id вкладки → имя поля.
|
|
||||||
* Только в памяти: данные пациента не попадают в хранилище браузера, при перезагрузке страницы состояние теряется.
|
|
||||||
*/
|
|
||||||
const tabStates = new Map<string, Map<string, Map<string, SectionTabStateRecord>>>()
|
|
||||||
/** Растёт при каждом clearSectionTabState: формы, смонтированные раньше, больше не пишут. */
|
|
||||||
let tabStateGeneration = 0
|
|
||||||
|
|
||||||
function writeTabState(scope: string, tabId: string, field: string, record: SectionTabStateRecord) {
|
|
||||||
let section = tabStates.get(scope)
|
|
||||||
if (!section) tabStates.set(scope, (section = new Map()))
|
|
||||||
let fields = section.get(tabId)
|
|
||||||
if (!fields) section.set(tabId, (fields = new Map()))
|
|
||||||
fields.set(field, record)
|
|
||||||
}
|
|
||||||
|
|
||||||
function dropTabState(scope: string, tabId: string) {
|
|
||||||
const section = tabStates.get(scope)
|
|
||||||
if (!section) return
|
|
||||||
section.delete(tabId)
|
|
||||||
if (section.size === 0) tabStates.delete(scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Стереть состояние всех вкладок всех разделов. Приложение вызывает при выходе пользователя. */
|
|
||||||
export function clearSectionTabState() {
|
|
||||||
tabStates.clear()
|
|
||||||
tabStateGeneration += 1
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStored(storageKey: string, section: string): SectionTab[] | null {
|
function readStored(storageKey: string, section: string): SectionTab[] | null {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(storageName(storageKey, section))
|
const raw = localStorage.getItem(storageName(storageKey, section))
|
||||||
|
|
@ -205,11 +168,6 @@ export function SectionTabsProvider({
|
||||||
if (next.length === list.length) return
|
if (next.length === list.length) return
|
||||||
setTabs(next)
|
setTabs(next)
|
||||||
|
|
||||||
const scope = storageName(storageKey, section)
|
|
||||||
for (const tab of list) {
|
|
||||||
if (!next.includes(tab)) dropTabState(scope, tab.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentId = activeRef.current
|
const currentId = activeRef.current
|
||||||
if (currentId && !next.some((t) => t.id === currentId)) {
|
if (currentId && !next.some((t) => t.id === currentId)) {
|
||||||
const oldIndex = list.findIndex((t) => t.id === currentId)
|
const oldIndex = list.findIndex((t) => t.id === currentId)
|
||||||
|
|
@ -217,7 +175,7 @@ export function SectionTabsProvider({
|
||||||
if (fallback) navigate(fallback.href)
|
if (fallback) navigate(fallback.href)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[navigate, storageKey, section],
|
[navigate],
|
||||||
)
|
)
|
||||||
|
|
||||||
const value = React.useMemo<SectionTabsValue>(
|
const value = React.useMemo<SectionTabsValue>(
|
||||||
|
|
@ -309,76 +267,12 @@ export function useCloseSectionTab() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const stored = readStored(storageKey, section)
|
const stored = readStored(storageKey, section)
|
||||||
if (stored?.some((t) => t.pinned && t.id === id)) return
|
if (stored) writeStored(storageKey, section, stored.filter((t) => t.pinned || t.id !== id))
|
||||||
dropTabState(storageName(storageKey, section), id)
|
|
||||||
if (stored) writeStored(storageKey, section, stored.filter((t) => t.id !== id))
|
|
||||||
},
|
},
|
||||||
[storageKey],
|
[storageKey],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* `useState`, значение которого переживает уход с вкладки: вернулись — форма такая же, как при уходе.
|
|
||||||
* Стирается при закрытии вкладки (любым способом) и при `clearSectionTabState`. Хранится только в памяти.
|
|
||||||
*
|
|
||||||
* `tabId` передаётся явно: у новой вкладки до регистрации `activeId` ещё пуст.
|
|
||||||
* `version` — чем отличаются исходные данные: запись с другой версией не восстанавливается, форма берёт `initial`.
|
|
||||||
* В хранилище попадает только изменённое значение: без правок форма при возврате получит свежий `initial`.
|
|
||||||
*/
|
|
||||||
export function useSectionTabState<T>(
|
|
||||||
tabId: string,
|
|
||||||
field: string,
|
|
||||||
initial: T | (() => T),
|
|
||||||
options?: { version?: SectionTabStateVersion },
|
|
||||||
): [T, React.Dispatch<React.SetStateAction<T>>] {
|
|
||||||
const { section, tabs } = useSectionTabs()
|
|
||||||
const { storageKey } = useShell()
|
|
||||||
const scope = storageName(storageKey, section)
|
|
||||||
const version = options?.version
|
|
||||||
const slot = JSON.stringify([scope, tabId, field, version])
|
|
||||||
|
|
||||||
const load = () => {
|
|
||||||
const saved = tabStates.get(scope)?.get(tabId)?.get(field)
|
|
||||||
if (saved && saved.version === version) return { slot, value: saved.value as T }
|
|
||||||
return { slot, value: typeof initial === "function" ? (initial as () => T)() : initial }
|
|
||||||
}
|
|
||||||
|
|
||||||
const [stored, setStored] = React.useState(load)
|
|
||||||
let state = stored
|
|
||||||
// Тот же экземпляр показывает другую вкладку или версию: значение прежней сюда не переносим.
|
|
||||||
if (stored.slot !== slot) {
|
|
||||||
state = load()
|
|
||||||
setStored(state)
|
|
||||||
}
|
|
||||||
|
|
||||||
const setValue = React.useCallback<React.Dispatch<React.SetStateAction<T>>>((action) => {
|
|
||||||
setStored((prev) => {
|
|
||||||
const value = typeof action === "function" ? (action as (prev: T) => T)(prev.value) : action
|
|
||||||
return Object.is(value, prev.value) ? prev : { ...prev, value }
|
|
||||||
})
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const isOpen = tabs.some((t) => t.id === tabId)
|
|
||||||
const seen = React.useRef<typeof state | null>(null)
|
|
||||||
const lastOpenId = React.useRef<string | null>(null)
|
|
||||||
const generation = React.useRef(tabStateGeneration)
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (isOpen) lastOpenId.current = tabId
|
|
||||||
|
|
||||||
const previous = seen.current
|
|
||||||
seen.current = state
|
|
||||||
if (!previous || previous.slot !== state.slot || Object.is(previous.value, state.value)) return
|
|
||||||
// Вкладку закрыли или пользователь вышел, а форма ещё на экране: стёртое не возвращаем.
|
|
||||||
if (lastOpenId.current === tabId && !isOpen) return
|
|
||||||
if (generation.current !== tabStateGeneration) return
|
|
||||||
|
|
||||||
writeTabState(scope, tabId, field, { value: state.value, version })
|
|
||||||
}, [state, isOpen, scope, tabId, field, version])
|
|
||||||
|
|
||||||
return [state.value, setValue]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PageTabs, подключённые к вкладкам раздела: роутинг, хоткеи, контекстное меню. */
|
/** PageTabs, подключённые к вкладкам раздела: роутинг, хоткеи, контекстное меню. */
|
||||||
export function SectionTabsBar({ rootIcon, actions }: { rootIcon: LucideIcon; actions?: React.ReactNode }) {
|
export function SectionTabsBar({ rootIcon, actions }: { rootIcon: LucideIcon; actions?: React.ReactNode }) {
|
||||||
const { tabs, activeId, activate, close, closeOthers, closeToRight, closeAll, move } = useSectionTabs()
|
const { tabs, activeId, activate, close, closeOthers, closeToRight, closeAll, move } = useSectionTabs()
|
||||||
|
|
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
import * as React from "react"
|
|
||||||
import { XIcon, type LucideIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { useMediaQuery } from "../hooks/use-media-query"
|
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
import { ShellLink } from "./shell-provider"
|
|
||||||
|
|
||||||
export interface SidebarCard {
|
|
||||||
readonly id: string
|
|
||||||
readonly title: string
|
|
||||||
/** Одна строка, не поместится — многоточие. */
|
|
||||||
readonly description?: string
|
|
||||||
readonly icon?: LucideIcon
|
|
||||||
readonly to: string
|
|
||||||
/** Перед переходом (например, отметить прочитанным). */
|
|
||||||
readonly onClick?: () => void
|
|
||||||
/** Есть — при наведении на карточке крестик: закрыть без перехода. */
|
|
||||||
readonly onDismiss?: () => void
|
|
||||||
/** Цвет карточки по типу: подложка и иконка. В оформлении «Графит» карточки остаются монохромными. */
|
|
||||||
readonly tone?: SidebarCardTone
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SidebarCardTone = "positive" | "info" | "warning" | "negative"
|
|
||||||
|
|
||||||
// Цвет кладётся в --tone, из него смешиваются подложка и иконка.
|
|
||||||
const toneVar: Record<SidebarCardTone, string> = {
|
|
||||||
positive: "[--tone:var(--success)]",
|
|
||||||
info: "[--tone:var(--info)]",
|
|
||||||
warning: "[--tone:var(--warning)]",
|
|
||||||
negative: "[--tone:var(--coral)]",
|
|
||||||
}
|
|
||||||
|
|
||||||
const TONED_CARD =
|
|
||||||
"bg-[color-mix(in_oklab,var(--tone)_13%,transparent)] hover:bg-[color-mix(in_oklab,var(--tone)_18%,transparent)] graphite:bg-sidebar-surface graphite:hover:bg-sidebar-surface-hover"
|
|
||||||
// Иконку тянем к «чернилам» меню: на тёмном меню она светлее, на светлом — темнее.
|
|
||||||
const TONED_ICON = "text-[color-mix(in_oklab,var(--tone)_78%,var(--sidebar-ink))] graphite:text-sidebar-primary"
|
|
||||||
|
|
||||||
export interface SidebarCardsProps {
|
|
||||||
/** Что за карточки: для скринридера. */
|
|
||||||
readonly label: string
|
|
||||||
readonly items: readonly SidebarCard[]
|
|
||||||
/** Смена карточки, мс. */
|
|
||||||
readonly interval?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Высота блока с отступом снизу: AppSidebar показывает его, только если под меню есть столько места. */
|
|
||||||
export const SIDEBAR_CARDS_HEIGHT = 68
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Листающиеся карточки внизу бокового меню. Сами сменяются по `interval`, на наведении и фокусе
|
|
||||||
* с клавиатуры останавливаются; при «уменьшить движение» в системе видна только первая.
|
|
||||||
*/
|
|
||||||
export function SidebarCards({ label, items, interval = 6000 }: SidebarCardsProps) {
|
|
||||||
const [index, setIndex] = React.useState(0)
|
|
||||||
const [paused, setPaused] = React.useState(false)
|
|
||||||
const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)")
|
|
||||||
const count = items.length
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (paused || reducedMotion || count < 2) return
|
|
||||||
const timer = window.setInterval(() => setIndex((i) => i + 1), interval)
|
|
||||||
return () => window.clearInterval(timer)
|
|
||||||
}, [paused, reducedMotion, count, interval])
|
|
||||||
|
|
||||||
if (count === 0) return null
|
|
||||||
// Список мог уменьшиться (карточку прочитали) — индекс остаётся в его пределах.
|
|
||||||
const active = index % count
|
|
||||||
const card = items[active]
|
|
||||||
const Icon = card.icon
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="shrink-0 px-3 pb-2">
|
|
||||||
<section
|
|
||||||
aria-label={label}
|
|
||||||
onMouseEnter={() => setPaused(true)}
|
|
||||||
onMouseLeave={() => setPaused(false)}
|
|
||||||
// Только фокус с клавиатуры: после клика мышью ссылка остаётся в фокусе, и листание бы не возобновилось.
|
|
||||||
onFocus={(e) => e.target.matches(":focus-visible") && setPaused(true)}
|
|
||||||
onBlur={() => setPaused(false)}
|
|
||||||
className={cn(
|
|
||||||
"group/card relative rounded-lg p-2.5 transition-colors",
|
|
||||||
card.tone ? [toneVar[card.tone], TONED_CARD] : "bg-sidebar-surface hover:bg-sidebar-surface-hover",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<ShellLink
|
|
||||||
href={card.to}
|
|
||||||
onClick={card.onClick}
|
|
||||||
className="block rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60"
|
|
||||||
>
|
|
||||||
<span key={card.id} className="block motion-safe:duration-300 motion-safe:animate-in motion-safe:fade-in">
|
|
||||||
{/* Отступ только пока виден крестик: без него название не обрезается раньше времени. */}
|
|
||||||
<span className="flex h-5 items-center gap-1.5 text-xs font-medium text-sidebar-strong group-focus-within/card:pr-5 group-hover/card:pr-5">
|
|
||||||
{Icon && <Icon className={cn("size-3.5 shrink-0", card.tone ? TONED_ICON : "text-sidebar-primary")} />}
|
|
||||||
<span className="truncate">{card.title}</span>
|
|
||||||
</span>
|
|
||||||
<span title={card.description} className="mt-0.5 block h-4 truncate text-2xs leading-4 text-sidebar-muted">
|
|
||||||
{card.description}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</ShellLink>
|
|
||||||
{card.onDismiss && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-label={`Закрыть: ${card.title}`}
|
|
||||||
onClick={card.onDismiss}
|
|
||||||
className="absolute top-2.5 right-1.5 grid size-5 place-items-center rounded text-sidebar-muted opacity-0 transition group-hover/card:opacity-100 hover:bg-sidebar-ink/10 hover:text-sidebar-strong focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-primary/60"
|
|
||||||
>
|
|
||||||
<XIcon className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -45,26 +45,15 @@ export function StatusDot({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const sizeClass = {
|
/** Статус с цветной точкой: «Работает», «Записан», «Неявка»… `pulse` — точка мигает («Подключение…»). */
|
||||||
sm: "gap-1 px-1.5 py-px text-2xs",
|
|
||||||
md: "gap-1.5 px-2 py-0.5 text-xs",
|
|
||||||
lg: "gap-2 px-2.5 py-1 text-sm",
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Статус с цветной точкой: «Работает», «Записан», «Неявка»… `pulse` — точка мигает («Подключение…»).
|
|
||||||
* `size="sm"` — в плотных строках таблиц и рядом с мелкими метками, `"lg"` — в шапке карточки или страницы.
|
|
||||||
*/
|
|
||||||
export function StatusBadge({
|
export function StatusBadge({
|
||||||
tone,
|
tone,
|
||||||
size = "md",
|
|
||||||
dot = true,
|
dot = true,
|
||||||
pulse,
|
pulse,
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
tone: StatusTone
|
tone: StatusTone
|
||||||
size?: "sm" | "md" | "lg"
|
|
||||||
dot?: boolean
|
dot?: boolean
|
||||||
pulse?: boolean
|
pulse?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
|
|
@ -73,13 +62,12 @@ export function StatusBadge({
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"inline-flex items-center rounded-md border font-semibold whitespace-nowrap",
|
"inline-flex items-center gap-1.5 rounded-md border px-2 py-0.5 text-xs font-semibold whitespace-nowrap",
|
||||||
sizeClass[size],
|
|
||||||
toneClass[tone],
|
toneClass[tone],
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{dot && <StatusDot pulse={pulse} className={cn(size === "lg" && "size-2")} />}
|
{dot && <StatusDot pulse={pulse} />}
|
||||||
{children}
|
{children}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -7,27 +7,19 @@ export interface TimeRangeValue {
|
||||||
to: string
|
to: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Диапазон времени «с–по» в одну строку; подсвечивается, если «по» раньше «с». */
|
||||||
* Диапазон времени «с–по» в одну строку; подсвечивается, если «по» не позже «с».
|
|
||||||
* С `overnight` «по» раньше «с» — переход через полночь (21:00–00:00), ошибка только при «с» = «по».
|
|
||||||
*/
|
|
||||||
export function TimeRangeInput({
|
export function TimeRangeInput({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
onRemove,
|
onRemove,
|
||||||
overnight = false,
|
|
||||||
className,
|
className,
|
||||||
}: {
|
}: {
|
||||||
value: TimeRangeValue
|
value: TimeRangeValue
|
||||||
onChange: (value: TimeRangeValue) => void
|
onChange: (value: TimeRangeValue) => void
|
||||||
onRemove?: () => void
|
onRemove?: () => void
|
||||||
/** Разрешить интервал через полночь: «по» раньше «с» не считается ошибкой. */
|
|
||||||
overnight?: boolean
|
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const invalid = Boolean(
|
const invalid = Boolean(value.from && value.to && value.to <= value.from)
|
||||||
value.from && value.to && (overnight ? value.to === value.from : value.to <= value.from),
|
|
||||||
)
|
|
||||||
// Ширина ровно под «ЧЧ:ММ»: моноширинный шрифт, без иконки часов и внутренних отступов браузера.
|
// Ширина ровно под «ЧЧ:ММ»: моноширинный шрифт, без иконки часов и внутренних отступов браузера.
|
||||||
const input =
|
const input =
|
||||||
"h-6 w-[calc(5ch+12px)] rounded bg-transparent px-[3px] font-mono text-xs tabular outline-none focus:bg-accent/60 [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-datetime-edit]:p-0 [&::-webkit-datetime-edit-fields-wrapper]:p-0"
|
"h-6 w-[calc(5ch+12px)] rounded bg-transparent px-[3px] font-mono text-xs tabular outline-none focus:bg-accent/60 [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-datetime-edit]:p-0 [&::-webkit-datetime-edit-fields-wrapper]:p-0"
|
||||||
|
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
import { XIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { formatBytes } from "../lib/format"
|
|
||||||
import { cn } from "../lib/utils"
|
|
||||||
import { Button } from "../ui/button"
|
|
||||||
import { Progress } from "../ui/progress"
|
|
||||||
import { FileTypeIcon } from "./file-type-icon"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Строка загружаемого файла: имя, размер, полоса прогресса и отмена.
|
|
||||||
* `progress` — проценты, `null` — неизвестно, сколько осталось (бегущий отрезок).
|
|
||||||
* С `error` вместо полосы — текст ошибки, а крестик скрывает строку.
|
|
||||||
*/
|
|
||||||
export function UploadProgress({
|
|
||||||
file,
|
|
||||||
progress = null,
|
|
||||||
error,
|
|
||||||
onCancel,
|
|
||||||
className,
|
|
||||||
}: {
|
|
||||||
file: { readonly name: string; readonly size: number; readonly type?: string }
|
|
||||||
progress?: number | null
|
|
||||||
error?: string
|
|
||||||
onCancel?: () => void
|
|
||||||
className?: string
|
|
||||||
}) {
|
|
||||||
const percent = progress === null ? null : Math.round(progress)
|
|
||||||
const cancelLabel = error ? "Скрыть" : "Отменить загрузку"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={cn("flex items-center gap-2.5 rounded-lg bg-muted/50 px-3 py-2", className)}>
|
|
||||||
<FileTypeIcon file={file} />
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<div className="truncate text-sm font-medium" title={file.name}>
|
|
||||||
{file.name}
|
|
||||||
</div>
|
|
||||||
{error ? (
|
|
||||||
<div role="alert" className="text-xs text-coral">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="text-xs text-muted-foreground tabular">
|
|
||||||
{formatBytes(file.size)} · {percent === null ? "Загрузка…" : `Загрузка ${percent}%`}
|
|
||||||
</div>
|
|
||||||
<Progress value={percent} aria-label={`Загрузка файла ${file.name}`} className="mt-1 h-1" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{onCancel && (
|
|
||||||
<Button variant="ghost" size="icon-sm" title={cancelLabel} aria-label={cancelLabel} onClick={onCancel}>
|
|
||||||
<XIcon />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
import * as React from "react"
|
|
||||||
|
|
||||||
/** Идентификаторы поля, которые FormField отдаёт вложенному контролу. */
|
|
||||||
export interface FormControlState {
|
|
||||||
readonly id: string
|
|
||||||
/** Есть, только когда под полем виден текст подсказки или ошибки. */
|
|
||||||
readonly descriptionId?: string
|
|
||||||
readonly invalid: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
const FormControlContext = React.createContext<FormControlState | null>(null)
|
|
||||||
|
|
||||||
export function FormControlProvider({ value, children }: { value: FormControlState; children: React.ReactNode }) {
|
|
||||||
return React.createElement(FormControlContext.Provider, { value }, children)
|
|
||||||
}
|
|
||||||
|
|
||||||
type AriaInvalid = React.AriaAttributes["aria-invalid"]
|
|
||||||
|
|
||||||
interface ControlProps {
|
|
||||||
id?: string
|
|
||||||
"aria-describedby"?: string
|
|
||||||
"aria-invalid"?: AriaInvalid
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Подмешивает id, aria-describedby и aria-invalid из FormField.
|
|
||||||
* Свой id у контрола важнее: так второе поле диапазона не забирает id первого.
|
|
||||||
* Вне FormField пропсы возвращаются как есть.
|
|
||||||
*/
|
|
||||||
export function useFormControl(props: ControlProps): ControlProps {
|
|
||||||
const field = React.useContext(FormControlContext)
|
|
||||||
if (!field) return props
|
|
||||||
const describedBy = [field.descriptionId, props["aria-describedby"]].filter(Boolean).join(" ") || undefined
|
|
||||||
return {
|
|
||||||
...props,
|
|
||||||
id: props.id ?? field.id,
|
|
||||||
"aria-describedby": describedBy,
|
|
||||||
"aria-invalid": mergeInvalid(props["aria-invalid"], field.invalid),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeInvalid(own: AriaInvalid, fieldInvalid: boolean): AriaInvalid {
|
|
||||||
if (own === true || own === "true" || fieldInvalid) return true
|
|
||||||
if (own === "grammar" || own === "spelling") return own
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import { formatBytes } from "./format"
|
|
||||||
|
|
||||||
describe("formatBytes", () => {
|
|
||||||
it("пишет единицы по-русски", () => {
|
|
||||||
expect(formatBytes(512)).toBe("512 Б")
|
|
||||||
expect(formatBytes(2048)).toBe("2 КБ")
|
|
||||||
expect(formatBytes(5 * 1024 * 1024)).toBe("5 МБ")
|
|
||||||
expect(formatBytes(3 * 1024 ** 3)).toBe("3 ГБ")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("дробную часть отделяет запятой, у больших чисел её нет", () => {
|
|
||||||
expect(formatBytes(1536)).toBe("1,5 КБ")
|
|
||||||
expect(formatBytes(12_582_912)).toBe("12 МБ")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -12,18 +12,16 @@ export function pluralYears(age: number) {
|
||||||
return `${age} ${plural(age, "год", "года", "лет")}`
|
return `${age} ${plural(age, "год", "года", "лет")}`
|
||||||
}
|
}
|
||||||
|
|
||||||
/** «512 Б», «1,5 КБ», «12 МБ»: у чисел от десяти дробная часть не нужна. */
|
|
||||||
export function formatBytes(bytes: number) {
|
export function formatBytes(bytes: number) {
|
||||||
if (bytes < 1024) return `${bytes} Б`
|
if (bytes < 1024) return `${bytes} B`
|
||||||
const units = ["КБ", "МБ", "ГБ"]
|
const units = ["KB", "MB", "GB"]
|
||||||
let value = bytes / 1024
|
let value = bytes / 1024
|
||||||
let unit = 0
|
let unit = 0
|
||||||
while (value >= 1024 && unit < units.length - 1) {
|
while (value >= 1024 && unit < units.length - 1) {
|
||||||
value /= 1024
|
value /= 1024
|
||||||
unit++
|
unit++
|
||||||
}
|
}
|
||||||
const text = value >= 10 ? String(Math.round(value)) : String(Number(value.toFixed(1))).replace(".", ",")
|
return `${value.toFixed(1)} ${units[unit]}`
|
||||||
return `${text} ${units[unit]}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** «1 300,00 ₽» */
|
/** «1 300,00 ₽» */
|
||||||
|
|
|
||||||
|
|
@ -1,151 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest"
|
|
||||||
|
|
||||||
import {
|
|
||||||
isDatePrefixValid,
|
|
||||||
isSnilsValid,
|
|
||||||
maskDate,
|
|
||||||
maskPhone,
|
|
||||||
maskSnils,
|
|
||||||
maskWithCaret,
|
|
||||||
parseRuDate,
|
|
||||||
} from "./masks"
|
|
||||||
|
|
||||||
function field(value: string, caret: number) {
|
|
||||||
return { value, selectionStart: caret } as HTMLInputElement
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("maskPhone", () => {
|
|
||||||
it("форматирует 10 цифр и отбрасывает 7 или 8 в начале", () => {
|
|
||||||
expect(maskPhone("9141231212")).toBe("(914) 123-12-12")
|
|
||||||
expect(maskPhone("+7 (914) 123-12-12")).toBe("(914) 123-12-12")
|
|
||||||
expect(maskPhone("89141231212")).toBe("(914) 123-12-12")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("не добивает номер нулями", () => {
|
|
||||||
expect(maskPhone("914")).toBe("(914")
|
|
||||||
expect(maskPhone("")).toBe("")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("maskSnils / isSnilsValid", () => {
|
|
||||||
it("ставит дефисы и пробел", () => {
|
|
||||||
expect(maskSnils("11223344595")).toBe("112-233-445 95")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("проверяет контрольное число и не ругает короткий номер как неверный формат длины 11", () => {
|
|
||||||
expect(isSnilsValid("112-233-445 95")).toBe(true)
|
|
||||||
expect(isSnilsValid("112-233-445 96")).toBe(false)
|
|
||||||
expect(isSnilsValid("112-233-445")).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("isDatePrefixValid / parseRuDate", () => {
|
|
||||||
it("пускает недописанную дату и отвергает невозможную", () => {
|
|
||||||
expect(isDatePrefixValid("3")).toBe(true)
|
|
||||||
expect(isDatePrefixValid("31.1")).toBe(true)
|
|
||||||
expect(isDatePrefixValid("29.02.2024")).toBe(true)
|
|
||||||
expect(isDatePrefixValid("40")).toBe(false)
|
|
||||||
expect(isDatePrefixValid("31.04")).toBe(false)
|
|
||||||
expect(isDatePrefixValid("12.13")).toBe(false)
|
|
||||||
expect(isDatePrefixValid("29.02.2023")).toBe(false)
|
|
||||||
expect(isDatePrefixValid("23.0_.2020")).toBe(true)
|
|
||||||
expect(isDatePrefixValid("29.02._024")).toBe(true)
|
|
||||||
expect(isDatePrefixValid("23.2_.2020")).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("разбирает только существующую полную дату", () => {
|
|
||||||
const date = parseRuDate("17.05.1984")
|
|
||||||
expect(date).toEqual(new Date(1984, 4, 17))
|
|
||||||
expect(parseRuDate("29.02.2024")).toEqual(new Date(2024, 1, 29))
|
|
||||||
expect(parseRuDate("29.02.2023")).toBeNull()
|
|
||||||
expect(parseRuDate("31.04.2024")).toBeNull()
|
|
||||||
expect(parseRuDate("17.05")).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("maskWithCaret", () => {
|
|
||||||
it("оставляет курсор после вставленной цифры, а не в конце номера", () => {
|
|
||||||
const next = maskWithCaret(field("(914) 912", 7), "insertText", "(914) 12", maskPhone)
|
|
||||||
expect(next).toEqual({ value: "(914) 912", caret: 7 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it("при удалении разделителя стирает соседнюю цифру", () => {
|
|
||||||
const next = maskWithCaret(field("1205", 2), "deleteContentBackward", "12.05", maskDate)
|
|
||||||
expect(next).toEqual({ value: "10.05", caret: 1 })
|
|
||||||
const withGap = maskWithCaret(field("1205", 2), "deleteContentBackward", "12.05", maskDate, isDatePrefixValid, "_")
|
|
||||||
expect(withGap).toEqual({ value: "10.05", caret: 1 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it("оставляет дырку на месте стёртой цифры, если правее ещё есть цифры", () => {
|
|
||||||
expect(maskDate("4")).toBe("04")
|
|
||||||
const next = maskWithCaret(
|
|
||||||
field("23.0.2020", 4),
|
|
||||||
"deleteContentBackward",
|
|
||||||
"23.04.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(next).toEqual({ value: "23.0_.2020", caret: 4 })
|
|
||||||
expect(maskDate("23.__.2020")).toBe("23.__.2020")
|
|
||||||
})
|
|
||||||
|
|
||||||
it("цифра занимает дырку и не сдвигает год", () => {
|
|
||||||
const next = maskWithCaret(
|
|
||||||
field("23.04_.2020", 5),
|
|
||||||
"insertText",
|
|
||||||
"23.0_.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(next).toEqual({ value: "23.04.2020", caret: 5 })
|
|
||||||
const padded = maskWithCaret(
|
|
||||||
field("23.4__.2020", 4),
|
|
||||||
"insertText",
|
|
||||||
"23.__.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(padded).toEqual({ value: "23.04.2020", caret: 5 })
|
|
||||||
const forward = maskWithCaret(
|
|
||||||
field("23.0.2020", 4),
|
|
||||||
"deleteContentForward",
|
|
||||||
"23.04.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(forward).toEqual({ value: "23.0_.2020", caret: 4 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it("стирание последней цифры года не ставит прочерк", () => {
|
|
||||||
const next = maskWithCaret(
|
|
||||||
field("23.04.202", 9),
|
|
||||||
"deleteContentBackward",
|
|
||||||
"23.04.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(next).toEqual({ value: "23.04.202", caret: 9 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it("стирание прочерка не смыкает маску", () => {
|
|
||||||
const next = maskWithCaret(
|
|
||||||
field("23.0.2020", 4),
|
|
||||||
"deleteContentBackward",
|
|
||||||
"23.0_.2020",
|
|
||||||
maskDate,
|
|
||||||
isDatePrefixValid,
|
|
||||||
"_",
|
|
||||||
)
|
|
||||||
expect(next).toEqual({ value: "23.0_.2020", caret: 4 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it("не вставляет цифру, из которой не получится дата", () => {
|
|
||||||
const next = maskWithCaret(field("32", 2), "insertText", "3", (value) => value.replace(/\D/g, "").slice(0, 2), isDatePrefixValid)
|
|
||||||
expect(next).toEqual({ value: "3", caret: 1 })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
144
src/lib/masks.ts
144
src/lib/masks.ts
|
|
@ -37,34 +37,8 @@ export function isSnilsValid(value: string) {
|
||||||
return control === Number(d.slice(9))
|
return control === Number(d.slice(9))
|
||||||
}
|
}
|
||||||
|
|
||||||
const DATE_GAP = "_"
|
/** «дд.мм.гггг». Первая цифра дня больше 3 или месяца больше 1 однозначна — дописываем ноль: «4» → «04». */
|
||||||
const DATE_GROUP_LIMITS = [2, 2, 4]
|
|
||||||
|
|
||||||
/** Группы дд, мм, гггг. «_» занимает позицию и не даёт следующим цифрам сдвинуться. */
|
|
||||||
function dateGroups(value: string) {
|
|
||||||
const groups: string[][] = [[], [], []]
|
|
||||||
let g = 0
|
|
||||||
for (const ch of value) {
|
|
||||||
if (ch === ".") {
|
|
||||||
if (g < 2) g++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (ch !== DATE_GAP && !/\d/.test(ch)) continue
|
|
||||||
if (groups[g].length >= DATE_GROUP_LIMITS[g]) {
|
|
||||||
if (g >= 2) break
|
|
||||||
g++
|
|
||||||
}
|
|
||||||
groups[g].push(ch)
|
|
||||||
}
|
|
||||||
return groups
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* «дд.мм.гггг». Первая цифра дня больше 3 или месяца больше 1 однозначна — дописываем ноль: «4» → «04»,
|
|
||||||
* но только если вторая позиция пары пустая. «_» — дырка на месте стёртой цифры, хвост остаётся на месте.
|
|
||||||
*/
|
|
||||||
export function maskDate(value: string) {
|
export function maskDate(value: string) {
|
||||||
if (!value.includes(DATE_GAP)) {
|
|
||||||
let d = ""
|
let d = ""
|
||||||
for (const ch of onlyDigits(value)) {
|
for (const ch of onlyDigits(value)) {
|
||||||
if ((d.length === 0 && ch > "3") || (d.length === 2 && ch > "1")) d += "0"
|
if ((d.length === 0 && ch > "3") || (d.length === 2 && ch > "1")) d += "0"
|
||||||
|
|
@ -75,82 +49,13 @@ export function maskDate(value: string) {
|
||||||
if (d.length > 2) out += `.${d.slice(2, 4)}`
|
if (d.length > 2) out += `.${d.slice(2, 4)}`
|
||||||
if (d.length > 4) out += `.${d.slice(4, 8)}`
|
if (d.length > 4) out += `.${d.slice(4, 8)}`
|
||||||
return out
|
return out
|
||||||
}
|
|
||||||
const groups = dateGroups(value)
|
|
||||||
for (const gi of [0, 1]) {
|
|
||||||
const slots = groups[gi]
|
|
||||||
const ch = slots[0]
|
|
||||||
const needsZero = Boolean(ch && /\d/.test(ch) && ch > (gi === 0 ? "3" : "1"))
|
|
||||||
const secondEmpty = slots.length === 1 || slots[1] === DATE_GAP
|
|
||||||
if (needsZero && secondEmpty) {
|
|
||||||
slots[0] = "0"
|
|
||||||
slots[1] = ch
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let lastG = -1
|
|
||||||
let lastI = -1
|
|
||||||
for (let gi = 0; gi < 3; gi++) {
|
|
||||||
for (let i = 0; i < groups[gi].length; i++) {
|
|
||||||
if (/\d/.test(groups[gi][i])) {
|
|
||||||
lastG = gi
|
|
||||||
lastI = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (lastG < 0) return ""
|
|
||||||
let out = ""
|
|
||||||
for (let gi = 0; gi <= lastG; gi++) {
|
|
||||||
if (gi > 0) out += "."
|
|
||||||
const width = gi < lastG ? DATE_GROUP_LIMITS[gi] : lastI + 1
|
|
||||||
for (let i = 0; i < width; i++) out += groups[gi][i] ?? DATE_GAP
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Какие числа пары ещё возможны. null — пару ещё не начали. Пустой список — уже невозможно. */
|
|
||||||
function possiblePair(slots: string[], lo: number, hi: number, maxTens: number) {
|
|
||||||
if (slots.length === 0) return null
|
|
||||||
const tens = slots[0] === DATE_GAP ? Array.from({ length: maxTens + 1 }, (_, i) => i) : [Number(slots[0])]
|
|
||||||
const units =
|
|
||||||
slots[1] === undefined || slots[1] === DATE_GAP ? Array.from({ length: 10 }, (_, i) => i) : [Number(slots[1])]
|
|
||||||
const out: number[] = []
|
|
||||||
for (const t of tens) {
|
|
||||||
for (const u of units) {
|
|
||||||
const n = t * 10 + u
|
|
||||||
if (n >= lo && n <= hi) out.push(n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
function yearSlotsPossible(slots: string[]) {
|
|
||||||
if (slots.length === 0) return true
|
|
||||||
return ["19", "20"].some((prefix) =>
|
|
||||||
slots.every((ch, i) => ch === DATE_GAP || (i < 2 ? ch === prefix[i] : /\d/.test(ch))),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Может ли введённое начало стать настоящей датой: «3», «31.1», «29.02.20» — да;
|
* Может ли введённое начало стать настоящей датой: «3», «31.1», «29.02.20» — да;
|
||||||
* «40», «31.04», «12.13», «29.02.2023» — нет. Годы — 1900–2099.
|
* «40», «31.04», «12.13», «29.02.2023» — нет. Годы — 1900–2099.
|
||||||
* «_» — пустая позиция: «23.0_.2020» ещё можно дописать, «23.2_.2020» — нет.
|
|
||||||
* Пока в годе есть дырка, 29 февраля допустимо.
|
|
||||||
*/
|
*/
|
||||||
export function isDatePrefixValid(value: string) {
|
export function isDatePrefixValid(value: string) {
|
||||||
if (value.includes(DATE_GAP)) {
|
|
||||||
const [day, month, year] = dateGroups(value)
|
|
||||||
const days = possiblePair(day, 1, 31, 3)
|
|
||||||
if (days && days.length === 0) return false
|
|
||||||
const months = possiblePair(month, 1, 12, 1)
|
|
||||||
if (months && months.length === 0) return false
|
|
||||||
if (!yearSlotsPossible(year)) return false
|
|
||||||
if (days && months) {
|
|
||||||
const yearReady = year.length === 4 && year.every((ch) => /\d/.test(ch))
|
|
||||||
const y = yearReady ? Number(year.join("")) : 2000
|
|
||||||
if (!months.some((m) => days.some((d) => d <= new Date(y, m, 0).getDate()))) return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
const d = onlyDigits(value)
|
const d = onlyDigits(value)
|
||||||
const num = (from: number, to: number) => Number(d.slice(from, to))
|
const num = (from: number, to: number) => Number(d.slice(from, to))
|
||||||
if (d.length >= 1 && d[0] > "3") return false
|
if (d.length >= 1 && d[0] > "3") return false
|
||||||
|
|
@ -217,37 +122,9 @@ export function isSameDay(a: Date | null | undefined, b: Date | null | undefined
|
||||||
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
|
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Хвост начинается с дырки (после точек) — цифра должна занять её, а не встать левее. */
|
|
||||||
function dropNextGap(tail: string, gap: string) {
|
|
||||||
let i = 0
|
|
||||||
while (i < tail.length && tail[i] === ".") i++
|
|
||||||
if (tail[i] !== gap) return tail
|
|
||||||
return tail.slice(0, i) + tail.slice(i + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
function slotCount(value: string, gap: string) {
|
|
||||||
let n = 0
|
|
||||||
for (const ch of value) if (/\d/.test(ch) || ch === gap) n++
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Курсор перед позицией: дырка не считается пройденной. */
|
|
||||||
function caretAtSlot(value: string, index: number, gap: string) {
|
|
||||||
let seen = 0
|
|
||||||
let pos = 0
|
|
||||||
for (; pos < value.length; pos++) {
|
|
||||||
const ch = value[pos]
|
|
||||||
if (ch !== gap && !/\d/.test(ch)) continue
|
|
||||||
if (seen === index) return pos
|
|
||||||
seen++
|
|
||||||
}
|
|
||||||
return pos
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Применить маску к полю, не теряя курсор: правка в середине не уводит каретку в конец,
|
* Применить маску к полю, не теряя курсор: правка в середине не уводит каретку в конец,
|
||||||
* а удаление разделителя стирает соседнюю цифру (иначе маска сразу вернула бы его обратно).
|
* а удаление разделителя стирает соседнюю цифру (иначе маска сразу вернула бы его обратно).
|
||||||
* gap — дырка на месте стёртой цифры, если правее ещё есть цифры (для даты «_»).
|
|
||||||
* Возвращает новое значение и позицию курсора в нём.
|
* Возвращает новое значение и позицию курсора в нём.
|
||||||
*/
|
*/
|
||||||
export function maskWithCaret(
|
export function maskWithCaret(
|
||||||
|
|
@ -257,23 +134,15 @@ export function maskWithCaret(
|
||||||
mask: (value: string) => string,
|
mask: (value: string) => string,
|
||||||
/** Проверка набранного (не удаления): неподходящие символы просто не попадают в поле. */
|
/** Проверка набранного (не удаления): неподходящие символы просто не попадают в поле. */
|
||||||
accept?: (value: string) => boolean,
|
accept?: (value: string) => boolean,
|
||||||
gap?: string,
|
|
||||||
) {
|
) {
|
||||||
let raw = input.value
|
let raw = input.value
|
||||||
let caret = input.selectionStart ?? raw.length
|
let caret = input.selectionStart ?? raw.length
|
||||||
const single = raw.length + 1 === previous.length
|
const removedSeparator = raw.length === previous.length - 1 && onlyDigits(raw) === onlyDigits(previous)
|
||||||
const deleted = single ? (previous[caret] ?? "") : ""
|
if (removedSeparator && inputType === "deleteContentBackward" && caret > 0) {
|
||||||
const removedSeparator = single && onlyDigits(raw) === onlyDigits(previous)
|
|
||||||
if (gap && deleted === gap) {
|
|
||||||
// Стирание прочерка не смыкает разряды.
|
|
||||||
raw = raw.slice(0, caret) + gap + raw.slice(caret)
|
|
||||||
} else if (removedSeparator && inputType === "deleteContentBackward" && caret > 0) {
|
|
||||||
raw = raw.slice(0, caret - 1) + raw.slice(caret)
|
raw = raw.slice(0, caret - 1) + raw.slice(caret)
|
||||||
caret -= 1
|
caret -= 1
|
||||||
} else if (removedSeparator && inputType === "deleteContentForward") {
|
} else if (removedSeparator && inputType === "deleteContentForward") {
|
||||||
raw = raw.slice(0, caret) + raw.slice(caret + 1)
|
raw = raw.slice(0, caret) + raw.slice(caret + 1)
|
||||||
} else if (gap && /\d/.test(deleted) && /\d/.test(raw.slice(caret))) {
|
|
||||||
raw = raw.slice(0, caret) + gap + raw.slice(caret)
|
|
||||||
}
|
}
|
||||||
if (accept && inputType?.startsWith("insert")) {
|
if (accept && inputType?.startsWith("insert")) {
|
||||||
// Вставленный кусок лежит перед курсором; хвост после курсора не менялся.
|
// Вставленный кусок лежит перед курсором; хвост после курсора не менялся.
|
||||||
|
|
@ -286,8 +155,7 @@ export function maskWithCaret(
|
||||||
// Символы проверяем по одному, как при наборе: «40.33.6566» → «04.03».
|
// Символы проверяем по одному, как при наборе: «40.33.6566» → «04.03».
|
||||||
let kept = raw.slice(0, common)
|
let kept = raw.slice(0, common)
|
||||||
for (const ch of raw.slice(common, caret)) {
|
for (const ch of raw.slice(common, caret)) {
|
||||||
const replacingGap = gap !== undefined && dropNextGap(tail, gap) !== tail
|
const rest = full ? tail.replace(/^\D*\d/, "") : tail
|
||||||
const rest = replacingGap ? dropNextGap(tail, gap) : full ? tail.replace(/^\D*\d/, "") : tail
|
|
||||||
if (accept(mask(kept + ch + rest))) {
|
if (accept(mask(kept + ch + rest))) {
|
||||||
kept += ch
|
kept += ch
|
||||||
tail = rest
|
tail = rest
|
||||||
|
|
@ -297,10 +165,6 @@ export function maskWithCaret(
|
||||||
caret = kept.length
|
caret = kept.length
|
||||||
}
|
}
|
||||||
const value = mask(raw)
|
const value = mask(raw)
|
||||||
if (gap && value.includes(gap)) {
|
|
||||||
const slotsBefore = slotCount(mask(raw.slice(0, caret)), gap)
|
|
||||||
return { value, caret: caretAtSlot(value, slotsBefore, gap) }
|
|
||||||
}
|
|
||||||
// Маска идёт слева направо, поэтому цифры до курсора — это маска того, что до курсора (с дописанными нулями).
|
// Маска идёт слева направо, поэтому цифры до курсора — это маска того, что до курсора (с дописанными нулями).
|
||||||
const digitsBefore = onlyDigits(mask(raw.slice(0, caret))).length
|
const digitsBefore = onlyDigits(mask(raw.slice(0, caret))).length
|
||||||
let pos = 0
|
let pos = 0
|
||||||
|
|
|
||||||
126
src/styles.css
126
src/styles.css
|
|
@ -3,7 +3,6 @@
|
||||||
* @import "tailwindcss";
|
* @import "tailwindcss";
|
||||||
* @import "@medkit/ui/styles.css";
|
* @import "@medkit/ui/styles.css";
|
||||||
* Переопределить палитру можно своими :root / .dark после импорта.
|
* Переопределить палитру можно своими :root / .dark после импорта.
|
||||||
* Второе оформление — «Графит»: [data-style="graphite"] на <html>, его ставит ThemeProvider.
|
|
||||||
*/
|
*/
|
||||||
@import "tw-animate-css";
|
@import "tw-animate-css";
|
||||||
@import "@fontsource-variable/onest";
|
@import "@fontsource-variable/onest";
|
||||||
|
|
@ -13,8 +12,6 @@
|
||||||
@source ".";
|
@source ".";
|
||||||
|
|
||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
/* Форма, а не цвет: то, что в «Графите» устроено иначе, например лист без рамки внутри */
|
|
||||||
@custom-variant graphite (&:is([data-style="graphite"] *));
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Палитра «клинический бирюзовый».
|
* Палитра «клинический бирюзовый».
|
||||||
|
|
@ -63,23 +60,6 @@
|
||||||
--sidebar-accent: oklch(0.3 0.045 220);
|
--sidebar-accent: oklch(0.3 0.045 220);
|
||||||
--sidebar-primary: oklch(0.8 0.12 185);
|
--sidebar-primary: oklch(0.8 0.12 185);
|
||||||
--sidebar-border: oklch(0.3 0.035 228);
|
--sidebar-border: oklch(0.3 0.035 228);
|
||||||
/* Текст активного пункта; «чернила» — наведение и обводки с прозрачностью: sidebar-ink/[0.05] */
|
|
||||||
--sidebar-strong: #fff;
|
|
||||||
--sidebar-ink: #fff;
|
|
||||||
/* Текст на жёлтом счётчике */
|
|
||||||
--sidebar-on-warning: var(--sidebar);
|
|
||||||
/* Поиск, карточки, часы */
|
|
||||||
--sidebar-surface: rgb(255 255 255 / 0.04);
|
|
||||||
--sidebar-surface-hover: rgb(255 255 255 / 0.07);
|
|
||||||
--sidebar-surface-border: rgb(255 255 255 / 0.08);
|
|
||||||
--sidebar-surface-border-hover: rgb(255 255 255 / 0.12);
|
|
||||||
--sidebar-surface-highlight: rgb(255 255 255 / 0.03);
|
|
||||||
--sidebar-footer: rgb(0 0 0 / 0.04);
|
|
||||||
--sidebar-footer-shadow: rgb(0 0 0 / 0.06);
|
|
||||||
--sidebar-frame: var(--sidebar-border);
|
|
||||||
|
|
||||||
/* Лист с разделом поверх меню: подсветка края в тёмной теме */
|
|
||||||
--sheet-ring: transparent;
|
|
||||||
|
|
||||||
/* Графики: категориальные слоты проверены на различимость при дальтонизме */
|
/* Графики: категориальные слоты проверены на различимость при дальтонизме */
|
||||||
--chart-1: #2a78d6;
|
--chart-1: #2a78d6;
|
||||||
|
|
@ -128,8 +108,6 @@
|
||||||
--sidebar-primary: oklch(0.8 0.12 185);
|
--sidebar-primary: oklch(0.8 0.12 185);
|
||||||
--sidebar-border: oklch(0.22 0.02 235);
|
--sidebar-border: oklch(0.22 0.02 235);
|
||||||
|
|
||||||
--sheet-ring: rgb(255 255 255 / 0.06);
|
|
||||||
|
|
||||||
--chart-1: #3987e5;
|
--chart-1: #3987e5;
|
||||||
--chart-2: #d95926;
|
--chart-2: #d95926;
|
||||||
--chart-3: #199e70;
|
--chart-3: #199e70;
|
||||||
|
|
@ -138,91 +116,6 @@
|
||||||
--chart-grid: oklch(0.28 0.02 235);
|
--chart-grid: oklch(0.28 0.02 235);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Оформление «Графит»: монохром, светлое меню на сером, белый лист.
|
|
||||||
* Цвет — только у статусов и тревожных отметок; цвета пола те же, что в клиническом оформлении.
|
|
||||||
* Токены, которых здесь нет, берутся из :root и .dark.
|
|
||||||
*/
|
|
||||||
[data-style="graphite"] {
|
|
||||||
--background: oklch(1 0 0);
|
|
||||||
--foreground: oklch(0.21 0.004 265);
|
|
||||||
--card: oklch(1 0 0);
|
|
||||||
--card-foreground: oklch(0.21 0.004 265);
|
|
||||||
--popover: oklch(1 0 0);
|
|
||||||
--popover-foreground: oklch(0.21 0.004 265);
|
|
||||||
--primary: oklch(0.22 0.004 265);
|
|
||||||
--primary-foreground: oklch(0.985 0 0);
|
|
||||||
--secondary: oklch(0.965 0.001 265);
|
|
||||||
--secondary-foreground: oklch(0.27 0.004 265);
|
|
||||||
--muted: oklch(0.968 0.001 265);
|
|
||||||
--muted-foreground: oklch(0.52 0.006 265);
|
|
||||||
--accent: oklch(0.955 0.001 265);
|
|
||||||
--accent-foreground: oklch(0.24 0.004 265);
|
|
||||||
--border: oklch(0.93 0.002 265);
|
|
||||||
--input: oklch(0.91 0.002 265);
|
|
||||||
--ring: oklch(0.62 0.006 265);
|
|
||||||
|
|
||||||
--sidebar: oklch(0.945 0.002 265);
|
|
||||||
--sidebar-foreground: oklch(0.36 0.006 265);
|
|
||||||
--sidebar-muted: oklch(0.52 0.006 265);
|
|
||||||
--sidebar-accent: oklch(0.895 0.003 265);
|
|
||||||
--sidebar-primary: oklch(0.24 0.004 265);
|
|
||||||
--sidebar-border: oklch(0.885 0.003 265);
|
|
||||||
--sidebar-strong: oklch(0.2 0.004 265);
|
|
||||||
--sidebar-ink: #000;
|
|
||||||
--sidebar-on-warning: oklch(0.2 0.004 265);
|
|
||||||
--sidebar-surface: oklch(1 0 0);
|
|
||||||
--sidebar-surface-hover: oklch(0.985 0 0);
|
|
||||||
--sidebar-surface-border: rgb(0 0 0 / 0.05);
|
|
||||||
--sidebar-surface-border-hover: rgb(0 0 0 / 0.09);
|
|
||||||
--sidebar-surface-highlight: transparent;
|
|
||||||
--sidebar-footer: transparent;
|
|
||||||
--sidebar-footer-shadow: transparent;
|
|
||||||
--sidebar-frame: transparent;
|
|
||||||
|
|
||||||
--sheet-ring: rgb(0 0 0 / 0.04);
|
|
||||||
|
|
||||||
--chart-grid: oklch(0.94 0.002 265);
|
|
||||||
}
|
|
||||||
|
|
||||||
[data-style="graphite"].dark {
|
|
||||||
--background: oklch(0.2 0.003 265);
|
|
||||||
--foreground: oklch(0.94 0.002 265);
|
|
||||||
--card: oklch(0.235 0.003 265);
|
|
||||||
--card-foreground: oklch(0.94 0.002 265);
|
|
||||||
--popover: oklch(0.25 0.003 265);
|
|
||||||
--popover-foreground: oklch(0.94 0.002 265);
|
|
||||||
--primary: oklch(0.93 0.002 265);
|
|
||||||
--primary-foreground: oklch(0.2 0.003 265);
|
|
||||||
--secondary: oklch(0.275 0.003 265);
|
|
||||||
--secondary-foreground: oklch(0.9 0.002 265);
|
|
||||||
--muted: oklch(0.26 0.003 265);
|
|
||||||
--muted-foreground: oklch(0.7 0.004 265);
|
|
||||||
--accent: oklch(0.3 0.003 265);
|
|
||||||
--accent-foreground: oklch(0.94 0.002 265);
|
|
||||||
--border: oklch(0.29 0.003 265);
|
|
||||||
--input: oklch(0.32 0.003 265);
|
|
||||||
--ring: oklch(0.6 0.005 265);
|
|
||||||
|
|
||||||
--sidebar: oklch(0.155 0.002 265);
|
|
||||||
--sidebar-foreground: oklch(0.78 0.004 265);
|
|
||||||
--sidebar-muted: oklch(0.58 0.005 265);
|
|
||||||
--sidebar-accent: oklch(0.25 0.003 265);
|
|
||||||
--sidebar-primary: oklch(0.93 0.002 265);
|
|
||||||
--sidebar-border: oklch(0.25 0.003 265);
|
|
||||||
--sidebar-strong: oklch(0.98 0 0);
|
|
||||||
--sidebar-ink: #fff;
|
|
||||||
--sidebar-on-warning: oklch(0.155 0.002 265);
|
|
||||||
--sidebar-surface: rgb(255 255 255 / 0.05);
|
|
||||||
--sidebar-surface-hover: rgb(255 255 255 / 0.08);
|
|
||||||
--sidebar-surface-border: rgb(255 255 255 / 0.07);
|
|
||||||
--sidebar-surface-border-hover: rgb(255 255 255 / 0.12);
|
|
||||||
|
|
||||||
--sheet-ring: rgb(255 255 255 / 0.06);
|
|
||||||
|
|
||||||
--chart-grid: oklch(0.29 0.003 265);
|
|
||||||
}
|
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--font-sans: "Onest Variable", ui-sans-serif, system-ui, sans-serif;
|
--font-sans: "Onest Variable", ui-sans-serif, system-ui, sans-serif;
|
||||||
--font-mono: "JetBrains Mono Variable", ui-monospace, monospace;
|
--font-mono: "JetBrains Mono Variable", ui-monospace, monospace;
|
||||||
|
|
@ -280,18 +173,6 @@
|
||||||
--color-sidebar-accent: var(--sidebar-accent);
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
--color-sidebar-primary: var(--sidebar-primary);
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
--color-sidebar-border: var(--sidebar-border);
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
--color-sidebar-strong: var(--sidebar-strong);
|
|
||||||
--color-sidebar-ink: var(--sidebar-ink);
|
|
||||||
--color-sidebar-on-warning: var(--sidebar-on-warning);
|
|
||||||
--color-sidebar-surface: var(--sidebar-surface);
|
|
||||||
--color-sidebar-surface-hover: var(--sidebar-surface-hover);
|
|
||||||
--color-sidebar-surface-border: var(--sidebar-surface-border);
|
|
||||||
--color-sidebar-surface-border-hover: var(--sidebar-surface-border-hover);
|
|
||||||
--color-sidebar-surface-highlight: var(--sidebar-surface-highlight);
|
|
||||||
--color-sidebar-footer: var(--sidebar-footer);
|
|
||||||
--color-sidebar-footer-shadow: var(--sidebar-footer-shadow);
|
|
||||||
--color-sidebar-frame: var(--sidebar-frame);
|
|
||||||
--color-sheet-ring: var(--sheet-ring);
|
|
||||||
|
|
||||||
/* Курсор в ячейке InputOTP */
|
/* Курсор в ячейке InputOTP */
|
||||||
--animate-caret-blink: caret-blink 1.25s ease-out infinite;
|
--animate-caret-blink: caret-blink 1.25s ease-out infinite;
|
||||||
|
|
@ -307,13 +188,6 @@
|
||||||
50% { opacity: 0.3; }
|
50% { opacity: 0.3; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Иконка пункта меню при наведении: чуть увеличивается и плавно возвращается */
|
|
||||||
--animate-nav-icon: nav-icon 0.35s ease-out;
|
|
||||||
@keyframes nav-icon {
|
|
||||||
0%, 100% { transform: scale(1); }
|
|
||||||
40% { transform: scale(1.1); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Progress без value и LoadingBar: отрезок бежит слева направо */
|
/* Progress без value и LoadingBar: отрезок бежит слева направо */
|
||||||
--animate-progress-indeterminate: progress-indeterminate 1.2s ease-in-out infinite;
|
--animate-progress-indeterminate: progress-indeterminate 1.2s ease-in-out infinite;
|
||||||
@keyframes progress-indeterminate {
|
@keyframes progress-indeterminate {
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,6 @@ import * as React from "react"
|
||||||
export type Theme = "light" | "dark" | "system"
|
export type Theme = "light" | "dark" | "system"
|
||||||
/** Тема, которая сейчас на экране. */
|
/** Тема, которая сейчас на экране. */
|
||||||
export type ResolvedTheme = "light" | "dark"
|
export type ResolvedTheme = "light" | "dark"
|
||||||
/** Оформление, не зависит от светлой и тёмной темы: `clinical` — бирюзовое с тёмным меню, `graphite` — монохромное со светлым меню. */
|
|
||||||
export type ThemeStyle = "clinical" | "graphite"
|
|
||||||
|
|
||||||
const DARK_QUERY = "(prefers-color-scheme: dark)"
|
const DARK_QUERY = "(prefers-color-scheme: dark)"
|
||||||
|
|
||||||
|
|
@ -13,8 +11,6 @@ interface ThemeContextValue {
|
||||||
theme: Theme
|
theme: Theme
|
||||||
resolvedTheme: ResolvedTheme
|
resolvedTheme: ResolvedTheme
|
||||||
setTheme: (theme: Theme) => void
|
setTheme: (theme: Theme) => void
|
||||||
style: ThemeStyle
|
|
||||||
setStyle: (style: ThemeStyle) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ThemeContext = React.createContext<ThemeContextValue | null>(null)
|
const ThemeContext = React.createContext<ThemeContextValue | null>(null)
|
||||||
|
|
@ -23,27 +19,15 @@ function isTheme(value: unknown): value is Theme {
|
||||||
return value === "light" || value === "dark" || value === "system"
|
return value === "light" || value === "dark" || value === "system"
|
||||||
}
|
}
|
||||||
|
|
||||||
function isThemeStyle(value: unknown): value is ThemeStyle {
|
function readTheme(storageKey: string, fallback: Theme): Theme {
|
||||||
return value === "clinical" || value === "graphite"
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStored<T>(key: string, isValid: (value: unknown) => value is T, fallback: T): T {
|
|
||||||
try {
|
try {
|
||||||
const stored = localStorage.getItem(key)
|
const stored = localStorage.getItem(storageKey)
|
||||||
return isValid(stored) ? stored : fallback
|
return isTheme(stored) ? stored : fallback
|
||||||
} catch {
|
} catch {
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeStored(key: string, value: string) {
|
|
||||||
try {
|
|
||||||
localStorage.setItem(key, value)
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function systemTheme(): ResolvedTheme {
|
function systemTheme(): ResolvedTheme {
|
||||||
return typeof window !== "undefined" && window.matchMedia?.(DARK_QUERY).matches ? "dark" : "light"
|
return typeof window !== "undefined" && window.matchMedia?.(DARK_QUERY).matches ? "dark" : "light"
|
||||||
}
|
}
|
||||||
|
|
@ -62,24 +46,19 @@ function useSystemTheme() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Светлая, тёмная или «как в системе»: класс `dark` на <html>. Оформление — атрибут `data-style`
|
* Светлая, тёмная или «как в системе»: класс `dark` на <html>, выбор помнится в localStorage.
|
||||||
* на <html> (у `clinical` его нет). Выбор помнится в localStorage: тема — `storageKey`, оформление — `<storageKey>.style`.
|
* `defaultTheme` — пока пользователь ничего не выбрал.
|
||||||
* `defaultTheme` и `defaultStyle` — пока пользователь ничего не выбрал.
|
|
||||||
*/
|
*/
|
||||||
export function ThemeProvider({
|
export function ThemeProvider({
|
||||||
defaultTheme = "light",
|
defaultTheme = "light",
|
||||||
defaultStyle = "clinical",
|
|
||||||
storageKey = "ml.theme",
|
storageKey = "ml.theme",
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
defaultTheme?: Theme
|
defaultTheme?: Theme
|
||||||
defaultStyle?: ThemeStyle
|
|
||||||
storageKey?: string
|
storageKey?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
const styleKey = `${storageKey}.style`
|
const [theme, setThemeState] = React.useState<Theme>(() => readTheme(storageKey, defaultTheme))
|
||||||
const [theme, setThemeState] = React.useState<Theme>(() => readStored(storageKey, isTheme, defaultTheme))
|
|
||||||
const [style, setStyleState] = React.useState<ThemeStyle>(() => readStored(styleKey, isThemeStyle, defaultStyle))
|
|
||||||
const system = useSystemTheme()
|
const system = useSystemTheme()
|
||||||
const resolvedTheme = theme === "system" ? system : theme
|
const resolvedTheme = theme === "system" ? system : theme
|
||||||
|
|
||||||
|
|
@ -88,31 +67,19 @@ export function ThemeProvider({
|
||||||
document.documentElement.style.colorScheme = resolvedTheme
|
document.documentElement.style.colorScheme = resolvedTheme
|
||||||
}, [resolvedTheme])
|
}, [resolvedTheme])
|
||||||
|
|
||||||
React.useLayoutEffect(() => {
|
|
||||||
if (style === "clinical") document.documentElement.removeAttribute("data-style")
|
|
||||||
else document.documentElement.setAttribute("data-style", style)
|
|
||||||
}, [style])
|
|
||||||
|
|
||||||
const setTheme = React.useCallback(
|
const setTheme = React.useCallback(
|
||||||
(next: Theme) => {
|
(next: Theme) => {
|
||||||
setThemeState(next)
|
setThemeState(next)
|
||||||
writeStored(storageKey, next)
|
try {
|
||||||
|
localStorage.setItem(storageKey, next)
|
||||||
|
} catch {
|
||||||
|
/* noop */
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[storageKey],
|
[storageKey],
|
||||||
)
|
)
|
||||||
|
|
||||||
const setStyle = React.useCallback(
|
const value = React.useMemo(() => ({ theme, resolvedTheme, setTheme }), [theme, resolvedTheme, setTheme])
|
||||||
(next: ThemeStyle) => {
|
|
||||||
setStyleState(next)
|
|
||||||
writeStored(styleKey, next)
|
|
||||||
},
|
|
||||||
[styleKey],
|
|
||||||
)
|
|
||||||
|
|
||||||
const value = React.useMemo(
|
|
||||||
() => ({ theme, resolvedTheme, setTheme, style, setStyle }),
|
|
||||||
[theme, resolvedTheme, setTheme, style, setStyle],
|
|
||||||
)
|
|
||||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,7 @@ function AlertDialogContent({
|
||||||
data-slot="alert-dialog-content"
|
data-slot="alert-dialog-content"
|
||||||
data-size={size}
|
data-size={size}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-card p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
|
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|
|
||||||
|
|
@ -10,19 +10,16 @@ import {
|
||||||
DayPicker,
|
DayPicker,
|
||||||
getDefaultClassNames,
|
getDefaultClassNames,
|
||||||
type DayButton,
|
type DayButton,
|
||||||
type DropdownProps,
|
|
||||||
} from "react-day-picker"
|
} from "react-day-picker"
|
||||||
import { ru } from "react-day-picker/locale"
|
import { ru } from "react-day-picker/locale"
|
||||||
|
|
||||||
import { Button, buttonVariants } from "./button"
|
import { Button, buttonVariants } from "./button"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./select"
|
|
||||||
|
|
||||||
function Calendar({
|
function Calendar({
|
||||||
className,
|
className,
|
||||||
classNames,
|
classNames,
|
||||||
showOutsideDays = true,
|
showOutsideDays = true,
|
||||||
captionLayout = "label",
|
captionLayout = "label",
|
||||||
yearCaption = "select",
|
|
||||||
buttonVariant = "ghost",
|
buttonVariant = "ghost",
|
||||||
formatters,
|
formatters,
|
||||||
components,
|
components,
|
||||||
|
|
@ -30,8 +27,6 @@ function Calendar({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DayPicker> & {
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
/** Год в шапке: список или поле из четырёх цифр. Вместе с captionLayout="dropdown". */
|
|
||||||
yearCaption?: "select" | "input"
|
|
||||||
}) {
|
}) {
|
||||||
const defaultClassNames = getDefaultClassNames()
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
|
@ -59,18 +54,17 @@ function Calendar({
|
||||||
),
|
),
|
||||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||||
nav: cn(
|
nav: cn(
|
||||||
// Полоса на всю ширину шапки: клики в середине должны попадать в списки месяца и года.
|
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||||
"pointer-events-none absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
|
||||||
defaultClassNames.nav
|
defaultClassNames.nav
|
||||||
),
|
),
|
||||||
button_previous: cn(
|
button_previous: cn(
|
||||||
buttonVariants({ variant: buttonVariant }),
|
buttonVariants({ variant: buttonVariant }),
|
||||||
"pointer-events-auto size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
defaultClassNames.button_previous
|
defaultClassNames.button_previous
|
||||||
),
|
),
|
||||||
button_next: cn(
|
button_next: cn(
|
||||||
buttonVariants({ variant: buttonVariant }),
|
buttonVariants({ variant: buttonVariant }),
|
||||||
"pointer-events-auto size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
defaultClassNames.button_next
|
defaultClassNames.button_next
|
||||||
),
|
),
|
||||||
month_caption: cn(
|
month_caption: cn(
|
||||||
|
|
@ -78,7 +72,7 @@ function Calendar({
|
||||||
defaultClassNames.month_caption
|
defaultClassNames.month_caption
|
||||||
),
|
),
|
||||||
dropdowns: cn(
|
dropdowns: cn(
|
||||||
"relative z-10 flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||||
defaultClassNames.dropdowns
|
defaultClassNames.dropdowns
|
||||||
),
|
),
|
||||||
dropdown_root: cn(
|
dropdown_root: cn(
|
||||||
|
|
@ -170,7 +164,6 @@ function Calendar({
|
||||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
Dropdown: (dropdownProps) => <CalendarDropdown {...dropdownProps} yearCaption={yearCaption} />,
|
|
||||||
DayButton: CalendarDayButton,
|
DayButton: CalendarDayButton,
|
||||||
WeekNumber: ({ children, ...props }) => {
|
WeekNumber: ({ children, ...props }) => {
|
||||||
return (
|
return (
|
||||||
|
|
@ -188,93 +181,6 @@ function Calendar({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyDropdownChange(onChange: DropdownProps["onChange"], value: string) {
|
|
||||||
onChange?.({ target: { value } } as React.ChangeEvent<HTMLSelectElement>)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Год отличается от месяца тем, что значения опций — сами годы, а не 0–11. */
|
|
||||||
function isYearDropdown(options: DropdownProps["options"]) {
|
|
||||||
return options?.some((option) => option.value > 99) ?? false
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Месяц и год в шапке: список кита вместо нативного select. Год можно заменить полем. */
|
|
||||||
function CalendarDropdown({
|
|
||||||
options,
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
disabled,
|
|
||||||
"aria-label": ariaLabel,
|
|
||||||
yearCaption,
|
|
||||||
}: DropdownProps & { yearCaption?: "select" | "input" }) {
|
|
||||||
if (yearCaption === "input" && isYearDropdown(options)) {
|
|
||||||
return (
|
|
||||||
<CalendarYearInput
|
|
||||||
options={options}
|
|
||||||
value={value}
|
|
||||||
onChange={onChange}
|
|
||||||
disabled={disabled}
|
|
||||||
aria-label={ariaLabel}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<Select
|
|
||||||
value={value == null ? undefined : String(value)}
|
|
||||||
disabled={disabled}
|
|
||||||
onValueChange={(next) => applyDropdownChange(onChange, next)}
|
|
||||||
>
|
|
||||||
<SelectTrigger size="sm" aria-label={ariaLabel} className="h-8 gap-1 px-2 font-normal shadow-none">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent className="z-[60]">
|
|
||||||
{options?.map((option) => (
|
|
||||||
<SelectItem key={option.value} value={String(option.value)} disabled={option.disabled}>
|
|
||||||
{option.label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Четыре цифры года: сетка переключается, когда год есть в доступных границах. */
|
|
||||||
function CalendarYearInput({
|
|
||||||
options,
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
disabled,
|
|
||||||
"aria-label": ariaLabel,
|
|
||||||
}: Pick<DropdownProps, "options" | "value" | "onChange" | "disabled" | "aria-label">) {
|
|
||||||
const year = value == null ? "" : String(value)
|
|
||||||
const [draft, setDraft] = React.useState<string | null>(null)
|
|
||||||
const allowed = new Set(options?.filter((option) => !option.disabled).map((option) => String(option.value)))
|
|
||||||
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
inputMode="numeric"
|
|
||||||
autoComplete="off"
|
|
||||||
maxLength={4}
|
|
||||||
aria-label={ariaLabel}
|
|
||||||
disabled={disabled}
|
|
||||||
value={draft ?? year}
|
|
||||||
onChange={(e) => {
|
|
||||||
const next = e.target.value.replace(/\D/g, "").slice(0, 4)
|
|
||||||
setDraft(next)
|
|
||||||
if (next.length === 4 && allowed.has(next)) {
|
|
||||||
applyDropdownChange(onChange, next)
|
|
||||||
setDraft(null)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onFocus={(e) => e.currentTarget.select()}
|
|
||||||
onBlur={() => setDraft(null)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key.startsWith("Arrow")) e.stopPropagation()
|
|
||||||
}}
|
|
||||||
className="h-8 w-16 rounded-md border border-input bg-transparent text-center text-sm tabular shadow-none outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CalendarDayButton({
|
function CalendarDayButton({
|
||||||
className,
|
className,
|
||||||
day,
|
day,
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ function DialogContent({
|
||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content
|
||||||
data-slot="dialog-content"
|
data-slot="dialog-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-card p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|
|
||||||
|
|
@ -1,35 +1,18 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { useFormControl } from "../lib/form-control"
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
type InputProps = React.ComponentProps<"input"> & {
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
"data-slot"?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function Input({
|
|
||||||
className,
|
|
||||||
type,
|
|
||||||
id,
|
|
||||||
"aria-describedby": ariaDescribedBy,
|
|
||||||
"aria-invalid": ariaInvalid,
|
|
||||||
"data-slot": dataSlot = "input",
|
|
||||||
...props
|
|
||||||
}: InputProps) {
|
|
||||||
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
|
||||||
return (
|
return (
|
||||||
<input
|
<input
|
||||||
{...props}
|
|
||||||
type={type}
|
type={type}
|
||||||
id={field.id}
|
data-slot="input"
|
||||||
aria-describedby={field["aria-describedby"]}
|
|
||||||
aria-invalid={field["aria-invalid"]}
|
|
||||||
data-slot={dataSlot}
|
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,12 +15,6 @@ function PopoverTrigger({
|
||||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||||
}
|
}
|
||||||
|
|
||||||
function PopoverClose({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof PopoverPrimitive.Close>) {
|
|
||||||
return <PopoverPrimitive.Close data-slot="popover-close" {...props} />
|
|
||||||
}
|
|
||||||
|
|
||||||
function PopoverContent({
|
function PopoverContent({
|
||||||
className,
|
className,
|
||||||
align = "center",
|
align = "center",
|
||||||
|
|
@ -85,7 +79,6 @@ function PopoverDescription({
|
||||||
export {
|
export {
|
||||||
Popover,
|
Popover,
|
||||||
PopoverTrigger,
|
PopoverTrigger,
|
||||||
PopoverClose,
|
|
||||||
PopoverContent,
|
PopoverContent,
|
||||||
PopoverAnchor,
|
PopoverAnchor,
|
||||||
PopoverHeader,
|
PopoverHeader,
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,7 @@ function SheetContent({
|
||||||
<SheetPrimitive.Content
|
<SheetPrimitive.Content
|
||||||
data-slot="sheet-content"
|
data-slot="sheet-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed z-50 flex flex-col gap-4 bg-card shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
|
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
|
||||||
side === "right" &&
|
side === "right" &&
|
||||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||||
side === "left" &&
|
side === "left" &&
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ function Switch({
|
||||||
<SwitchPrimitive.Thumb
|
<SwitchPrimitive.Thumb
|
||||||
data-slot="switch-thumb"
|
data-slot="switch-thumb"
|
||||||
className={cn(
|
className={cn(
|
||||||
"pointer-events-none block rounded-full bg-card shadow-xs ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"
|
"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</SwitchPrimitive.Root>
|
</SwitchPrimitive.Root>
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,15 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { useFormControl } from "../lib/form-control"
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
type TextareaProps = React.ComponentProps<"textarea"> & {
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||||
"data-slot"?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function Textarea({
|
|
||||||
className,
|
|
||||||
id,
|
|
||||||
"aria-describedby": ariaDescribedBy,
|
|
||||||
"aria-invalid": ariaInvalid,
|
|
||||||
"data-slot": dataSlot = "textarea",
|
|
||||||
...props
|
|
||||||
}: TextareaProps) {
|
|
||||||
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
|
||||||
return (
|
return (
|
||||||
<textarea
|
<textarea
|
||||||
{...props}
|
data-slot="textarea"
|
||||||
id={field.id}
|
|
||||||
aria-describedby={field["aria-describedby"]}
|
|
||||||
aria-invalid={field["aria-invalid"]}
|
|
||||||
data-slot={dataSlot}
|
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
import { defineConfig } from "vitest/config"
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
environment: "node",
|
|
||||||
include: ["src/**/*.test.{ts,tsx}"],
|
|
||||||
},
|
|
||||||
})
|
|
||||||
Loading…
Reference in New Issue